jennyxue commited on
Commit
141c3a6
·
verified ·
1 Parent(s): c890752

bf16 build of Real-ESRGAN

Browse files
Files changed (3) hide show
  1. bf16/config.json +10 -0
  2. bf16/mlx_model.py +124 -0
  3. bf16/model.safetensors +3 -0
bf16/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "rrdbnet",
3
+ "num_in_ch": 3,
4
+ "num_out_ch": 3,
5
+ "num_feat": 64,
6
+ "num_block": 23,
7
+ "num_grow_ch": 32,
8
+ "scale": 4,
9
+ "precision": "bf16"
10
+ }
bf16/mlx_model.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real-ESRGAN x4plus (RRDBNet) in MLX: a port of basicsr's `RRDBNet` (xinntao/Real-ESRGAN, BSD-3-Clause).
2
+
3
+ import mlx_model
4
+ model = mlx_model.load("bf16") # a folder with config.json + model.safetensors
5
+ out = mlx_model.upscale(model, rgb) # rgb: HxWx3 uint8 numpy -> (4H)x(4W)x3 uint8
6
+
7
+ Runs on its own next to its weights (only mlx and numpy). NHWC throughout; the weights are the original
8
+ `params_ema` with each conv kernel transposed to MLX's (out, kh, kw, in).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from pathlib import Path
15
+
16
+ import mlx.core as mx
17
+ import mlx.nn as nn
18
+ import numpy as np
19
+
20
+ CONFIG = {"model_type": "rrdbnet", "num_in_ch": 3, "num_out_ch": 3, "num_feat": 64, "num_block": 23,
21
+ "num_grow_ch": 32, "scale": 4}
22
+ # Every layer is a convolution, which MLX can't quantize: only bf16 / fp16 (lab/zoo/real-esrgan/model.toml).
23
+ PRECISIONS = ["bf16", "fp16"]
24
+
25
+
26
+ def lrelu(x):
27
+ return nn.leaky_relu(x, 0.2)
28
+
29
+
30
+ class RDB(nn.Module):
31
+ def __init__(self, f: int, g: int):
32
+ super().__init__()
33
+ self.conv1 = nn.Conv2d(f, g, 3, padding=1)
34
+ self.conv2 = nn.Conv2d(f + g, g, 3, padding=1)
35
+ self.conv3 = nn.Conv2d(f + 2 * g, g, 3, padding=1)
36
+ self.conv4 = nn.Conv2d(f + 3 * g, g, 3, padding=1)
37
+ self.conv5 = nn.Conv2d(f + 4 * g, f, 3, padding=1)
38
+
39
+ def __call__(self, x):
40
+ x1 = lrelu(self.conv1(x))
41
+ x2 = lrelu(self.conv2(mx.concatenate([x, x1], -1)))
42
+ x3 = lrelu(self.conv3(mx.concatenate([x, x1, x2], -1)))
43
+ x4 = lrelu(self.conv4(mx.concatenate([x, x1, x2, x3], -1)))
44
+ x5 = self.conv5(mx.concatenate([x, x1, x2, x3, x4], -1))
45
+ return x5 * 0.2 + x
46
+
47
+
48
+ class RRDB(nn.Module):
49
+ def __init__(self, f: int, g: int):
50
+ super().__init__()
51
+ self.rdb1, self.rdb2, self.rdb3 = RDB(f, g), RDB(f, g), RDB(f, g)
52
+
53
+ def __call__(self, x):
54
+ return self.rdb3(self.rdb2(self.rdb1(x))) * 0.2 + x
55
+
56
+
57
+ def up2(x):
58
+ """Nearest-neighbour x2 (NHWC)."""
59
+ b, h, w, c = x.shape
60
+ x = mx.broadcast_to(x[:, :, None, :, None, :], (b, h, 2, w, 2, c))
61
+ return x.reshape(b, h * 2, w * 2, c)
62
+
63
+
64
+ class Model(nn.Module):
65
+ def __init__(self, config: dict = CONFIG):
66
+ super().__init__()
67
+ f, g, cin, cout = config["num_feat"], config["num_grow_ch"], config["num_in_ch"], config["num_out_ch"]
68
+ self.scale = config["scale"]
69
+ assert self.scale == 4, "x4plus only (x2 needs basicsr's pixel_unshuffle input)"
70
+ self.conv_first = nn.Conv2d(cin, f, 3, padding=1)
71
+ self.body = [RRDB(f, g) for _ in range(config["num_block"])]
72
+ self.conv_body = nn.Conv2d(f, f, 3, padding=1)
73
+ self.conv_up1 = nn.Conv2d(f, f, 3, padding=1)
74
+ self.conv_up2 = nn.Conv2d(f, f, 3, padding=1)
75
+ self.conv_hr = nn.Conv2d(f, f, 3, padding=1)
76
+ self.conv_last = nn.Conv2d(f, cout, 3, padding=1)
77
+
78
+ def __call__(self, x):
79
+ """x: (B, H, W, 3) in [0, 1] -> (B, 4H, 4W, 3)."""
80
+ feat = self.conv_first(x)
81
+ body = feat
82
+ for blk in self.body:
83
+ body = blk(body)
84
+ feat = feat + self.conv_body(body)
85
+ feat = lrelu(self.conv_up1(up2(feat)))
86
+ feat = lrelu(self.conv_up2(up2(feat)))
87
+ return self.conv_last(lrelu(self.conv_hr(feat)))
88
+
89
+
90
+ def load(folder) -> Model:
91
+ folder = Path(folder)
92
+ config = json.loads((folder / "config.json").read_text())
93
+ model = Model(config)
94
+ model.load_weights(str(folder / "model.safetensors"), strict=True)
95
+ mx.eval(model.parameters())
96
+ return model
97
+
98
+
99
+ def upscale(model: Model, rgb: np.ndarray, tile: int = 256, pad: int = 16) -> np.ndarray:
100
+ """HxWx3 uint8 -> (4H)x(4W)x3 uint8, in tiles of `tile` input pixels (overlap `pad`) to bound memory."""
101
+ dt = model.conv_first.weight.dtype
102
+ x = rgb.astype(np.float32) / 255.0
103
+ h, w, _ = x.shape
104
+ s = model.scale
105
+ out = np.zeros((h * s, w * s, 3), np.float32)
106
+ for y0 in range(0, h, tile):
107
+ for x0 in range(0, w, tile):
108
+ y1, x1 = min(y0 + tile, h), min(x0 + tile, w)
109
+ ya, xa, yb, xb = max(y0 - pad, 0), max(x0 - pad, 0), min(y1 + pad, h), min(x1 + pad, w)
110
+ t = mx.array(x[None, ya:yb, xa:xb]).astype(dt)
111
+ o = np.array(model(t).astype(mx.float32))[0]
112
+ out[y0 * s:y1 * s, x0 * s:x1 * s] = o[(y0 - ya) * s:(y1 - ya) * s, (x0 - xa) * s:(x1 - xa) * s]
113
+ return (np.clip(out, 0, 1) * 255.0).round().astype(np.uint8)
114
+
115
+
116
+ def convert(source: Path) -> dict:
117
+ """runs/source/RealESRGAN_x4plus.pth (params_ema) -> MLX names and layouts, float32."""
118
+ import torch
119
+ sd = torch.load(Path(source) / "RealESRGAN_x4plus.pth", map_location="cpu", weights_only=True)["params_ema"]
120
+ out = {}
121
+ for k, v in sd.items():
122
+ a = v.float().numpy()
123
+ out[k] = a.transpose(0, 2, 3, 1) if a.ndim == 4 else a
124
+ return out
bf16/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c21e6b4f63ffaf7d9ff53cd8ba832f5146a9591e210c31f6450eb81e7411f6ff
3
+ size 33462410