mlx-bun 0.0.8 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -20
- package/docs/design/batching-v2-plan.md +515 -0
- package/docs/design/bucketing-stage.md +196 -0
- package/docs/design/compat-cli-surface-design.md +11 -11
- package/docs/design/docs-reorg-plan.md +1 -1
- package/docs/design/dreaming-nightly-pipeline.md +291 -0
- package/docs/design/dspark-speculative-decoding.md +106 -0
- package/docs/design/generic-model-support.md +381 -0
- package/docs/design/memory-inference-path.md +422 -0
- package/docs/design/memory-synthesis.md +287 -0
- package/docs/design/minicpm5-decode-megakernel.md +484 -0
- package/docs/design/mlx-lm-tool-parity-plan.md +535 -0
- package/docs/design/orpo-dynamic-lambda.md +41 -0
- package/docs/design/orpo-training.md +35 -5
- package/docs/design/parallel-slots.md +12 -1
- package/docs/design/parity-tier-dag.md +13 -5
- package/docs/design/spec-decode-larger-targets.md +229 -0
- package/docs/design/tauri-desktop-app.md +2 -2
- package/docs/design/the-dreaming-handoff.md +141 -0
- package/docs/design/the-dreaming-master-plan.md +446 -0
- package/docs/design/write-pipeline-entity.md +468 -0
- package/docs/investigations/curve-bisector-routing.md +1 -1
- package/docs/investigations/decode-roofline-lookagain.md +262 -0
- package/docs/investigations/dspark-handoff.md +58 -0
- package/docs/investigations/kernel-perf-review-2026-07.md +92 -0
- package/docs/planning/PRODUCT_ROADMAP.md +2 -2
- package/docs/planning/curve-sampler-research-plan.md +331 -0
- package/docs/planning/memory-docs-and-dag-plan.md +185 -0
- package/docs/planning/pi-integration-review.md +178 -0
- package/docs/planning/release-notes-v0.0.9.md +122 -0
- package/docs/planning/web-ui-pass-plan.md +213 -0
- package/docs/planning/website-readme-pass-plan.md +224 -0
- package/docs/reference/cli.md +255 -0
- package/docs/reference/embedding.md +7 -2
- package/docs/reference/library-api.md +22 -3
- package/docs/reference/memory.md +5 -5
- package/docs/reference/models.md +137 -0
- package/docs/reference/orpo-quickstart.md +6 -0
- package/docs/reference/server-api.md +187 -9
- package/docs/reference/server-config.md +40 -9
- package/docs/reference/training.md +25 -11
- package/package.json +1 -1
- package/src/anthropic.ts +22 -0
- package/src/assets/curve-designer.html +1 -1
- package/src/chat-template.ts +25 -7
- package/src/cli.ts +1029 -86
- package/src/config.ts +4 -1
- package/src/download.ts +99 -8
- package/src/embed.ts +77 -0
- package/src/eval/perplexity.ts +164 -0
- package/src/eval/runner.ts +15 -6
- package/src/eval/tasks/bfcl.ts +1 -1
- package/src/generate.ts +141 -18
- package/src/harness-pi.ts +43 -17
- package/src/index.ts +2 -0
- package/src/lora.ts +2 -2
- package/src/memory/article.ts +558 -0
- package/src/memory/chunk-validation.ts +150 -0
- package/src/memory/chunk.ts +305 -12
- package/src/memory/cluster.ts +344 -17
- package/src/memory/coverage.ts +134 -0
- package/src/memory/crosslink.ts +0 -0
- package/src/memory/db.ts +184 -45
- package/src/memory/entity.ts +203 -0
- package/src/memory/gate.ts +187 -0
- package/src/memory/history.ts +152 -0
- package/src/memory/ingest.ts +324 -11
- package/src/memory/model.ts +321 -0
- package/src/memory/normalize.ts +671 -0
- package/src/memory/parse.ts +22 -0
- package/src/memory/pipeline.ts +242 -30
- package/src/memory/prompts.ts +42 -0
- package/src/memory/query.ts +334 -0
- package/src/memory/reconcile.ts +734 -0
- package/src/memory/redirect.ts +108 -0
- package/src/memory/reindex.ts +325 -0
- package/src/memory/resolve.ts +307 -0
- package/src/memory/route.ts +272 -0
- package/src/memory/schedule.ts +6 -4
- package/src/memory/stages.ts +774 -0
- package/src/memory/synthesize.ts +1629 -20
- package/src/memory/tools.ts +446 -96
- package/src/memory/vault.ts +462 -35
- package/src/memory/wikify.ts +1057 -16
- package/src/mlx/ffi.ts +3 -0
- package/src/mlx/ops.ts +46 -0
- package/src/model/compiled-decode.ts +43 -8
- package/src/model/factory.ts +29 -8
- package/src/model/flash-attention.ts +4 -2
- package/src/model/fused-decode-kernel.ts +14 -7
- package/src/model/fused-mlp-kernel.ts +169 -0
- package/src/model/fused-swiglu-kernel.ts +240 -0
- package/src/model/gemma4-base.ts +62 -6
- package/src/model/gemma4.ts +33 -2
- package/src/model/minicpm5.ts +106 -8
- package/src/model/qwen3.ts +276 -0
- package/src/model/steel-linear-kernel.ts +96 -0
- package/src/model/support.ts +38 -8
- package/src/model/universal/archs.ts +332 -0
- package/src/model/universal/dense.ts +576 -0
- package/src/model/universal/modules.ts +163 -0
- package/src/model/universal/rope.ts +366 -0
- package/src/pi-provider.ts +1 -1
- package/src/pi-terminal.ts +29 -8
- package/src/pi-web.ts +19 -2
- package/src/quantize/config-writer.ts +1 -1
- package/src/registry.ts +215 -7
- package/src/responses.ts +23 -0
- package/src/sampler.ts +220 -9
- package/src/serve/batch-scheduler.ts +272 -80
- package/src/serve/generation-gateway.ts +86 -18
- package/src/server.ts +612 -49
- package/src/spec/drafter.ts +81 -49
- package/src/spec/dspark/data-dflash.ts +156 -0
- package/src/spec/dspark/data.ts +201 -0
- package/src/spec/dspark/generate-dflash.ts +193 -0
- package/src/spec/dspark/generate.ts +290 -0
- package/src/spec/dspark/loss.ts +213 -0
- package/src/spec/dspark/module-dflash.ts +361 -0
- package/src/spec/dspark/module.ts +540 -0
- package/src/spec/dspark/sample.ts +112 -0
- package/src/spec/generate.ts +40 -19
- package/src/status-page.html +1 -1
- package/src/tokenizer.ts +7 -0
- package/src/train/flash-cce.ts +70 -15
- package/src/train/fuse.ts +243 -0
- package/src/train/index.ts +3 -0
- package/src/train/job.ts +8 -0
- package/src/train/loss.ts +289 -30
- package/src/train/prefix-shared.ts +33 -5
- package/src/train/segmented.ts +67 -11
- package/src/train/trainer.ts +92 -28
- package/src/web/skills/memory/SKILL.md +40 -17
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Plain quantized linear y = x @ Wᵀ as OUR dispatch, composed from the steel
|
|
2
|
+
// building blocks already in src/train/steel-qmm-header.ts (BlockMMA + Block/
|
|
3
|
+
// QuantizedBlockLoader — MLX's verbatim GEMM, the same code qmm_t_impl wraps).
|
|
4
|
+
// This is the projection primitive for the controlled forward (q/k/v/o/down):
|
|
5
|
+
// we own the dispatch and the eval boundary instead of emitting an ops.* node
|
|
6
|
+
// into MLX's lazy graph. N (out) and H (in/K) are baked as template literals;
|
|
7
|
+
// M comes from the x_shape helper. Output bit-matches the BlockMMA store epilogue
|
|
8
|
+
// (TransformNone → cast to T), the same store qmm_t_impl uses.
|
|
9
|
+
|
|
10
|
+
import { MlxArray } from "../mlx/array";
|
|
11
|
+
import { MetalKernel } from "../mlx/metal-kernel";
|
|
12
|
+
import { STEEL_QMM_HEADER } from "../train/steel-qmm-header";
|
|
13
|
+
import * as ops from "../mlx/ops";
|
|
14
|
+
import type { QuantSpec } from "../mlx/ops";
|
|
15
|
+
|
|
16
|
+
const BM = 32, BN = 32, BK = 32, WM = 2, WN = 2;
|
|
17
|
+
const TGN = WM * WN * 32;
|
|
18
|
+
|
|
19
|
+
// One BM×BN output tile per threadgroup (grid.y = N-tiles, grid.z = M-tiles), the
|
|
20
|
+
// K=H reduction looped inside — the qmm_t_impl body, dims via templateInts.
|
|
21
|
+
const SOURCE = String.raw`
|
|
22
|
+
const uint M=x_shape[0]; constexpr int N=N_T, H=H_T;
|
|
23
|
+
constexpr int gs=GS_T, bts=BITS_T;
|
|
24
|
+
constexpr int pf=get_pack_factor<bts,8>(), bpp=get_bytes_per_pack<bts>();
|
|
25
|
+
constexpr int BKp=BK_T+16/sizeof(T);
|
|
26
|
+
threadgroup T Xs[BM_T*BKp];
|
|
27
|
+
threadgroup T Ws[BN_T*BKp];
|
|
28
|
+
using mma_t=mlx::steel::BlockMMA<T,T,BM_T,BN_T,BK_T,WM_T,WN_T,false,true,BKp,BKp>;
|
|
29
|
+
using lx_t=mlx::steel::BlockLoader<T,BM_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE>;
|
|
30
|
+
using lw_t=QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gs,bts>;
|
|
31
|
+
const uint sg=simdgroup_index_in_threadgroup, sl=thread_index_in_simdgroup;
|
|
32
|
+
const int Hh=(int)H, K_w=Hh*bpp/pf, K_g=Hh/gs;
|
|
33
|
+
const int m0=(int)threadgroup_position_in_grid.z*BM_T;
|
|
34
|
+
const int n0=(int)threadgroup_position_in_grid.y*BN_T;
|
|
35
|
+
const short num_els=(short)min(BM_T,(int)M-m0);
|
|
36
|
+
const short num_outs=(short)min(BN_T,(int)N-n0);
|
|
37
|
+
|
|
38
|
+
mma_t mma_op(sg,sl);
|
|
39
|
+
lx_t lx(x + (int64_t)m0*Hh, Hh, Xs, sg, sl);
|
|
40
|
+
lw_t lw((const device uint8_t*)w + (int64_t)n0*K_w, scales + (int64_t)n0*K_g, biases + (int64_t)n0*K_g, Hh, Ws, sg, sl);
|
|
41
|
+
|
|
42
|
+
for (int k=0; k<Hh; k+=BK_T){
|
|
43
|
+
threadgroup_barrier(mem_flags::mem_threadgroup);
|
|
44
|
+
if (num_els<BM_T) lx.load_safe(short2(BK_T,num_els)); else lx.load_unsafe();
|
|
45
|
+
if (num_outs<BN_T) lw.load_safe(short2(BK_T,num_outs)); else lw.load_unsafe();
|
|
46
|
+
threadgroup_barrier(mem_flags::mem_threadgroup);
|
|
47
|
+
mma_op.mma(Xs,Ws);
|
|
48
|
+
lx.next(); lw.next();
|
|
49
|
+
}
|
|
50
|
+
threadgroup_barrier(mem_flags::mem_threadgroup);
|
|
51
|
+
// Store straight to device y[m0.., n0..] via the BlockMMA epilogue (float accum
|
|
52
|
+
// → T, the SAME rounding MLX's quantized_matmul applies).
|
|
53
|
+
device T* yp = y + (int64_t)m0*(int64_t)N + n0;
|
|
54
|
+
if (num_els<BM_T || num_outs<BN_T) mma_op.store_result_safe(yp, N, short2(num_outs,num_els));
|
|
55
|
+
else mma_op.store_result(yp, N);
|
|
56
|
+
`;
|
|
57
|
+
|
|
58
|
+
const _kernels = new Map<string, MetalKernel>();
|
|
59
|
+
function getKernel(gs: number, bits: number): MetalKernel {
|
|
60
|
+
const key = `${gs}:${bits}`;
|
|
61
|
+
let k = _kernels.get(key);
|
|
62
|
+
if (!k) {
|
|
63
|
+
k = new MetalKernel({
|
|
64
|
+
name: "mlx_bun_steel_linear",
|
|
65
|
+
inputNames: ["x", "w", "scales", "biases"],
|
|
66
|
+
outputNames: ["y"],
|
|
67
|
+
source: SOURCE,
|
|
68
|
+
header:
|
|
69
|
+
`${STEEL_QMM_HEADER}\n` +
|
|
70
|
+
`#define GS_T ${gs}\n#define BITS_T ${bits}\n` +
|
|
71
|
+
`#define BM_T ${BM}\n#define BN_T ${BN}\n#define BK_T ${BK}\n` +
|
|
72
|
+
`#define WM_T ${WM}\n#define WN_T ${WN}\n#define TGN_T ${TGN}\n`,
|
|
73
|
+
ensureRowContiguous: true,
|
|
74
|
+
});
|
|
75
|
+
_kernels.set(key, k);
|
|
76
|
+
}
|
|
77
|
+
return k;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** y = x @ Wᵀ, quantized, as our own dispatch. `x` is [M, H] (bf16/f16); `w` is
|
|
81
|
+
* the packed weight [N, H*bits/32] with per-group scales/biases [N, H/groupSize].
|
|
82
|
+
* Returns [M, N] in x.dtype. H % BK == 0 and groupSize % BK == 0 required. */
|
|
83
|
+
export function steelLinear(
|
|
84
|
+
x: MlxArray, w: MlxArray, scales: MlxArray, biases: MlxArray, spec: QuantSpec,
|
|
85
|
+
): MlxArray {
|
|
86
|
+
const M = x.shape[0]!, H = x.shape[1]!, N = w.shape[0]!;
|
|
87
|
+
const [y] = getKernel(spec.groupSize, spec.bits).apply([x, w, scales, biases], {
|
|
88
|
+
outputShapeFn: (ins) => [{ shape: [ins[0]!.shape[0]!, N], dtype: x.dtype }],
|
|
89
|
+
grid: (ins) => [TGN, Math.ceil(N / BN), Math.ceil(ins[0]!.shape[0]! / BM)],
|
|
90
|
+
threadGroup: [TGN, 1, 1],
|
|
91
|
+
templateInts: { N_T: N, H_T: H },
|
|
92
|
+
templateDtypes: { T: x.dtype },
|
|
93
|
+
});
|
|
94
|
+
void M;
|
|
95
|
+
return y!;
|
|
96
|
+
}
|
package/src/model/support.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ModelConfig } from "../config";
|
|
2
|
+
import { GENERIC_MODEL_TYPES, genericArgsFor, remapModelType } from "./universal/archs";
|
|
2
3
|
|
|
3
4
|
export function isMiniCPM5Config(config: ModelConfig): boolean {
|
|
4
5
|
const t = config.text;
|
|
@@ -22,6 +23,13 @@ export function isQwen35Config(config: ModelConfig): boolean {
|
|
|
22
23
|
config.text.fullAttentionInterval > 0;
|
|
23
24
|
}
|
|
24
25
|
|
|
26
|
+
/** Plain Qwen3 (model_type `qwen3`, Qwen3ForCausalLM) — a standard dense decoder
|
|
27
|
+
* with per-head q/k norm and tied embeddings. Used here as the text-embedding
|
|
28
|
+
* backbone (mlx-community Qwen3-Embedding-*). Distinct from the qwen3_5 hybrid. */
|
|
29
|
+
export function isQwen3Config(config: ModelConfig): boolean {
|
|
30
|
+
return config.modelType === "qwen3";
|
|
31
|
+
}
|
|
32
|
+
|
|
25
33
|
/** Speculative-decoding drafters (e.g. `gemma4_assistant`) are companion
|
|
26
34
|
* artifacts to a target model — Q-only, centroid-head, no standalone LM
|
|
27
35
|
* head. They are never servable/selectable on their own (the spec path
|
|
@@ -38,17 +46,39 @@ export function isDiffusionGemmaConfig(config: ModelConfig): boolean {
|
|
|
38
46
|
return config.modelType === "diffusion_gemma";
|
|
39
47
|
}
|
|
40
48
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
49
|
+
/** Support tier for a registry record (docs/design/generic-model-support.md):
|
|
50
|
+
* "targeted" = dedicated/generated forward + L2/L3 paths;
|
|
51
|
+
* "generic" = the Tier-0 universal module (L1 monolith only);
|
|
52
|
+
* null = unsupported. Generic never shadows targeted. */
|
|
53
|
+
export function supportTier(modelType: string, repoId = ""): "targeted" | "generic" | null {
|
|
54
|
+
if (isDrafterModelType(modelType)) return null;
|
|
55
|
+
if (modelType.startsWith("gemma4")) return "targeted";
|
|
56
|
+
if (modelType === "diffusion_gemma") return "targeted";
|
|
45
57
|
// qwen3_5 / qwen3_5_text (dense hybrid). The MoE variant is a separate type.
|
|
46
|
-
if (modelType === "qwen3_5" || modelType === "qwen3_5_text") return
|
|
47
|
-
|
|
58
|
+
if (modelType === "qwen3_5" || modelType === "qwen3_5_text") return "targeted";
|
|
59
|
+
if (modelType === "qwen3") return "targeted"; // plain Qwen3 (embedding backbone)
|
|
60
|
+
if (modelType === "llama" && repoId.toLowerCase().includes("minicpm5-1b-optiq-4bit"))
|
|
61
|
+
return "targeted";
|
|
62
|
+
// Tier-0 generic fallback: the universal-dense descriptor table.
|
|
63
|
+
if (GENERIC_MODEL_TYPES.has(remapModelType(modelType))) return "generic";
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function isSupportedModelRecord(modelType: string, repoId = ""): boolean {
|
|
68
|
+
return supportTier(modelType, repoId) !== null;
|
|
48
69
|
}
|
|
49
70
|
|
|
50
71
|
export function isSupportedModelConfig(config: ModelConfig): boolean {
|
|
51
72
|
if (isDrafterModelType(config.modelType)) return false;
|
|
52
|
-
|
|
53
|
-
|
|
73
|
+
if (
|
|
74
|
+
config.modelType.startsWith("gemma4") || isMiniCPM5Config(config) ||
|
|
75
|
+
isQwen35Config(config) || isQwen3Config(config) || isDiffusionGemmaConfig(config)
|
|
76
|
+
) return true;
|
|
77
|
+
// Generic tier: an arch descriptor exists for this model_type (and its
|
|
78
|
+
// config parses — a malformed config is unsupported, not a crash).
|
|
79
|
+
try {
|
|
80
|
+
return genericArgsFor(config) !== null;
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
54
84
|
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
// Arch descriptor table for the Tier-0 universal dense module
|
|
2
|
+
// (docs/design/generic-model-support.md §3.1). One entry per mlx-lm
|
|
3
|
+
// model_type; each parse function is the ~15–25-line transcription of that
|
|
4
|
+
// arch's ModelArgs (defaults included) + structural deltas, read from the
|
|
5
|
+
// RAW config.json exactly like the oracle's dataclass does.
|
|
6
|
+
//
|
|
7
|
+
// Support is this table's keys (+ MODEL_REMAPPING aliases) — an explicit,
|
|
8
|
+
// declared surface. No config sniffing. A model_type absent here is
|
|
9
|
+
// unsupported until a descriptor + green parity manifest entry exist.
|
|
10
|
+
|
|
11
|
+
import type { ModelConfig } from "../../config";
|
|
12
|
+
import type { RopeScalingConfig } from "./rope";
|
|
13
|
+
|
|
14
|
+
/** mlx_lm/utils.py MODEL_REMAPPING, vendored (free aliases). Only entries
|
|
15
|
+
* whose TARGET has a descriptor below actually load; the rest are kept so
|
|
16
|
+
* the reject message can name the real arch. */
|
|
17
|
+
export const MODEL_REMAPPING: Record<string, string> = {
|
|
18
|
+
mistral: "llama",
|
|
19
|
+
llava: "mistral3",
|
|
20
|
+
"phi-msft": "phixtral",
|
|
21
|
+
falcon_mamba: "mamba",
|
|
22
|
+
joyai_llm_flash: "deepseek_v3",
|
|
23
|
+
kimi_k2: "deepseek_v3",
|
|
24
|
+
qwen2_5_vl: "qwen2_vl",
|
|
25
|
+
minimax_m2: "minimax",
|
|
26
|
+
iquestcoder: "llama",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export function remapModelType(modelType: string): string {
|
|
30
|
+
return MODEL_REMAPPING[modelType] ?? modelType;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Normalized args for the universal dense forward — the union of the
|
|
34
|
+
* launch archs' ModelArgs, one value per knob (no optionals left). */
|
|
35
|
+
export interface UniversalArgs {
|
|
36
|
+
modelType: string;
|
|
37
|
+
hiddenSize: number;
|
|
38
|
+
numHiddenLayers: number;
|
|
39
|
+
intermediateSize: number;
|
|
40
|
+
numHeads: number;
|
|
41
|
+
numKvHeads: number;
|
|
42
|
+
headDim: number;
|
|
43
|
+
normEps: number;
|
|
44
|
+
vocabSize: number;
|
|
45
|
+
ropeTheta: number;
|
|
46
|
+
ropeTraditional: boolean;
|
|
47
|
+
ropeScaling: RopeScalingConfig | null;
|
|
48
|
+
maxPositionEmbeddings: number | null;
|
|
49
|
+
/** q/k/v projection bias; o and mlp separately (qwen2: qkv only). */
|
|
50
|
+
qkvBias: boolean;
|
|
51
|
+
oBias: boolean;
|
|
52
|
+
mlpBias: boolean;
|
|
53
|
+
tieWordEmbeddings: boolean;
|
|
54
|
+
/** null ⇒ every layer full attention. */
|
|
55
|
+
layerTypes: string[] | null;
|
|
56
|
+
slidingWindow: number | null;
|
|
57
|
+
// ---- block structure ----
|
|
58
|
+
/** pre = llama (norm → sublayer → residual)
|
|
59
|
+
* post = olmo2 (sublayer → norm → residual)
|
|
60
|
+
* gemma2 = sandwich (input/post-attn + pre/post-ffn norms)
|
|
61
|
+
* glm4 = post-sublayer norms with pre-norms too */
|
|
62
|
+
block: "pre" | "post" | "gemma2" | "glm4";
|
|
63
|
+
norm: "rmsnorm" | "rmsnorm_plus_one" | "layernorm";
|
|
64
|
+
/** qwen3 = per-head RMSNorm over head_dim (before transpose);
|
|
65
|
+
* olmo2 = full-width RMSNorm on the flat projection (before reshape). */
|
|
66
|
+
qkNorm: "none" | "head" | "full";
|
|
67
|
+
mlp: "swiglu" | "geglu" | "geglu_approx" | "fused_swiglu" | "gelu_mlp";
|
|
68
|
+
/** phi3: one fused qkv_proj, split as activations (mx.split — exactly
|
|
69
|
+
* what mlx-lm does; the quantized matrix stays fused). */
|
|
70
|
+
fusedQkv: boolean;
|
|
71
|
+
attnScale: number;
|
|
72
|
+
/** gemma2 attention-score softcap ⇒ manual q·kᵀ→tanh→softmax path. */
|
|
73
|
+
attnLogitSoftcap: number | null;
|
|
74
|
+
finalLogitSoftcap: number | null;
|
|
75
|
+
/** granite: logits / logits_scaling. */
|
|
76
|
+
logitsDivisor: number | null;
|
|
77
|
+
/** gemma: hidden**0.5; granite: embedding_multiplier. */
|
|
78
|
+
embedMultiplier: number | null;
|
|
79
|
+
/** granite residual_multiplier. */
|
|
80
|
+
residualMultiplier: number | null;
|
|
81
|
+
rope: "initialize" | "plain" | "phi3";
|
|
82
|
+
/** rope dims = floor(headDim * partialRotaryFactor) (glm4, phi3). */
|
|
83
|
+
partialRotaryFactor: number;
|
|
84
|
+
/** phi3 SuScaledRoPE original context (TOP-LEVEL config key). */
|
|
85
|
+
originalMaxPositionEmbeddings: number;
|
|
86
|
+
/** smollm3: per-layer 1 = rope, 0 = NoPE. null ⇒ rope everywhere. */
|
|
87
|
+
noRopeLayers: number[] | null;
|
|
88
|
+
/** gemma2: create_attention_mask(..., return_array=True). */
|
|
89
|
+
maskArray: boolean;
|
|
90
|
+
/** sanitize: tensors mlx-lm drops on load (audit allowances). */
|
|
91
|
+
dropWeightPatterns: RegExp[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
type Raw = Record<string, any>;
|
|
95
|
+
|
|
96
|
+
const INV_FREQ = /self_attn\.rotary_emb\.inv_freq/;
|
|
97
|
+
|
|
98
|
+
/** Common fields most archs share; per-arch parsers override the deltas. */
|
|
99
|
+
function common(raw: Raw, modelType: string): UniversalArgs {
|
|
100
|
+
const heads = raw.num_attention_heads as number;
|
|
101
|
+
return {
|
|
102
|
+
modelType,
|
|
103
|
+
hiddenSize: raw.hidden_size,
|
|
104
|
+
numHiddenLayers: raw.num_hidden_layers,
|
|
105
|
+
intermediateSize: raw.intermediate_size,
|
|
106
|
+
numHeads: heads,
|
|
107
|
+
numKvHeads: raw.num_key_value_heads ?? heads,
|
|
108
|
+
headDim: Math.floor(raw.hidden_size / heads),
|
|
109
|
+
normEps: raw.rms_norm_eps,
|
|
110
|
+
vocabSize: raw.vocab_size,
|
|
111
|
+
ropeTheta: raw.rope_theta ?? 10000,
|
|
112
|
+
ropeTraditional: raw.rope_traditional ?? false,
|
|
113
|
+
ropeScaling: (raw.rope_scaling as RopeScalingConfig | undefined) ?? null,
|
|
114
|
+
maxPositionEmbeddings: raw.max_position_embeddings ?? null,
|
|
115
|
+
qkvBias: false,
|
|
116
|
+
oBias: false,
|
|
117
|
+
mlpBias: false,
|
|
118
|
+
tieWordEmbeddings: raw.tie_word_embeddings ?? true,
|
|
119
|
+
layerTypes: null,
|
|
120
|
+
slidingWindow: null,
|
|
121
|
+
block: "pre",
|
|
122
|
+
norm: "rmsnorm",
|
|
123
|
+
qkNorm: "none",
|
|
124
|
+
mlp: "swiglu",
|
|
125
|
+
fusedQkv: false,
|
|
126
|
+
attnScale: Math.pow(Math.floor(raw.hidden_size / heads), -0.5),
|
|
127
|
+
attnLogitSoftcap: null,
|
|
128
|
+
finalLogitSoftcap: null,
|
|
129
|
+
logitsDivisor: null,
|
|
130
|
+
embedMultiplier: null,
|
|
131
|
+
residualMultiplier: null,
|
|
132
|
+
rope: "initialize",
|
|
133
|
+
partialRotaryFactor: 1.0,
|
|
134
|
+
originalMaxPositionEmbeddings: 4096,
|
|
135
|
+
noRopeLayers: null,
|
|
136
|
+
maskArray: false,
|
|
137
|
+
dropWeightPatterns: [],
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function parseLlama(raw: Raw, modelType = "llama"): UniversalArgs {
|
|
142
|
+
const a = common(raw, modelType);
|
|
143
|
+
a.headDim = raw.head_dim ?? a.headDim;
|
|
144
|
+
a.attnScale = Math.pow(a.headDim, -0.5);
|
|
145
|
+
a.qkvBias = raw.attention_bias ?? false;
|
|
146
|
+
a.oBias = raw.attention_bias ?? false; // llama.py wires o_proj bias to the same flag
|
|
147
|
+
a.mlpBias = raw.mlp_bias ?? false;
|
|
148
|
+
a.layerTypes = (raw.layer_types as string[] | undefined) ?? null;
|
|
149
|
+
a.slidingWindow = raw.sliding_window ?? null;
|
|
150
|
+
a.dropWeightPatterns = [INV_FREQ];
|
|
151
|
+
if (a.tieWordEmbeddings) a.dropWeightPatterns.push(/^lm_head\.weight$/);
|
|
152
|
+
return a;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const ARCHS: Record<string, (raw: Raw) => UniversalArgs> = {
|
|
156
|
+
/** llama (+ mistral / iquestcoder via remap): the reference dense block. */
|
|
157
|
+
llama: (raw) => parseLlama(raw),
|
|
158
|
+
|
|
159
|
+
/** smollm3: llama with NoPE layers (every no_rope_layer_interval-th). */
|
|
160
|
+
smollm3: (raw) => {
|
|
161
|
+
const a = parseLlama(raw, "smollm3");
|
|
162
|
+
const interval = raw.no_rope_layer_interval ?? 4;
|
|
163
|
+
const list = raw.no_rope_layers as number[] | undefined;
|
|
164
|
+
if (list && list.length !== a.numHiddenLayers)
|
|
165
|
+
throw new Error("`no_rope_layers` length mismatch");
|
|
166
|
+
a.noRopeLayers = list ??
|
|
167
|
+
Array.from({ length: a.numHiddenLayers }, (_, i) => ((i + 1) % interval !== 0 ? 1 : 0));
|
|
168
|
+
return a;
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
/** qwen2: llama block + hardcoded q/k/v bias (o unbiased), theta 1e6. */
|
|
172
|
+
qwen2: (raw) => {
|
|
173
|
+
const a = common(raw, "qwen2");
|
|
174
|
+
a.ropeTheta = raw.rope_theta ?? 1000000;
|
|
175
|
+
a.maxPositionEmbeddings = raw.max_position_embeddings ?? 32768;
|
|
176
|
+
a.qkvBias = true;
|
|
177
|
+
a.dropWeightPatterns = [INV_FREQ];
|
|
178
|
+
if (a.tieWordEmbeddings) a.dropWeightPatterns.push(/^lm_head\.weight$/);
|
|
179
|
+
return a;
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
/** qwen3: per-head q/k RMSNorm over head_dim BEFORE transpose+rope. */
|
|
183
|
+
qwen3: (raw) => {
|
|
184
|
+
const a = common(raw, "qwen3");
|
|
185
|
+
a.headDim = raw.head_dim; // required in qwen3 ModelArgs
|
|
186
|
+
a.attnScale = Math.pow(a.headDim, -0.5);
|
|
187
|
+
a.qkNorm = "head";
|
|
188
|
+
a.tieWordEmbeddings = raw.tie_word_embeddings ?? false;
|
|
189
|
+
if (a.tieWordEmbeddings) a.dropWeightPatterns = [/^lm_head\.weight$/];
|
|
190
|
+
return a;
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
/** gemma (v1): (1+w) RMSNorm, √hidden embed scale, PRECISE-gelu gated
|
|
194
|
+
* MLP, always-tied head, plain rope (rope_scaling ignored). */
|
|
195
|
+
gemma: (raw) => {
|
|
196
|
+
const a = common(raw, "gemma");
|
|
197
|
+
a.headDim = raw.head_dim; // required
|
|
198
|
+
a.attnScale = Math.pow(a.headDim, -0.5);
|
|
199
|
+
a.norm = "rmsnorm_plus_one";
|
|
200
|
+
a.mlp = "geglu";
|
|
201
|
+
a.embedMultiplier = Math.pow(raw.hidden_size, 0.5);
|
|
202
|
+
a.tieWordEmbeddings = true; // as_linear unconditionally
|
|
203
|
+
a.rope = "plain";
|
|
204
|
+
a.ropeScaling = null;
|
|
205
|
+
return a;
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
/** gemma2: gemma + sandwich norms, attention-score softcap (manual
|
|
209
|
+
* attention), query_pre_attn_scalar scale, final logit softcap,
|
|
210
|
+
* gelu_approx MLP, always-array mask. mlx-lm runs every layer full
|
|
211
|
+
* attention (no sliding window in its gemma2) — we match the oracle. */
|
|
212
|
+
gemma2: (raw) => {
|
|
213
|
+
const a = common(raw, "gemma2");
|
|
214
|
+
a.headDim = raw.head_dim; // required
|
|
215
|
+
a.norm = "rmsnorm_plus_one";
|
|
216
|
+
a.block = "gemma2";
|
|
217
|
+
a.mlp = "geglu_approx";
|
|
218
|
+
a.embedMultiplier = Math.pow(raw.hidden_size, 0.5);
|
|
219
|
+
a.tieWordEmbeddings = true;
|
|
220
|
+
a.rope = "plain";
|
|
221
|
+
a.ropeScaling = null;
|
|
222
|
+
a.attnScale = 1.0 / Math.pow(raw.query_pre_attn_scalar ?? 144.0, 0.5);
|
|
223
|
+
a.attnLogitSoftcap = raw.attn_logit_softcapping ?? 50.0;
|
|
224
|
+
a.finalLogitSoftcap = raw.final_logit_softcapping ?? 30.0;
|
|
225
|
+
a.maskArray = true;
|
|
226
|
+
return a;
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
/** phi3: fused qkv + fused gate_up (split as ACTIVATIONS, like mlx-lm),
|
|
230
|
+
* longrope/su (or linear) rope on partial dims, untied head. */
|
|
231
|
+
phi3: (raw) => {
|
|
232
|
+
const a = common(raw, "phi3");
|
|
233
|
+
a.tieWordEmbeddings = raw.tie_word_embeddings ?? false;
|
|
234
|
+
a.fusedQkv = true;
|
|
235
|
+
a.mlp = "fused_swiglu";
|
|
236
|
+
a.rope = "phi3";
|
|
237
|
+
a.partialRotaryFactor = raw.partial_rotary_factor ?? 1.0;
|
|
238
|
+
a.maxPositionEmbeddings = raw.max_position_embeddings ?? 131072;
|
|
239
|
+
a.originalMaxPositionEmbeddings = raw.original_max_position_embeddings ?? 4096;
|
|
240
|
+
// phi3.py __post_init__: rope_scaling must carry {long_factor, type};
|
|
241
|
+
// only longrope/su/linear supported, anything else → scaling off.
|
|
242
|
+
if (a.ropeScaling) {
|
|
243
|
+
for (const key of ["long_factor", "type"])
|
|
244
|
+
if (!(key in a.ropeScaling))
|
|
245
|
+
throw new Error(`rope_scaling must contain keys {'long_factor', 'type'}`);
|
|
246
|
+
const t = String(a.ropeScaling.type);
|
|
247
|
+
if (!["longrope", "su", "linear"].includes(t)) a.ropeScaling = null;
|
|
248
|
+
}
|
|
249
|
+
return a;
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
/** olmo2: POST-norm block (norm on sublayer output), full-width q/k
|
|
253
|
+
* RMSNorm on the flat projections. */
|
|
254
|
+
olmo2: (raw) => {
|
|
255
|
+
const a = common(raw, "olmo2");
|
|
256
|
+
a.headDim = raw.head_dim ?? a.headDim;
|
|
257
|
+
a.attnScale = Math.pow(a.headDim, -0.5);
|
|
258
|
+
a.block = "post";
|
|
259
|
+
a.qkNorm = "full";
|
|
260
|
+
a.qkvBias = raw.attention_bias ?? false;
|
|
261
|
+
a.oBias = raw.attention_bias ?? false;
|
|
262
|
+
a.mlpBias = raw.mlp_bias ?? false;
|
|
263
|
+
a.dropWeightPatterns = [INV_FREQ];
|
|
264
|
+
return a;
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
/** glm4: pre+post sublayer norms (post_self_attn / post_mlp), fused
|
|
268
|
+
* gate_up MLP, PARTIAL rope with traditional=True default, always a
|
|
269
|
+
* separate lm_head. */
|
|
270
|
+
glm4: (raw) => {
|
|
271
|
+
const a = common(raw, "glm4");
|
|
272
|
+
a.headDim = raw.head_dim ?? a.headDim;
|
|
273
|
+
a.attnScale = Math.pow(a.headDim, -0.5);
|
|
274
|
+
a.block = "glm4";
|
|
275
|
+
a.mlp = "fused_swiglu";
|
|
276
|
+
a.qkvBias = raw.attention_bias;
|
|
277
|
+
a.rope = "plain";
|
|
278
|
+
a.ropeScaling = null;
|
|
279
|
+
a.ropeTraditional = raw.rope_traditional ?? true;
|
|
280
|
+
a.partialRotaryFactor = raw.partial_rotary_factor;
|
|
281
|
+
a.maxPositionEmbeddings = raw.max_position_embeddings ?? 32768;
|
|
282
|
+
a.tieWordEmbeddings = false; // glm4.py constructs lm_head unconditionally
|
|
283
|
+
return a;
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
/** granite: llama block scaled everywhere — attention_multiplier as the
|
|
287
|
+
* SDPA scale, embedding/residual multipliers, logits / logits_scaling. */
|
|
288
|
+
granite: (raw) => {
|
|
289
|
+
const a = common(raw, "granite");
|
|
290
|
+
a.attnScale = raw.attention_multiplier;
|
|
291
|
+
a.embedMultiplier = raw.embedding_multiplier;
|
|
292
|
+
a.residualMultiplier = raw.residual_multiplier;
|
|
293
|
+
a.logitsDivisor = raw.logits_scaling;
|
|
294
|
+
a.qkvBias = raw.attention_bias;
|
|
295
|
+
a.oBias = raw.attention_bias;
|
|
296
|
+
a.mlpBias = raw.mlp_bias;
|
|
297
|
+
a.ropeTraditional = false; // granite.py hardcodes False
|
|
298
|
+
return a;
|
|
299
|
+
},
|
|
300
|
+
|
|
301
|
+
/** starcoder2: LayerNorm (bias affine), bias on ALL projections, plain
|
|
302
|
+
* c_fc→gelu(precise)→c_proj MLP, theta 1e5. */
|
|
303
|
+
starcoder2: (raw) => {
|
|
304
|
+
const a = common(raw, "starcoder2");
|
|
305
|
+
a.normEps = raw.norm_epsilon ?? 1e-5;
|
|
306
|
+
a.vocabSize = raw.vocab_size ?? 49152;
|
|
307
|
+
a.ropeTheta = raw.rope_theta ?? 100000;
|
|
308
|
+
a.norm = "layernorm";
|
|
309
|
+
a.mlp = "gelu_mlp";
|
|
310
|
+
a.qkvBias = true;
|
|
311
|
+
a.oBias = true;
|
|
312
|
+
a.mlpBias = true;
|
|
313
|
+
a.rope = "plain";
|
|
314
|
+
a.ropeScaling = null;
|
|
315
|
+
return a;
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
/** The declared generic support surface (post-remap model_types). */
|
|
320
|
+
export const GENERIC_MODEL_TYPES: ReadonlySet<string> = new Set(Object.keys(ARCHS));
|
|
321
|
+
|
|
322
|
+
/** Descriptor lookup for a loaded config; null ⇒ not generically supported. */
|
|
323
|
+
export function genericArgsFor(config: ModelConfig): UniversalArgs | null {
|
|
324
|
+
const arch = remapModelType(config.modelType);
|
|
325
|
+
const parse = ARCHS[arch];
|
|
326
|
+
if (!parse) return null;
|
|
327
|
+
const raw = (config.raw.text_config ?? config.raw) as Raw;
|
|
328
|
+
const args = parse(raw);
|
|
329
|
+
// keep the ORIGINAL model_type visible in errors/labels
|
|
330
|
+
args.modelType = config.modelType;
|
|
331
|
+
return args;
|
|
332
|
+
}
|