sebekblessing commited on
Commit
172e6ba
·
verified ·
1 Parent(s): 9c46558

Fibo 2.0 edit for phone graphics chips: engine weights, small encoder and decoder, reader, file list

Browse files
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ files/fibo_q8.gguf filter=lfs diff=lfs merge=lfs -text
37
+ files/tae_f2.gguf filter=lfs diff=lfs merge=lfs -text
38
+ files/taee_f2.gguf filter=lfs diff=lfs merge=lfs -text
39
+ files/fibo_reader.gguf filter=lfs diff=lfs merge=lfs -text
40
+ files/fibo_reader_mmproj.gguf filter=lfs diff=lfs merge=lfs -text
LICENSE.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licence
2
+
3
+ The Fibo 2.0 model weights, and the files in `files/` made from them, are licensed under
4
+ **Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)**.
5
+ Full text: https://creativecommons.org/licenses/by-nc/4.0/legalcode
6
+
7
+ You may share and adapt them for non-commercial purposes only, giving credit to BRIA AI and noting that changes were
8
+ made. See NOTICE for what each file is made from and the licences of the other parts.
9
+
10
+ The build scripts in `build/` are shared as-is, without any warranty.
NOTICE ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Fibo 2.0 model weights are (c) BRIA AI and licensed under Creative Commons Attribution-NonCommercial 4.0
2
+ International (CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/
3
+
4
+ The files in files/ are modified: they are converted and quantized versions of
5
+ - Fibo 2.0 edit-turbo (briaai/Fibo-2.0-edit-turbo, via Comfy-Org/Fibo-2.0): fibo_q8.gguf (CC BY-NC 4.0),
6
+ - Qwen3-VL-4B's language model and vision tower (Apache License 2.0), as packaged in Comfy-Org/Fibo-2.0:
7
+ fibo_reader.gguf, fibo_reader_mmproj.gguf,
8
+ - taef2 by madebyollin (MIT License): taee_f2.gguf, tae_f2.gguf.
README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ base_model:
4
+ - briaai/Fibo-2.0-edit-turbo
5
+ tags:
6
+ - image-editing
7
+ - android
8
+ - opencl
9
+ ---
10
+
11
+ # Fibo 2.0 edit for phone graphics chips
12
+
13
+ Files the Anima Android app downloads to edit pictures with Fibo 2.0 (edit-turbo, 4 steps) on a phone's graphics
14
+ chip, on phones that have no Snapdragon AI chip the app supports. Phones with a Snapdragon 8 Elite or 8 Elite Gen 5
15
+ use the AI-chip build in `fibo-qnn-8elite` / `fibo-qnn-8elite-gen5` instead, which is faster.
16
+
17
+ | File | What it is |
18
+ | --- | --- |
19
+ | `files/fibo_q8.gguf` | Fibo 2.0 edit-turbo, 8-bit, in the app engine's own layout. Read one block at a time while drawing. |
20
+ | `files/fibo_reader.gguf` | The prompt reader, Qwen3-VL-4B, 8-bit (Q8_0), for llama.cpp. Runs on the phone's processor. |
21
+ | `files/fibo_reader_mmproj.gguf` | The reader's picture part (fp16), for llama.cpp. |
22
+ | `files/taee_f2.gguf`, `files/tae_f2.gguf` | The small Flux 2 picture encoder and decoder (taef2 by madebyollin) in the engine's layout. |
23
+ | `files/sigmas.txt` | The 4 noise levels of the edit-turbo model. |
24
+ | `manifest.json` | The file list the app reads (name, size, SHA-256). |
25
+
26
+ `build/pack_fibo.py` and `build/pack_tae.py` made the engine files (the encoder with `ENC=1`); `build/fibotaps.cpp` is
27
+ the reader program, which hands Fibo the 15 inner layers of the reader that ComfyUI's Fibo text encoder uses.
28
+
29
+ **Non-commercial use only** (CC BY-NC 4.0, see LICENSE.md and NOTICE). Qwen3-VL, Apache 2.0. taef2, MIT.
build/fibotaps.cpp ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Fibo 2.0's prompt reader on the processor (llama.cpp): Qwen3-VL-4B reads the edit instruction with the picture to
2
+ // edit, and 15 of its inner states are handed to Fibo, as ComfyUI's Fibo2TEModel does (comfy/text_encoders/fibo2.py):
3
+ // the stream before layers 5, 7, 9, 11, 13, 16, 18, 20, 22, 24, 27, 29, 31, 33, 35 (= llama.cpp's "l_out-<n - 1>"),
4
+ // each at unit RMS (no weight, eps 1e-6) and rounded to bf16, laid out as six bundles of three.
5
+ //
6
+ // fibotaps <reader.gguf> <mmproj.gguf> <picture.rgb> <width> <height> <instruction file> <out dir> [threads]
7
+ //
8
+ // picture.rgb: raw 8-bit RGB rows (the app's 768 x 768 picture). Writes <out>/ctx.f32 (T x 46080) and <out>/info.txt
9
+ // "T G h w" for the engine (h, w = the drawing's latent rows: picture / 16). Exit code 0 on success.
10
+ #include "llama.h"
11
+ #include "mtmd.h"
12
+ #include "mtmd-helper.h"
13
+
14
+ #include <chrono>
15
+ #include <cmath>
16
+ #include <cstdio>
17
+ #include <cstdlib>
18
+ #include <cstring>
19
+ #include <map>
20
+ #include <string>
21
+ #include <vector>
22
+
23
+ static const int BUNDLES[6][3] = {{9, 20, 31}, {5, 16, 27}, {7, 18, 29}, {9, 20, 31}, {11, 22, 33}, {13, 24, 35}};
24
+ static const int TAPS[15] = {5, 7, 9, 11, 13, 16, 18, 20, 22, 24, 27, 29, 31, 33, 35};
25
+ static const int MAXG = 512;
26
+
27
+ struct Taps {
28
+ int n_embd = 0;
29
+ std::map<int, std::vector<float>> rows; // tap layer -> rows x n_embd, in the order the reader ran them
30
+ };
31
+
32
+ // asked for every node; keeps the outputs of the layers just before a tap
33
+ static bool onTensor(struct ggml_tensor *t, bool ask, void *ud) {
34
+ auto *tp = (Taps *)ud;
35
+ int il = -1;
36
+ if (sscanf(t->name, "l_out-%d", &il) != 1) return ask ? false : true;
37
+ const int tap = il + 1;
38
+ bool want = false;
39
+ for (int x : TAPS) want |= x == tap;
40
+ if (ask) return want;
41
+ if (!want) return true;
42
+ if (t->type != GGML_TYPE_F32) { fprintf(stderr, "l_out-%d is not f32\n", il); return false; }
43
+ const int ne0 = (int)t->ne[0], ne1 = (int)t->ne[1];
44
+ tp->n_embd = ne0;
45
+ auto &v = tp->rows[tap];
46
+ const size_t at = v.size();
47
+ v.resize(at + (size_t)ne0 * ne1);
48
+ ggml_backend_tensor_get(t, v.data() + at, 0, (size_t)ne0 * ne1 * sizeof(float));
49
+ return true;
50
+ }
51
+
52
+ static float bf16(float x) { // round to nearest even, as torch's .to(bfloat16)
53
+ uint32_t u; memcpy(&u, &x, 4);
54
+ u += 0x7FFF + ((u >> 16) & 1);
55
+ u &= 0xFFFF0000u;
56
+ float y; memcpy(&y, &u, 4); return y;
57
+ }
58
+
59
+ static std::string jsonString(const std::string &s) { // as Python's json.dumps(..., ensure_ascii=False)
60
+ std::string o = "\"";
61
+ for (unsigned char c : s) {
62
+ switch (c) {
63
+ case '"': o += "\\\""; break;
64
+ case '\\': o += "\\\\"; break;
65
+ case '\n': o += "\\n"; break;
66
+ case '\r': o += "\\r"; break;
67
+ case '\t': o += "\\t"; break;
68
+ case '\b': o += "\\b"; break;
69
+ case '\f': o += "\\f"; break;
70
+ default:
71
+ if (c < 0x20) { char b[8]; snprintf(b, sizeof b, "\\u%04x", c); o += b; }
72
+ else o += (char)c;
73
+ }
74
+ }
75
+ return o + "\"";
76
+ }
77
+
78
+ int main(int argc, char **argv) {
79
+ if (argc < 8) {
80
+ fprintf(stderr, "usage: %s <reader.gguf> <mmproj.gguf> <picture.rgb> <width> <height> <instruction file> <out dir> [threads]\n", argv[0]);
81
+ return 1;
82
+ }
83
+ const char *modelPath = argv[1], *mmprojPath = argv[2], *picPath = argv[3], *instrPath = argv[6];
84
+ const int W = atoi(argv[4]), H = atoi(argv[5]);
85
+ const std::string out = argv[7];
86
+ const int threads = argc > 8 ? atoi(argv[8]) : 4;
87
+ auto t0 = std::chrono::steady_clock::now();
88
+ auto secs = [&]() { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); };
89
+
90
+ std::vector<unsigned char> rgb((size_t)W * H * 3);
91
+ { FILE *f = fopen(picPath, "rb");
92
+ if (!f || fread(rgb.data(), 1, rgb.size(), f) != rgb.size()) { fprintf(stderr, "cannot read %s (%dx%d RGB)\n", picPath, W, H); return 1; }
93
+ fclose(f); }
94
+ std::string instr;
95
+ { FILE *f = fopen(instrPath, "rb");
96
+ if (!f) { fprintf(stderr, "cannot read %s\n", instrPath); return 1; }
97
+ char b[4096]; size_t n; while ((n = fread(b, 1, sizeof b, f)) > 0) instr.append(b, n); fclose(f); }
98
+
99
+ llama_backend_init();
100
+ llama_model_params mp = llama_model_default_params();
101
+ mp.n_gpu_layers = 0; // the processor: this runs on phones without the AI chip
102
+ llama_model *model = llama_model_load_from_file(modelPath, mp);
103
+ if (!model) { fprintf(stderr, "cannot load %s\n", modelPath); return 1; }
104
+
105
+ Taps taps;
106
+ llama_context_params cp = llama_context_default_params();
107
+ cp.n_ctx = 2048; cp.n_batch = 1024; cp.n_ubatch = 1024; cp.n_threads = cp.n_threads_batch = threads;
108
+ cp.cb_eval = onTensor; cp.cb_eval_user_data = &taps;
109
+ llama_context *lctx = llama_init_from_model(model, cp);
110
+ if (!lctx) { fprintf(stderr, "cannot make the reader's context\n"); return 1; }
111
+
112
+ mtmd_context_params mcp = mtmd_context_params_default();
113
+ mcp.use_gpu = false; mcp.n_threads = threads; mcp.print_timings = false; mcp.warmup = false;
114
+ mtmd_context *mctx = mtmd_init_from_file(mmprojPath, model, mcp);
115
+ if (!mctx) { fprintf(stderr, "cannot load %s\n", mmprojPath); return 1; }
116
+ printf("loaded in %.1f s\n", secs()); fflush(stdout);
117
+
118
+ // {"image":"<picture>","edit_instruction":"..."} in the chat turn, as Fibo2Tokenizer writes it; mtmd puts
119
+ // <|vision_start|> ... <|vision_end|> around the picture's rows itself
120
+ const std::string prompt = std::string("<|im_start|>user\n{\"image\":\"") + mtmd_default_marker() +
121
+ "\",\"edit_instruction\":" + jsonString(instr) + "}<|im_end|>\n<|im_start|>assistant\n";
122
+ mtmd_bitmap *bmp = mtmd_bitmap_init(W, H, rgb.data());
123
+ mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true};
124
+ mtmd_input_chunks *chunks = mtmd_input_chunks_init();
125
+ const mtmd_bitmap *bl[1] = {bmp};
126
+ if (int r = mtmd_tokenize(mctx, chunks, &txt, bl, 1)) { fprintf(stderr, "tokenize failed (%d)\n", r); return 1; }
127
+ const size_t T = mtmd_helper_get_n_tokens(chunks);
128
+ printf("reading %zu rows\n", T); fflush(stdout);
129
+ llama_pos np = 0;
130
+ if (mtmd_helper_eval_chunks(mctx, lctx, chunks, 0, 0, cp.n_batch, false, &np)) { fprintf(stderr, "reading failed\n"); return 1; }
131
+ printf("read in %.1f s\n", secs()); fflush(stdout);
132
+
133
+ const int E = taps.n_embd;
134
+ for (int tap : TAPS) {
135
+ const size_t got = taps.rows[tap].size() / (E ? E : 1);
136
+ if (got != T) { fprintf(stderr, "layer %d gave %zu rows, not %zu\n", tap, got, T); return 1; }
137
+ }
138
+ // unit RMS + bf16 per tap, then the six bundles side by side per row
139
+ for (auto &kv : taps.rows) {
140
+ auto &v = kv.second;
141
+ for (size_t r = 0; r < T; r++) {
142
+ float *x = v.data() + r * E;
143
+ double ss = 0; for (int k = 0; k < E; k++) ss += (double)x[k] * x[k];
144
+ const float s = (float)(1.0 / std::sqrt(ss / E + 1e-6));
145
+ for (int k = 0; k < E; k++) x[k] = bf16(x[k] * s);
146
+ }
147
+ }
148
+ const size_t RW = (size_t)18 * E;
149
+ std::vector<float> ctx(T * RW);
150
+ for (size_t r = 0; r < T; r++)
151
+ for (int b = 0; b < 6; b++) for (int j = 0; j < 3; j++)
152
+ memcpy(&ctx[r * RW + (size_t)(b * 3 + j) * E], &taps.rows[BUNDLES[b][j]][r * E], E * sizeof(float));
153
+ FILE *f = fopen((out + "/ctx.f32").c_str(), "wb");
154
+ if (!f || fwrite(ctx.data(), sizeof(float), ctx.size(), f) != ctx.size()) { fprintf(stderr, "cannot write %s/ctx.f32\n", out.c_str()); return 1; }
155
+ fclose(f);
156
+ // Fibo's gist size grows with the prompt (fibo_model.gist_count)
157
+ const double rr = std::min(1.0, std::max(0.0, ((double)T - 256) / (2048 - 256)));
158
+ const int G = std::max(256, std::min(MAXG, (int)std::ceil((256 + rr * (MAXG - 256)) / 64) * 64));
159
+ f = fopen((out + "/info.txt").c_str(), "w");
160
+ fprintf(f, "%zu %d %d %d\n", T, G, H / 16, W / 16); fclose(f);
161
+ printf("done: %zu rows x %zu, gist %d, %.1f s\n", T, RW, G, secs());
162
+
163
+ mtmd_bitmap_free(bmp); mtmd_input_chunks_free(chunks); mtmd_free(mctx);
164
+ llama_free(lctx); llama_model_free(model); llama_backend_free();
165
+ return 0;
166
+ }
build/pack_fibo.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fibo 2.0 edit-turbo -> one GGUF for the universal phone engine (2026-11-18). 8-bit ConvRot (BITS=4 for 4-bit),
2
+ meant to be STREAMED (STREAM=1): ~8 GB, more than a phone holds at once.
3
+ Blocks are numbered in running order: b0, b1 = the noise refiner, b2..b45 = the 44 main layers (injection layers
4
+ 6, 14, 22, 30, 38 are b8, b16, b24, b32, b40).
5
+ Per block: qkv (q, k rows reordered to the half-split rotation layout), o, mlp_in ([gate 8][up 8] per 16 rows), down;
6
+ qn, kn (reordered); mod (4D x 256, fp16) + mod.b; the norm weights n1 n2 f1 f2 and z1 z2 zf1 zf2 = the same with the
7
+ t = 0 modulation folded in (for gist and edit-picture rows; gates through tanh). Injection blocks also: cq, ckv
8
+ (k rows then v rows, 7680 inputs), co, cqn, ckn, cn1, cn2 (= norm weight * tanh(gate)).
9
+ Perceiver p0 / p1: cq, ckv, co, cqn, ckn (cross to bundle 0), sq, skv, so, sqn, skn (self), mlp_in, down, cn, sn, fn;
10
+ queries (512 x D), pnorm. Small: x_in (padded to 256 inputs) + b, t1 t2 out_scale (fp16) + b, out + b.
11
+ Usage: python pack_fibo.py <out.gguf> (ComfyUI's ROCm venv)"""
12
+ import os
13
+ import sys
14
+ sys.path[:0] = ["/home/debian/gpu-engine-test/tsbuild/anima", "/home/debian/llama.cpp/gguf-py"]
15
+ import numpy as np
16
+ import torch
17
+ from safetensors import safe_open
18
+ import anima_qnn
19
+ import gguf
20
+
21
+ OUT = sys.argv[1]
22
+ GS, BITS = 32, int(os.environ.get("BITS", "8"))
23
+ SRC = "/home/debian/fibo-build/models/fibo2_edit_turbo_bf16.safetensors"
24
+ D, H, HD, FF, NL, NR = 3584, 28, 128, 9728, 44, 2
25
+ INJ = (6, 14, 22, 30, 38)
26
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
27
+ HT = anima_qnn._HT.to(dev)
28
+ f = safe_open(SRC, "pt")
29
+ pre = next((p for p in ("model.diffusion_model.", "") if f"{p}x_embedder.weight" in f.keys()), "")
30
+ g = lambda k: f.get_tensor(pre + k).to(dev).float()
31
+ writer = gguf.GGUFWriter(OUT, "ugpu")
32
+ index = []
33
+ PERM = torch.cat([torch.arange(0, HD, 2), torch.arange(1, HD, 2)]).to(dev)
34
+ FULL = torch.cat([h * HD + PERM for h in range(H)])
35
+
36
+ def put(name, kind, a, M, K):
37
+ writer.add_tensor(name, np.ascontiguousarray(a))
38
+ index.append(f"{name} {kind} {M} {K}")
39
+ def f16(name, w): put(name, "f16", w.half().contiguous().cpu().numpy(), *w.shape)
40
+ def f32(name, v): put(name, "f32", v.float().contiguous().cpu().numpy(), v.numel(), 1)
41
+ def rotw(w):
42
+ M, K = w.shape
43
+ return (w.reshape(M, K // HT.shape[0], HT.shape[0]) @ HT).reshape(M, K)
44
+ def q8(name, w, b=None):
45
+ M, K = w.shape
46
+ t = rotw(w).view(M, K // GS, GS)
47
+ s = t.abs().amax(-1, keepdim=True).clamp_min(1e-12) / 127
48
+ q = (t / s).round().clamp(-127, 127).to(torch.int8).view(M, K)
49
+ put(name, "q8", q.view(M, K // 16, 16).permute(1, 0, 2).contiguous().cpu().numpy(), M, K)
50
+ put(name + ".s", "qs", s.view(M, K // GS).contiguous().cpu().numpy().astype(np.float32), M, K // GS)
51
+ if b is not None: f32(name + ".b", b)
52
+ def q4(name, w, b=None):
53
+ M, K = w.shape
54
+ t = rotw(w).view(M, K // GS, GS)
55
+ s = t.abs().amax(-1, keepdim=True).clamp_min(1e-12) / 7
56
+ q = (t / s).round().clamp(-8, 7).to(torch.int16).view(M, K // 32, 2, 16)
57
+ by = ((q[:, :, 0] & 15) | ((q[:, :, 1] & 15) << 4)).to(torch.uint8)
58
+ put(name, "q4", by.permute(1, 0, 2).contiguous().cpu().numpy().view(np.int8), M, K)
59
+ put(name + ".s", "qs", (s / 16).view(M, K // GS).contiguous().cpu().numpy().astype(np.float32), M, K // GS)
60
+ if b is not None: f32(name + ".b", b)
61
+ qb = q4 if BITS == 4 else q8
62
+ def pair_rows(gate, up):
63
+ n = gate.shape[0]
64
+ return torch.stack([gate.view(n // 8, 8, -1), up.view(n // 8, 8, -1)], 1).reshape(2 * n, -1)
65
+ def cross(o, c, ctxin=True):
66
+ """cross / self attention c -> o{q,kv,o,qn,kn}"""
67
+ kv = g(c + "to_kv.weight")
68
+ qb(o + "q", g(c + "to_q.weight")[FULL])
69
+ qb(o + "kv", torch.cat([kv[:D][FULL], kv[D:]], 0))
70
+ qb(o + "o", g(c + "to_out.weight"))
71
+ f32(o + "qn", g(c + "norm_q.weight")[PERM]); f32(o + "kn", g(c + "norm_k.weight")[PERM])
72
+
73
+ with torch.no_grad():
74
+ t1w, t1b, t2w, t2b = g("t_embedder.mlp.0.weight"), g("t_embedder.mlp.0.bias"), g("t_embedder.mlp.2.weight"), g("t_embedder.mlp.2.bias")
75
+ half = 128
76
+ fr = torch.exp(-np.log(10000) * torch.arange(half, dtype=torch.float32, device=dev) / half)
77
+ ts0 = torch.cat([torch.cos(0 * fr), torch.sin(0 * fr)])[None]
78
+ t0 = torch.nn.functional.silu(ts0 @ t1w.T + t1b) @ t2w.T + t2b # temb at t = 0
79
+ blocks = [("noise_refiner", i) for i in range(NR)] + [("layers", i) for i in range(NL)]
80
+ for k, (kind, i) in enumerate(blocks):
81
+ p, o = f"{kind}.{i}.", f"b{k}."
82
+ qkv = g(p + "attention.qkv.weight")
83
+ qb(o + "qkv", torch.cat([qkv[:D][FULL], qkv[D:2 * D][FULL], qkv[2 * D:]], 0))
84
+ qb(o + "o", g(p + "attention.out.weight"))
85
+ w13 = g(p + "feed_forward.w13.weight")
86
+ qb(o + "mlp_in", pair_rows(w13[:FF], w13[FF:]))
87
+ qb(o + "down", g(p + "feed_forward.w2.weight"))
88
+ f32(o + "qn", g(p + "attention.q_norm.weight")[PERM]); f32(o + "kn", g(p + "attention.k_norm.weight")[PERM])
89
+ mw, mb = g(p + "adaLN_modulation.0.weight"), g(p + "adaLN_modulation.0.bias")
90
+ f16(o + "mod", mw); f32(o + "mod.b", mb)
91
+ s1, g1, s2, g2 = (t0 @ mw.T + mb)[0].chunk(4)
92
+ n1, n2, f1, f2 = (g(p + n + ".weight") for n in ("attention_norm1", "attention_norm2", "ffn_norm1", "ffn_norm2"))
93
+ for n, v in (("n1", n1), ("n2", n2), ("f1", f1), ("f2", f2), ("z1", n1 * (1 + s1)), ("z2", n2 * g1.tanh()),
94
+ ("zf1", f1 * (1 + s2)), ("zf2", f2 * g2.tanh())):
95
+ f32(o + n, v)
96
+ if kind == "layers" and i in INJ:
97
+ cross(o + "c", p + "cross_attention.")
98
+ f32(o + "cn1", g(p + "cross_attn_norm1.weight"))
99
+ f32(o + "cn2", g(p + "cross_attn_norm2.weight") * torch.tanh(g(p + "cross_attn_gate")))
100
+ print("block", k, flush=True)
101
+ for j in range(2):
102
+ p, o = f"perceiver.layers.{j}.", f"p{j}."
103
+ cross(o + "c", p + "cross_attention."); cross(o + "s", p + "self_attention.")
104
+ w13 = g(p + "ffn.w13.weight")
105
+ qb(o + "mlp_in", pair_rows(w13[:FF], w13[FF:])); qb(o + "down", g(p + "ffn.w2.weight"))
106
+ f32(o + "cn", g(p + "cross_attn_norm.weight")); f32(o + "sn", g(p + "self_attn_norm.weight"))
107
+ f32(o + "fn", g(p + "ffn_norm.weight"))
108
+ f32("queries", g("perceiver.latent_queries")); f32("pnorm", g("perceiver.norm_out.weight"))
109
+ xw = g("x_embedder.weight")
110
+ q8("x_in", torch.cat([xw, torch.zeros_like(xw)], 1), g("x_embedder.bias"))
111
+ f16("t1", t1w); f32("t1.b", t1b); f16("t2", t2w); f32("t2.b", t2b)
112
+ f16("out_scale", g("final_layer.adaLN_modulation.1.weight")); f32("out_scale.b", g("final_layer.adaLN_modulation.1.bias"))
113
+ q8("out", g("final_layer.linear.weight"), g("final_layer.linear.bias"))
114
+ writer.add_string("ugpu.model", "fibo")
115
+ writer.add_string("ugpu.index", "\n".join(index))
116
+ writer.write_header_to_file(); writer.write_kv_data_to_file(); writer.write_tensors_to_file(); writer.close()
117
+ print("wrote", OUT, os.path.getsize(OUT) / 1e9, "GB,", len(index), "tensors")
build/pack_tae.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny picture decoders (the TAESD family: taeqi2_1 for Qwen, taef2 for Klein, ...) -> one GGUF for the engine.
2
+ The decoder is rebuilt with the reference code and walked layer by layer; the walk is written as a small program
3
+ ("ugpu.program", one op per line) that model_tae.h runs:
4
+ clamp x = 3 tanh(x / 3)
5
+ conv <name> <ci> <co> <k> <bias> <relu> <up> k x k filter, padding k/2; up = 1: input doubled first (nearest),
6
+ up = -1: stride 2 (an encoder's shrinking filter)
7
+ pool <name> <ci> <cg> <groups> x += p3(relu(groupnorm(p0(x)))), p0: ci -> cg 1x1, p3 back (flux_2)
8
+ block <name> <ci> <co> <skip> relu(c2(relu(c1(relu(c0(x))))) + skip(x)), skip = 1x1 filter or x itself
9
+ shuffle <r> channels -> r x r pixels (PixelShuffle)
10
+ out <channels> channels kept in the picture
11
+ Filters are stored fp16 as [out][ky][kx][in]; biases fp32.
12
+ ENC=1 packs the encoder instead (input: the picture in [0, 1], channels padded to 4; output: the latent).
13
+ Usage: python pack_tae.py <taesd file> <out.gguf> <latent channels> <arch variant or ""> <image channels>"""
14
+ import os
15
+ import sys
16
+ sys.path[:0] = ["/home/debian/phone-v81/qwen/build/common", "/home/debian/llama.cpp/gguf-py"]
17
+ import numpy as np
18
+ import torch
19
+ import torch.nn as nn
20
+ from safetensors.torch import load_file
21
+ from taesd import TAESD, Clamp, Block
22
+ import gguf
23
+
24
+ SRC, OUT, LC, ARCH, IC = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] or None, int(sys.argv[5])
25
+ t = TAESD(encoder_path=None, decoder_path=None, latent_channels=LC, arch_variant=ARCH, image_channels=IC)
26
+ sd = load_file(SRC)
27
+ ENC = os.environ.get("ENC") == "1"
28
+ if any(k.startswith("decoder.layers.") or k.startswith("encoder.layers.") for k in sd): # the Sequential's index 0 (Clamp) has no weights in these files
29
+ sd = {".".join([e, str(int(i) + (1 if e == "decoder" else 0)), *s]): v
30
+ for k, v in sd.items() for e, _l, i, *s in [k.split(".")]}
31
+ half = "encoder." if ENC else "decoder."
32
+ sd = {k: v for k, v in sd.items() if k.startswith(half)}
33
+ missing = [k for k in t.load_state_dict({k: v.float() for k, v in sd.items()}, strict=False).missing_keys if k.startswith(half)]
34
+ if missing: raise SystemExit(f"weights missing from {SRC}: {missing[:5]}")
35
+ writer = gguf.GGUFWriter(OUT, "ugpu")
36
+ index, prog = [], []
37
+
38
+ def put(name, kind, a, M, K):
39
+ writer.add_tensor(name, np.ascontiguousarray(a))
40
+ index.append(f"{name} {kind} {M} {K}")
41
+ def filt(name, c):
42
+ w = c.weight.detach().permute(0, 2, 3, 1).contiguous() # [out][ky][kx][in]
43
+ if w.shape[-1] % 4: # the picture's 3 colours -> 4 (a zero channel)
44
+ w = torch.cat([w, w.new_zeros(*w.shape[:-1], 4 - w.shape[-1] % 4)], -1)
45
+ co = (c.out_channels + 3) // 4 * 4 # the engine works in groups of 4 channels:
46
+ w = torch.cat([w, w.new_zeros(co - w.shape[0], *w.shape[1:])]) # pad with zero outputs (e.g. RGB -> RGB0)
47
+ put(name, "f16", w.half().reshape(w.shape[0], -1).numpy(), w.shape[0], w[0].numel())
48
+ if c.bias is not None:
49
+ b = torch.cat([c.bias.detach().float(), torch.zeros(co - c.out_channels)])
50
+ put(name + ".b", "f32", b.numpy(), co, 1)
51
+ return (c.in_channels + 3) // 4 * 4, co, c.kernel_size[0], int(c.bias is not None)
52
+
53
+ layers, up, i = list(t.encoder if ENC else t.decoder), 0, 0
54
+ while i < len(layers):
55
+ m = layers[i]
56
+ if isinstance(m, Clamp): prog.append("clamp")
57
+ elif isinstance(m, nn.Upsample): up = 1
58
+ elif isinstance(m, nn.Conv2d):
59
+ assert m.stride in ((1, 1), (2, 2)) and m.padding[0] == m.kernel_size[0] // 2
60
+ if m.stride == (2, 2): up = -1
61
+ relu = int(i + 1 < len(layers) and isinstance(layers[i + 1], nn.ReLU))
62
+ ci, co, k, b = filt(f"l{i}", m)
63
+ prog.append(f"conv l{i} {ci} {co} {k} {b} {relu} {up}")
64
+ up = 0
65
+ i += relu
66
+ elif isinstance(m, Block):
67
+ if m.pool is not None: # flux_2: x += p3(relu(groupnorm(p0(x)))) before the block
68
+ p0, gn, p3 = m.pool[0], m.pool[1], m.pool[3]
69
+ filt(f"l{i}.p0", p0); filt(f"l{i}.p3", p3)
70
+ put(f"l{i}.gn.w", "f32", gn.weight.detach().float().numpy(), gn.num_channels, 1)
71
+ put(f"l{i}.gn.b", "f32", gn.bias.detach().float().numpy(), gn.num_channels, 1)
72
+ prog.append(f"pool l{i} {p0.in_channels} {p0.out_channels} {gn.num_groups}")
73
+ c = [x for x in m.conv if isinstance(x, nn.Conv2d)]
74
+ for j, cj in enumerate(c): filt(f"l{i}.c{j}", cj)
75
+ skip = int(isinstance(m.skip, nn.Conv2d))
76
+ if skip: filt(f"l{i}.skip", m.skip)
77
+ prog.append(f"block l{i} {c[0].in_channels} {c[0].out_channels} {skip}")
78
+ elif isinstance(m, nn.PixelShuffle): prog.append(f"shuffle {m.upscale_factor}")
79
+ elif isinstance(m, nn.ReLU): raise SystemExit(f"ReLU at {i} not after a filter")
80
+ else: raise SystemExit(f"layer {i} ({type(m).__name__}) not supported")
81
+ i += 1
82
+ prog.append(f"out {LC if ENC else min(IC, 3)}")
83
+ writer.add_string("ugpu.model", "tae")
84
+ writer.add_string("ugpu.index", "\n".join(index))
85
+ writer.add_string("ugpu.program", "\n".join(prog))
86
+ writer.write_header_to_file(); writer.write_kv_data_to_file(); writer.write_tensors_to_file(); writer.close()
87
+ print("\n".join(prog))
88
+ print("wrote", OUT, len(index), "tensors")
files/fibo_q8.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42b0c943cb6375bae4f6fc373c7e1f6e2094461a5454be1b059d824a334a96b3
3
+ size 9416244640
files/fibo_reader.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dd3e9db2deb779fe5b65aa273822b62ba1fc737f8436a5e68973ad295075555
3
+ size 4280406112
files/fibo_reader_mmproj.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c6fe00837ebce49e609a63c3316160acfd702b46efe0e4c904241f55ea745e1
3
+ size 836180192
files/sigmas.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ 1.000000
2
+ 0.904531
3
+ 0.759511
4
+ 0.512844
files/tae_f2.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7482e8d7a55c85e37d9ce138026a18b26c66a00a2af23c5430f671c13196d8ce
3
+ size 2690432
files/taee_f2.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b37dc38589b8dca234e664e4546664ad30b4be86a5783d568468ab50ea9577cb
3
+ size 2690528
manifest.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base": "https://huggingface.co/sebekblessing/fibo-gpu/resolve/main/",
3
+ "shared": [],
4
+ "variants": {
5
+ "gpu": {
6
+ "label": "Fibo 2.0 edit (graphics chip)",
7
+ "about": "Fibo 2.0 edit-turbo on the graphics chip: edits a 768x768 picture as you describe, in several minutes. Its prompt reader is Qwen3-VL-4B (8-bit) on the processor.",
8
+ "files": [
9
+ {
10
+ "path": "files/fibo_q8.gguf",
11
+ "name": "fibo_q8.gguf",
12
+ "size": 9416244640,
13
+ "sha256": "42b0c943cb6375bae4f6fc373c7e1f6e2094461a5454be1b059d824a334a96b3"
14
+ },
15
+ {
16
+ "path": "files/tae_f2.gguf",
17
+ "name": "tae_f2.gguf",
18
+ "size": 2690432,
19
+ "sha256": "7482e8d7a55c85e37d9ce138026a18b26c66a00a2af23c5430f671c13196d8ce"
20
+ },
21
+ {
22
+ "path": "files/taee_f2.gguf",
23
+ "name": "taee_f2.gguf",
24
+ "size": 2690528,
25
+ "sha256": "b37dc38589b8dca234e664e4546664ad30b4be86a5783d568468ab50ea9577cb"
26
+ },
27
+ {
28
+ "path": "files/fibo_reader.gguf",
29
+ "name": "fibo_reader.gguf",
30
+ "size": 4280406112,
31
+ "sha256": "6dd3e9db2deb779fe5b65aa273822b62ba1fc737f8436a5e68973ad295075555"
32
+ },
33
+ {
34
+ "path": "files/fibo_reader_mmproj.gguf",
35
+ "name": "fibo_reader_mmproj.gguf",
36
+ "size": 836180192,
37
+ "sha256": "0c6fe00837ebce49e609a63c3316160acfd702b46efe0e4c904241f55ea745e1"
38
+ },
39
+ {
40
+ "path": "files/sigmas.txt",
41
+ "name": "sigmas.txt",
42
+ "size": 36,
43
+ "sha256": "1ebd8b21b2d886ec6e7d6be63569d90918b3e0b7e2eece6fb6bd2749616027ee"
44
+ }
45
+ ]
46
+ }
47
+ }
48
+ }