Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / supertonic_bundle.py
supertonic_bundle.py118 lines · 4.7 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Supertonic 3's non-weight bundle files: the codepoint table and the voice styles. |
| 3 | |
| 4 | `supertonic_fold.py` produces the four `.maml` plans. Two more things travel with them and are |
| 5 | neither weights nor plans: |
| 6 | |
| 7 | onnx/unicode_indexer.json -> unicode_indexer.bin 65,536 int16, one per BMP codepoint |
| 8 | voice_styles/<name>.json -> style_<name>.bin style_ttl then style_dp, as fp16 |
| 9 | |
| 10 | # Why the codepoint table is not a `.maml` |
| 11 | |
| 12 | A `.maml` holds fp16 or int8 *tensors*, and this is a lookup table of signed indices: `-1` where |
| 13 | the model has no token, 0..8320 where it has one. 65,536 `int16` is 128 KB against the JSON's |
| 14 | 278 KB, and the Rust reads it as a borrowed `&[u8]` with no parsing at all. See |
| 15 | `post::supertonic::to_ids`, and note that the model expects **NFD** text - precomposed accents are |
| 16 | unmapped while combining marks are first-class tokens. |
| 17 | |
| 18 | # Why the styles are not weights either |
| 19 | |
| 20 | `style_ttl` and `style_dp` are *inputs*, one pair per voice, so they cannot live in a plan's |
| 21 | weights buffer. `style_ttl` is `[1, 50, 256]` in the JSON and this runtime is channel-major, so it |
| 22 | is written **transposed** to `[256, 50]`; `style_dp` is `[1, 8, 16]` and flattens row-major to 128, |
| 23 | which is the order the export's own `Reshape` produces. |
| 24 | |
| 25 | Usage: |
| 26 | ./scripts/ml/supertonic_bundle.py --indexer onnx/unicode_indexer.json -o out/ |
| 27 | ./scripts/ml/supertonic_bundle.py --styles voice_styles/ -o out/ |
| 28 | """ |
| 29 | |
| 30 | import argparse |
| 31 | import json |
| 32 | import os |
| 33 | |
| 34 | import numpy as np |
| 35 | |
| 36 | # Every code unit of the Basic Multilingual Plane. Astral-plane characters are outside the table |
| 37 | # and dropped by the reader rather than being mapped to -1 here. |
| 38 | ENTRIES = 65_536 |
| 39 | |
| 40 | # `n_style` and `style_key_dim` of the text-to-latent style token layer, and `n_style * style_dim` |
| 41 | # of the duration predictor's. |
| 42 | STYLE_TOKENS = 50 |
| 43 | STYLE_WIDTH = 256 |
| 44 | DURATION_STYLE = 128 |
| 45 | |
| 46 | |
| 47 | def indexer(path, out): |
| 48 | """`unicode_indexer.json` to a flat `int16` table.""" |
| 49 | table = json.load(open(path, encoding="utf-8")) |
| 50 | if len(table) != ENTRIES: |
| 51 | raise SystemExit(f"{path}: {len(table)} entries, not {ENTRIES}") |
| 52 | values = np.asarray(table, dtype=np.int64) |
| 53 | if values.min() < -1 or values.max() > 32_767: |
| 54 | raise SystemExit(f"{path}: indices {values.min()}..{values.max()} do not fit int16") |
| 55 | mapped = int((values >= 0).sum()) |
| 56 | target = os.path.join(out, "unicode_indexer.bin") |
| 57 | values.astype("<i2").tofile(target) |
| 58 | print(f" unicode_indexer.bin {mapped} mapped, max index {values.max()}, {ENTRIES * 2} bytes") |
| 59 | return target |
| 60 | |
| 61 | |
| 62 | def style(path, out): |
| 63 | """One `voice_styles/<name>.json` to `style_<name>.bin`, transposed and fp16.""" |
| 64 | name = os.path.splitext(os.path.basename(path))[0] |
| 65 | held = json.load(open(path, encoding="utf-8")) |
| 66 | |
| 67 | def read(key, dims): |
| 68 | entry = held[key] |
| 69 | values = np.asarray(entry["data"], dtype=np.float32) |
| 70 | if list(entry["dims"]) != dims: |
| 71 | raise SystemExit(f"{path}: {key} is {entry['dims']}, not {dims}") |
| 72 | return values.reshape(dims) |
| 73 | |
| 74 | ttl = read("style_ttl", [1, STYLE_TOKENS, STYLE_WIDTH]).reshape(STYLE_TOKENS, STYLE_WIDTH) |
| 75 | dp = read("style_dp", [1, 8, 16]).reshape(-1) |
| 76 | if dp.size != DURATION_STYLE: |
| 77 | raise SystemExit(f"{path}: style_dp flattens to {dp.size}, not {DURATION_STYLE}") |
| 78 | |
| 79 | # Channel-major for `style_ttl`; `style_dp` is already in the order the export's `Reshape` |
| 80 | # produces, which is what the duration predictor's head concatenates. |
| 81 | blob = np.concatenate( |
| 82 | [np.ascontiguousarray(ttl.T).reshape(-1).astype(np.float16), dp.astype(np.float16)] |
| 83 | ) |
| 84 | target = os.path.join(out, f"style_{name}.bin") |
| 85 | blob.tofile(target) |
| 86 | print(f" style_{name}.bin {blob.size} fp16, {blob.nbytes} bytes") |
| 87 | return target |
| 88 | |
| 89 | |
| 90 | def main(): |
| 91 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 92 | parser.add_argument("--indexer", help="onnx/unicode_indexer.json") |
| 93 | parser.add_argument("--styles", help="the voice_styles directory, or one .json in it") |
| 94 | parser.add_argument("-o", "--out", required=True) |
| 95 | args = parser.parse_args() |
| 96 | os.makedirs(args.out, exist_ok=True) |
| 97 | |
| 98 | if not args.indexer and not args.styles: |
| 99 | raise SystemExit("nothing to do: pass --indexer, --styles or both") |
| 100 | if args.indexer: |
| 101 | indexer(args.indexer, args.out) |
| 102 | if args.styles: |
| 103 | if os.path.isdir(args.styles): |
| 104 | names = sorted( |
| 105 | os.path.join(args.styles, f) |
| 106 | for f in os.listdir(args.styles) |
| 107 | if f.endswith(".json") |
| 108 | ) |
| 109 | if not names: |
| 110 | raise SystemExit(f"{args.styles}: no .json voice styles") |
| 111 | else: |
| 112 | names = [args.styles] |
| 113 | for name in names: |
| 114 | style(name, args.out) |
| 115 | |
| 116 | |
| 117 | if __name__ == "__main__": |
| 118 | main() |