Real-ESRGAN converts to Core ML without much drama. The hard part comes after: the converted model wants a small fixed input, your users drop in a 4000 x 3000 photo, and the output at 4x is 192 megapixels. This post is how I run these models on big images on Apple silicon: tiling with overlap, hiding seams, keeping memory in check, and picking compute units. All code is Swift and was compiled and run on an M3 Pro with 18 GB under macOS 27.2.
The model: fixed 256 x 256 input
I converted the Real-ESRGAN networks (RRDBNet for x4plus, SRVGGNetCompact for general-x4v3) with coremltools to an ML Program in FP16, with a fixed 256 x 256 input named x and output y. I stuck to a fixed shape. It keeps memory per call predictable, and I did not want to find out which flexible-shape setups stay on the Neural Engine.
Compile once and load with explicit compute units:
import CoreML func compileOnce(_ packageURL: URL) async throws -> URL { // Returns a temporary .mlmodelc. Move it somewhere permanent, // or let Xcode compile the model into your app bundle instead. try await MLModel.compileModel(at: packageURL) } func loadModel(compiledAt url: URL, units: MLComputeUnits) throws -> MLModel { let cfg = MLModelConfiguration() cfg.computeUnits = units // .cpuAndNeuralEngine, .cpuAndGPU, .all, .cpuOnly return try MLModel(contentsOf: url, configuration: cfg) } On macOS 14 and later you can ask whether a Neural Engine is present at all:
func hasNeuralEngine() -> Bool { MLModel.availableComputeDevices.contains { device in if case .neuralEngine = device { return true } return false } } A macOS virtual machine has no Neural Engine, which is worth knowing if you test there: my VM runs went to the CPU and were much slower.
Why naive tiling leaves seams
The obvious approach is to cut the image into 256 x 256 squares, upscale each, and paste them back. You get a visible grid. Each output pixel depends on a neighbourhood of input pixels, and at a tile border half that neighbourhood is missing, so the network sees padding instead of real image content. Colours and textures drift slightly at every edge.
The fix is to give every tile context it will not keep. I use a 16 pixel margin on each side, so each 256 pixel tile contributes only its central 224 pixels:
let tile = 256 // the model's fixed input edge let pad = 16 // context on each side, discarded after inference let step = tile - 2 * pad // 224 new pixels per tile Tiles start every 224 pixels and read 16 pixels beyond their area on each side. At the image border there is nothing to read, so I mirror the image instead of padding with black. Reflect padding looks like plausible image content to the network; zero padding looks like a black frame, and the model happily sharpens it.
func mirror(_ i: Int, _ n: Int) -> Int { if n == 1 { return 0 } var i = i while i < 0 || i >= n { if i < 0 { i = -i } if i >= n { i = 2 * (n - 1) - i } } return i } mirror(-3, 4) gives 3, mirror(4, 4) gives 2: indices bounce off the edges without repeating the edge pixel.
Filling a tile
The model takes NCHW float32 in 0...1. I reuse one MLMultiArray for every tile instead of allocating per call:
struct RGB8 { // interleaved RGB, 3 bytes per pixel let width: Int, height: Int var pixels: [UInt8] } func fillTile(_ input: MLMultiArray, from src: RGB8, x0: Int, y0: Int) { let p = input.dataPointer.assumingMemoryBound(to: Float.self) let plane = tile * tile src.pixels.withUnsafeBufferPointer { px in for yy in 0..<tile { let sy = mirror(y0 - pad + yy, src.height) for xx in 0..<tile { let sx = mirror(x0 - pad + xx, src.width) let s = (sy * src.width + sx) * 3 let o = yy * tile + xx p[o] = Float(px[s]) / 255 p[plane + o] = Float(px[s + 1]) / 255 p[2 * plane + o] = Float(px[s + 2]) / 255 } } } } Reading the output: it may be Float16
An FP16 ML Program can hand back a Float16 MLMultiArray. Don't assume float32. I convert the whole tile at once with vImage, which also works on Intel Macs where Swift's Float16 type is not available:
import Accelerate func floats(_ y: MLMultiArray, into buffer: UnsafeMutablePointer<Float>) -> UnsafePointer<Float>? { switch y.dataType { case .float32: return UnsafePointer(y.dataPointer.assumingMemoryBound(to: Float.self)) case .float16: let n = y.count var s = vImage_Buffer(data: y.dataPointer, height: 1, width: vImagePixelCount(n), rowBytes: n * 2) var d = vImage_Buffer(data: buffer, height: 1, width: vImagePixelCount(n), rowBytes: n * 4) vImageConvert_Planar16FtoPlanarF(&s, &d, 0) return UnsafePointer(buffer) default: return nil } } The tile loop, crop strategy
Run the model, then copy only the centre of each output tile (the margin times the scale is thrown away):
func upscale(_ src: RGB8, model: MLModel, scale: Int) throws -> RGB8 { var out = RGB8(width: src.width * scale, height: src.height * scale, pixels: <a href="repeating: 0, count: src.width * scale * src.height * scale * 3">UInt8</a>) let input = try MLMultiArray(shape: [1, 3, NSNumber(value: tile), NSNumber(value: tile)], dataType: .float32) let outTile = tile * scale let buffer = UnsafeMutablePointer<Float>.allocate(capacity: 3 * outTile * outTile) defer { buffer.deallocate() } for y0 in stride(from: 0, to: src.height, by: step) { for x0 in stride(from: 0, to: src.width, by: step) { fillTile(input, from: src, x0: x0, y0: y0) let result = try autoreleasepool { try model.prediction(from: MLDictionaryFeatureProvider( dictionary: ["x": MLFeatureValue(multiArray: input)])) } guard let y = result.featureValue(for: "y")?.multiArrayValue, let f = floats(y, into: buffer) else { throw CocoaError(.featureUnsupported) } let validW = min(step, src.width - x0) * scale let validH = min(step, src.height - y0) * scale let n = outTile * outTile let off = pad * scale for oy in 0..<validH { let dRow = ((y0 * scale + oy) * out.width + x0 * scale) * 3 let sRow = (off + oy) * outTile + off for ox in 0..<validW { for c in 0..<3 { let v = f[c * n + sRow + ox] * 255 + 0.5 out.pixels[dRow + ox * 3 + c] = UInt8(max(0, min(255, v))) } } } } } return out } The autoreleasepool around prediction is cheap insurance in long loops: without it, autoreleased objects created per call can pile up until the whole loop ends.
Partial tiles at the right and bottom edges just copy fewer pixels; the mirror function fills the rest of the input.
Crop or blend?
The other common approach is to overlap tiles and blend them with a feathered weight that ramps from near 0 at a tile edge to 1 in the middle:
func featherWeight(_ i: Int, length: Int, ramp: Int) -> Float { let d = min(i, length - 1 - i) // distance to the nearest tile edge return d >= ramp ? 1 : Float(d + 1) / Float(ramp + 1) } You accumulate value * weight and weight per output pixel and divide at the end. It hides seams very well, even with a smaller margin. The cost is memory: the accumulators are floats for the whole output. For a 192 megapixel result that is about 2.3 GB for the RGB sums plus another 0.77 GB for the weights, on top of the 576 MB 8-bit output. I went with crop because the margin already discards the worst edge pixels and the memory stays at the output buffer plus one tile. If your model shows seams with crop, raise pad first; blending is the fallback.
Memory: the output is the problem
The model is small (2.4 MB for general-x4v3, 33 MB for x4plus in FP16). Tile buffers are a few megabytes. The full-size output is what hurts: 16000 x 12000 x 3 bytes is 576 MB, and many image writers want their own copy. A few rules I follow:
- Cap the output. I refuse anything above about 200 megapixels or 32768 pixels on a side.
- Keep one input array and one float buffer for the whole job.
- Check free disk space before writing, since a 192 MP PNG is large.
- For really large outputs, write strips to disk as tiles finish instead of holding the full image. I have not needed that yet at 200 MP on an 18 GB Mac, so treat it as an option rather than advice.
Measured with /usr/bin/time -l, the benchmark below (two models, three compute unit settings, 1024 x 768 input to 4096 x 3072) peaked at about 460 MB resident.
ANE vs GPU: measure, don't guess
Here is a simple benchmark. The first run per configuration includes on-device compilation for that compute unit, so warm up before timing:
func timeUnits(_ url: URL, image: RGB8) throws { for (name, units) in [("CPU+ANE", MLComputeUnits.cpuAndNeuralEngine), ("CPU+GPU", .cpuAndGPU), ("all", .all)] { let model = try loadModel(compiledAt: url, units: units) _ = try upscale(image, model: model, scale: 4) // warm-up let t0 = CFAbsoluteTimeGetCurrent() _ = try upscale(image, model: model, scale: 4) print(name, String(format: "%.2f s", CFAbsoluteTimeGetCurrent() - t0)) } } On my M3 Pro, a 1024 x 768 image (20 tiles) at 4x:
| Model | CPU+ANE | CPU+GPU | all |
|---|---|---|---|
| realesr-general-x4v3 (compact) | 0.46 s | 0.53 s | 0.46 s |
| RealESRGAN_x4plus (RRDBNet) | 3.45 s | 8.63 s | 4.70 s |
An earlier test with a 4000 x 3000 photo at 4x (252 tiles) and x4plus showed the same pattern: 49 s on CPU+ANE, 63 s with .all, 111 s on CPU+GPU.
Two things stand out. For the small compact model the choice barely matters. For the big RRDBNet model, the Neural Engine was about 2.5 times faster than the GPU, and .all landed in between, so letting Core ML decide was not the fastest option here. I would not generalise that to every Mac or every model; the M-series GPUs differ a lot in size. The point is that the benchmark takes ten minutes to write and the answer can be a factor of two.
Summary
- Convert with a fixed input tile, FP16.
- Tile with a margin (I use 256 with 16 px each side), reflect-pad at image borders, keep the centre.
- Handle Float16 output; reuse buffers; wrap predictions in
autoreleasepool. - Blend only if crop shows seams; it costs a lot of memory at large sizes.
- Benchmark
.cpuAndNeuralEngineagainst.cpuAndGPUand.allon your model.
Disclosure: I make Upsharp, a Mac app that upscales photos, scans and art on-device with Real-ESRGAN Core ML models, using the tiling approach above. The download is free for 2x with the Fast model, and a one-time licence adds 4x, 8x, the larger models and batches: Upsharp.
Written with help from an AI assistant; code and commands were tested on macOS.
