crit-models 0.23.0__py3-none-any.whl

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.
@@ -0,0 +1,9 @@
1
+ """crit Models' Python side: a decoder's mechanisms as its config.json states them and the rules over them
2
+ (crit_models.config), and what a GGUF's metadata must agree with for them (crit_models.gguf). Eval's limits and the
3
+ model plugins read them; Core reads only the generic fields (crit_core.model)."""
4
+ from crit_core import registry as _registry
5
+
6
+ __version__ = "0.23.0"
7
+
8
+ if "gguf_checks" in _registry.KINDS: # a Core that runs a mechanism's GGUF checks (crit-core 0.22 on)
9
+ _registry.register("gguf_checks", "crit_models.gguf:CHECKS")
crit_models/config.py ADDED
@@ -0,0 +1,522 @@
1
+ """A decoder's mechanisms as its config.json states them: layer kinds, looped spans, routed experts, latent attention,
2
+ recurrent state and rotary positions, and the rules over them that Eval's limits and the model plugins share.
3
+
4
+ Core reads config.json's generic fields (crit_core.model.config: the text section, sizes, heads, positions, token
5
+ ids, quantization); this module reads what a mechanism adds on top of them, and the rules that need it: the layer
6
+ kinds a config states (layer_kinds), the layers a token runs through a looped span (layer_applications), the layers
7
+ whose MLP routes experts (routed_layers), the attention layers' geometry (attention_shape, attention_geometry), the
8
+ KV elements a token adds (kv_elements_per_token) and the state that does not grow with the context
9
+ (fixed_state_bytes). architecture(config) gives a ModelConfig together with these: its fields and these sections and
10
+ rules as one object. A family that spells a field its own way adds its key to config_keys.json, never a branch in a
11
+ rule. Every rule reads values only where it evaluates them and raises ConfigError for a value of the wrong type.
12
+ """
13
+ from collections.abc import Mapping
14
+ from dataclasses import dataclass, field
15
+ import json
16
+ from pathlib import Path
17
+ from types import MappingProxyType
18
+
19
+ from crit_core.model.config import (CONFIG_NAME, MAX_LAYERS, UINT64_END, ConfigError, ModelConfig, _Picklable,
20
+ _boolean, _describe, _empty, _fail, _finite_real, _first, _head_dim, _integer,
21
+ _integers, _layer_count, _mapping_of, _object, _positive, _real, _reals, _string,
22
+ _strings, parse_model_config)
23
+
24
+ # Which keys spell each mechanism field, in order: config_keys.json.
25
+ _KEYS = json.loads((Path(__file__).with_name("config_keys.json")).read_text(encoding="utf-8"))
26
+
27
+ EXPERT_KEYS = tuple(_KEYS["experts"])
28
+ EXPERTS_PER_TOKEN_KEYS = tuple(_KEYS["experts_per_token"])
29
+ FULL_KV_HEAD_KEYS = tuple(_KEYS["full_attention_kv_heads"])
30
+ FULL_HEAD_DIM_KEYS = tuple(_KEYS["full_attention_head_dim"])
31
+ FULL_KEYS_EQUAL_VALUES_KEYS = tuple(_KEYS["full_attention_keys_equal_values"])
32
+ LAYER_TYPE_KEYS = tuple(_KEYS["layer_types"])
33
+ SLIDING_LAYER_ID_KEYS = tuple(_KEYS["sliding_layer_ids"])
34
+ SLIDING_WINDOW_KEYS = tuple(_KEYS["sliding_window"])
35
+ ROUTED_SCALING_KEYS = tuple(_KEYS["routed_scaling_factor"])
36
+ LAYER_PASS_KEYS = tuple(MappingProxyType(dict(entry)) for entry in _KEYS["layer_passes"])
37
+ LAYER_TYPE_NAMES = MappingProxyType(dict(_KEYS["layer_type_names"]))
38
+ FULL_ATTENTION = "full_attention"
39
+ SLIDING_ATTENTION = "sliding_attention"
40
+ LINEAR_ATTENTION = "linear_attention"
41
+ OTHER = "other"
42
+ LAYER_KINDS = MappingProxyType({"full_attention": FULL_ATTENTION, "attention": FULL_ATTENTION,
43
+ "sliding_attention": SLIDING_ATTENTION, "linear_attention": LINEAR_ATTENTION})
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class RopeConfig(_Picklable):
48
+ """Rotary position parameters from rope_scaling (else rope_parameters) plus rope_theta; type "" when none."""
49
+ theta: float | None = None
50
+ partial_rotary_factor: float | None = None
51
+ type: str = ""
52
+ factor: float | None = None
53
+ attention_factor: float | None = None
54
+ beta_fast: float | None = None
55
+ beta_slow: float | None = None
56
+ low_freq_factor: float | None = None
57
+ high_freq_factor: float | None = None
58
+ mscale: float | None = None
59
+ mscale_all_dim: float | None = None
60
+ original_max_position_embeddings: int | None = None
61
+ short_factor: tuple = ()
62
+ long_factor: tuple = ()
63
+ mrope_section: tuple = ()
64
+ raw: Mapping = field(default_factory=_empty)
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class RopeLayer:
69
+ """One entry of a rope object keyed by layer type, such as "sliding_attention" (transformers v5's per-layer-type rope):
70
+ its own rope_type, scaling fields, rope_theta and partial_rotary_factor; nothing falls back to the section."""
71
+ layer_type: str = ""
72
+ rope: RopeConfig = field(default_factory=RopeConfig)
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class MoeConfig:
77
+ """Mixture-of-experts fields; experts_key names the key the expert count came from. A field config.json leaves
78
+ out is None, 0 or empty here (norm_topk_prob None, scoring_func ""): Core fills in no family's default, so a
79
+ model plugin states what its reference assumes for it (the reference's own config class has the default)."""
80
+ experts: int = 0
81
+ experts_key: str = ""
82
+ experts_per_token: int = 0
83
+ shared_experts: int | None = None
84
+ moe_intermediate_size: int | None = None
85
+ shared_expert_intermediate_size: int | None = None
86
+ first_k_dense_replace: int | None = None
87
+ decoder_sparse_step: int | None = None
88
+ n_group: int | None = None
89
+ topk_group: int | None = None
90
+ mlp_only_layers: tuple = ()
91
+ norm_topk_prob: bool | None = None
92
+ routed_scaling_factor: float | None = None
93
+ scoring_func: str = ""
94
+ topk_method: str = ""
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class MlaConfig:
99
+ """Multi-head latent attention: present when kv_lora_rank is positive; absent sizes read as 0."""
100
+ kv_lora_rank: int = 0
101
+ qk_rope_head_dim: int = 0
102
+ qk_nope_head_dim: int = 0
103
+ v_head_dim: int = 0
104
+ q_lora_rank: int | None = None
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class LinearAttentionConfig:
109
+ """linear_* recurrence sizes: present when any of them is set."""
110
+ num_key_heads: int | None = None
111
+ num_value_heads: int | None = None
112
+ key_head_dim: int | None = None
113
+ value_head_dim: int | None = None
114
+ conv_kernel_dim: int | None = None
115
+
116
+
117
+ def _layer_types(config, source):
118
+ # The first LAYER_TYPE_KEYS entry the config has (layers_block_type: "mamba", "moe", "mlp", "attention"); else,
119
+ # where the config lists the layers that attend a sliding window (SLIDING_LAYER_ID_KEYS), "sliding_attention" for
120
+ # those and "full_attention" for the others.
121
+ key = next((key for key in LAYER_TYPE_KEYS if key in config), None)
122
+ if key: # a family's own names of the types read as the names they stand for (config_keys.json)
123
+ found = _strings(config, key, source)
124
+ return None if found is None else tuple(LAYER_TYPE_NAMES.get(name, name) for name in found)
125
+ key = next((key for key in SLIDING_LAYER_ID_KEYS if key in config), None)
126
+ ids = _integers(config, key, source) if key else None
127
+ if ids is None:
128
+ return None
129
+ layers = _integer(config, "num_hidden_layers", source)
130
+ if not layers:
131
+ _fail(source, key, "lists sliding-window layers of a config without num_hidden_layers")
132
+ if any(index >= layers for index in ids) or len(set(ids)) != len(ids):
133
+ _fail(source, key, f"names layers outside 0..{layers - 1} or one twice")
134
+ sliding = set(ids)
135
+ return tuple(SLIDING_ATTENTION if index in sliding else FULL_ATTENTION for index in range(layers))
136
+
137
+
138
+ def _sliding_window(config, source):
139
+ # The first SLIDING_WINDOW_KEYS entry the config has.
140
+ return _first(config, SLIDING_WINDOW_KEYS, _integer, source)[0]
141
+
142
+
143
+ def _layer_passes(config, source):
144
+ """((start, end, passes), ...): the spans of layers a looped decoder runs more than once (LAYER_PASS_KEYS), in
145
+ order, without overlaps and inside the layers; () where the config has none."""
146
+ spans = []
147
+ for spec in LAYER_PASS_KEYS:
148
+ if spec["object"] is None: # the config's own keys
149
+ value, label = (config, "") if spec["start"] in config else (None, "")
150
+ else:
151
+ value, label = _object(config, spec["object"], source), spec["object"] + "."
152
+ if value is None:
153
+ continue
154
+ start = _integer(value, spec["start"], source, label + spec["start"])
155
+ end = _integer(value, spec["end"], source, label + spec["end"])
156
+ passes = _integer(value, spec["passes"], source, label + spec["passes"])
157
+ if start is None or end is None or passes is None:
158
+ _fail(source, spec["object"] or spec["start"], f"needs {spec['start']}, {spec['end']} and "
159
+ f"{spec['passes']}")
160
+ spans.append((start, end, passes))
161
+ if not spans:
162
+ return ()
163
+ layers = _layer_count(config, source)
164
+ spans.sort()
165
+ for i, (start, end, passes) in enumerate(spans):
166
+ if not (0 <= start < end) or (layers and end > layers) or passes < 1 or \
167
+ (i and start < spans[i - 1][1]):
168
+ _fail(source, "layer passes", f"span [{start}, {end}) x {passes} is empty, overlaps another or lies "
169
+ f"outside the {layers} layers")
170
+ return tuple(spans)
171
+
172
+
173
+ def _passes_of(config, source):
174
+ # How many times each layer runs a token: 1, or a looped span's passes.
175
+ layers = _layer_count(config, source) or 0
176
+ runs = [1] * layers
177
+ for start, end, passes in _layer_passes(config, source):
178
+ for index in range(start, min(end, layers)):
179
+ runs[index] = passes
180
+ return runs
181
+
182
+
183
+ def attention_shape(config, source=CONFIG_NAME):
184
+ """(full-attention layers, query heads, head dim, KV heads), or None without layers, heads or a head dim.
185
+
186
+ Full layers: layer_types entries "full_attention" or "attention", else layers // full_attention_interval,
187
+ else every layer. Head dim and KV heads are the full-attention layers' (attention_geometry): a
188
+ full_attention_head_dim / full_attention_kv_heads key (config_keys.json) where the config declares one, else
189
+ head_dim (else hidden_size // heads) and num_key_value_heads (else heads).
190
+ """
191
+ config = _mapping_of(config, source)
192
+ layers = _layer_count(config, source)
193
+ if not layers:
194
+ return None
195
+ types = _layer_types(config, source)
196
+ if types:
197
+ full = sum(1 for kind in types if kind in ("full_attention", "attention"))
198
+ else:
199
+ interval = _integer(config, "full_attention_interval", source)
200
+ full = layers // interval if interval else layers
201
+ heads = _integer(config, "num_attention_heads", source)
202
+ head_dim = _head_dim(config, source)
203
+ if not heads or not head_dim:
204
+ return None
205
+ kv_heads = _integer(config, "num_key_value_heads", source) or heads
206
+ full_kv_heads, full_head_dim, _ = _full_geometry(config, source, kv_heads, head_dim)
207
+ return full, heads, full_head_dim, full_kv_heads
208
+
209
+
210
+ def _full_geometry(config, source, kv_heads, head_dim):
211
+ # (KV heads, head dim, cached tensors) of full-attention layers: their own keys where declared, else the others'
212
+ own_heads = _first(config, FULL_KV_HEAD_KEYS, _integer, source)[0]
213
+ own_dim = _first(config, FULL_HEAD_DIM_KEYS, _integer, source)[0]
214
+ keys_only = _first(config, FULL_KEYS_EQUAL_VALUES_KEYS, _boolean, source)[0]
215
+ return own_heads or kv_heads, own_dim or head_dim, 1 if keys_only else 2
216
+
217
+
218
+ def attention_geometry(config, source=CONFIG_NAME):
219
+ """{layer kind: (KV heads, head dim, cached tensors per token)} for FULL_ATTENTION and SLIDING_ATTENTION layers,
220
+ or None without query heads or a head dim. Sliding layers: num_key_value_heads (else num_attention_heads) and
221
+ head_dim (else hidden_size // heads), keys and values cached apart (2 tensors). Full layers: the same, except where
222
+ the config declares their own (config_keys.json full_attention_kv_heads, full_attention_head_dim), and one cached
223
+ tensor where full_attention_keys_equal_values is true (keys derived from the cached values)."""
224
+ config = _mapping_of(config, source)
225
+ heads = _integer(config, "num_attention_heads", source)
226
+ head_dim = _head_dim(config, source)
227
+ if not heads or not head_dim:
228
+ return None
229
+ kv_heads = _integer(config, "num_key_value_heads", source) or heads
230
+ return {FULL_ATTENTION: _full_geometry(config, source, kv_heads, head_dim),
231
+ SLIDING_ATTENTION: (kv_heads, head_dim, 2)}
232
+
233
+
234
+ def kv_elements_per_token(config, source=CONFIG_NAME):
235
+ """K and V elements one token adds to the cache over every layer whose cache grows with the context, or None.
236
+
237
+ Multi-head latent attention (kv_lora_rank) caches the latent plus one shared rope key per layer. Full-attention
238
+ layers cache their own geometry (attention_geometry), one tensor where their keys equal their values. A layer a
239
+ looped decoder runs several times (layer_passes) keeps a cache for each pass.
240
+ """
241
+ config = _mapping_of(config, source)
242
+ layers = _integer(config, "num_hidden_layers", source)
243
+ rank = _integer(config, "kv_lora_rank", source)
244
+ if rank and layers:
245
+ return layers * (rank + (_integer(config, "qk_rope_head_dim", source) or 0))
246
+ shape = attention_shape(config, source)
247
+ if not shape:
248
+ return None
249
+ full, _, head_dim, kv_heads = shape
250
+ runs = _passes_of(config, source)
251
+ types = _layer_types(config, source)
252
+ if types and any(count > 1 for count in runs):
253
+ full = sum(count for kind, count in zip(types, runs) if kind in ("full_attention", "attention"))
254
+ elif any(count > 1 for count in runs):
255
+ full = sum(runs) if full == len(runs) else full
256
+ tensors = attention_geometry(config, source)[FULL_ATTENTION][2]
257
+ return tensors * kv_heads * head_dim * full
258
+
259
+
260
+ def fixed_state_bytes(config, kv_bytes_per_element, source=CONFIG_NAME):
261
+ """Bytes of state that does not grow with the context: the linear-attention recurrence (FP32 state, BF16
262
+ convolution window of linear_conv_kernel_dim - 1, default kernel 4), the Mamba-2 recurrence of "mamba" layers
263
+ (FP32 state, BF16 convolution window of conv_kernel - 1) and the KV cache of sliding_attention layers
264
+ at kv_bytes_per_element. Layer kinds come from layer_types (or the sliding layers' ids); the linear_* sizes are
265
+ read only for linear_attention layers and the sliding window only for sliding_attention layers. A layer a looped
266
+ decoder runs several times (layer_passes) keeps its state once a pass."""
267
+ element = kv_bytes_per_element
268
+ if _finite_real(element) is None or element < 0:
269
+ raise ValueError(f"kv_bytes_per_element must be a finite non-negative number, not {_describe(element)}")
270
+ config = _mapping_of(config, source)
271
+ types = _layer_types(config, source) or ()
272
+ runs = _passes_of(config, source)
273
+ runs = runs if len(runs) == len(types) else [1] * len(types)
274
+
275
+ def count(kind):
276
+ return sum(n for name, n in zip(types, runs) if name == kind)
277
+
278
+ total = 0
279
+ mamba = count("mamba")
280
+ m_heads = _integer(config, "mamba_num_heads", source) if mamba else None
281
+ m_dim = _integer(config, "mamba_head_dim", source) if m_heads else None
282
+ m_state = _integer(config, "ssm_state_size", source) if m_dim else None
283
+ if m_state:
284
+ # Mamba-2: FP32 state [heads][head_dim][state], BF16 window of conv_kernel - 1 over x, B and C.
285
+ channels = m_heads * m_dim + 2 * (_integer(config, "n_groups", source) or 1) * m_state
286
+ conv = max(0, (_integer(config, "conv_kernel", source) or 4) - 1) * channels
287
+ total += mamba * (m_heads * m_dim * m_state * 4 + conv * 2)
288
+ linear = count("linear_attention")
289
+ hv = _integer(config, "linear_num_value_heads", source) if linear else None
290
+ dk = _integer(config, "linear_key_head_dim", source) if hv else None
291
+ dv = _integer(config, "linear_value_head_dim", source) if dk else None
292
+ if dv:
293
+ hk = _integer(config, "linear_num_key_heads", source) or hv
294
+ conv = max(0, (_integer(config, "linear_conv_kernel_dim", source) or 4) - 1) * (2 * hk * dk + hv * dv)
295
+ total += linear * (hv * dk * dv * 4 + conv * 2)
296
+ sliding = count("sliding_attention")
297
+ head_dim = _head_dim(config, source) # crit eval computes it for every config
298
+ window = _sliding_window(config, source) if sliding else None
299
+ if window and head_dim:
300
+ kv_heads = _integer(config, "num_key_value_heads", source) or _integer(config, "num_attention_heads", source)
301
+ if kv_heads is None:
302
+ _fail(source, "num_attention_heads", "missing; sliding_attention layers need a KV head count")
303
+ cache = sliding * 2 * kv_heads * head_dim * window * element # exact for an integer or rational element
304
+ try:
305
+ total += int(cache)
306
+ except (OverflowError, ValueError): # an infinite product
307
+ raise ValueError(f"kv_bytes_per_element {_describe(element)} makes the sliding_attention cache size "
308
+ f"overflow") from None
309
+ return total
310
+
311
+
312
+ def layer_kinds(config, source=CONFIG_NAME):
313
+ """One kind per layer: layer_types mapped ("attention" counts as full, unknown names as OTHER) and required to
314
+ have num_hidden_layers entries; else every full_attention_interval-th layer full and the rest linear attention
315
+ (the layer_types Hugging Face derives from that key); else all full. layer_types may be the list of the layers that
316
+ attend a sliding window (config_keys.json sliding_layer_ids). The FULL_ATTENTION count always equals
317
+ attention_shape's full layers."""
318
+ config = _mapping_of(config, source)
319
+ layers = _layer_count(config, source) if "num_hidden_layers" not in config else None
320
+ if not layers:
321
+ layers = _positive(config, "num_hidden_layers", source)
322
+ if layers > MAX_LAYERS:
323
+ _fail(source, "num_hidden_layers", f"{layers} layers exceed the {MAX_LAYERS}-layer limit")
324
+ types = _layer_types(config, source)
325
+ if types:
326
+ if len(types) != layers:
327
+ _fail(source, "layer_types", f"{len(types)} entries for {layers} layers")
328
+ return tuple(LAYER_KINDS.get(kind, OTHER) for kind in types)
329
+ interval = _integer(config, "full_attention_interval", source)
330
+ if interval:
331
+ return tuple(FULL_ATTENTION if (index + 1) % interval == 0 else LINEAR_ATTENTION for index in range(layers))
332
+ return (FULL_ATTENTION,) * layers
333
+
334
+
335
+ def routed_layers(config, source=CONFIG_NAME):
336
+ """The indices of the layers whose MLP routes experts, in order (() for a model without routed experts): every
337
+ layer from first_k_dense_replace on whose (index + 1) is a multiple of decoder_sparse_step (default 1), less the
338
+ mlp_only_layers, as the checkpoints' reference code places its sparse blocks."""
339
+ config = _mapping_of(config, source)
340
+ if _moe(config, source) is None:
341
+ return ()
342
+ layers = _layer_count(config, source) if "num_hidden_layers" not in config else None
343
+ if not layers:
344
+ layers = _positive(config, "num_hidden_layers", source)
345
+ dense = _integer(config, "first_k_dense_replace", source) or 0
346
+ step = _integer(config, "decoder_sparse_step", source) or 1
347
+ dense_only = set(_integers(config, "mlp_only_layers", source) or ())
348
+ return tuple(i for i in range(dense, layers) if (i + 1) % step == 0 and i not in dense_only)
349
+
350
+
351
+ def layer_applications(config, source=CONFIG_NAME):
352
+ """The checkpoint layer each layer application of a token runs, in order: range(num_hidden_layers) for a plain
353
+ decoder; for a looped one (layer_passes) each looped span repeated its passes in a row, so a span [6, 18) of 3
354
+ passes runs 0..5, 6..17, 6..17, 6..17, 18.. . The applications of one layer share its weights and keep their own
355
+ state (KV, convolution windows) each."""
356
+ config = _mapping_of(config, source)
357
+ layers = _layer_count(config, source) if "num_hidden_layers" not in config else None
358
+ if not layers:
359
+ layers = _positive(config, "num_hidden_layers", source)
360
+ order, index = [], 0
361
+ for start, end, passes in _layer_passes(config, source):
362
+ order.extend(range(index, start))
363
+ order.extend(list(range(start, end)) * passes)
364
+ index = end
365
+ order.extend(range(index, layers))
366
+ return tuple(order)
367
+
368
+
369
+ def _rope_fields(rope, prefix, source):
370
+ """rope_type (else type) and the scaling fields of one rope object, as RopeConfig keywords."""
371
+ def real(key):
372
+ return _real(rope, key, source, f"{prefix}.{key}")
373
+
374
+ kind = _string(rope, "rope_type", source, f"{prefix}.rope_type") \
375
+ or _string(rope, "type", source, f"{prefix}.type") or ""
376
+ return dict(type=kind, factor=real("factor"), attention_factor=real("attention_factor"),
377
+ beta_fast=real("beta_fast"), beta_slow=real("beta_slow"), low_freq_factor=real("low_freq_factor"),
378
+ high_freq_factor=real("high_freq_factor"), mscale=real("mscale"), mscale_all_dim=real("mscale_all_dim"),
379
+ original_max_position_embeddings=_integer(rope, "original_max_position_embeddings", source,
380
+ f"{prefix}.original_max_position_embeddings",
381
+ maximum=UINT64_END - 1),
382
+ short_factor=_reals(rope, "short_factor", source, f"{prefix}.short_factor"),
383
+ long_factor=_reals(rope, "long_factor", source, f"{prefix}.long_factor"),
384
+ mrope_section=_integers(rope, "mrope_section", source, f"{prefix}.mrope_section"),
385
+ raw=rope or _empty()) # already read-only: the section is frozen
386
+
387
+
388
+ def _rope(section, source):
389
+ """(RopeConfig, rope_by_layer_type). A rope object whose members are all objects is keyed by layer type: each
390
+ entry is read like a rope object of its own, with its own rope_theta and partial_rotary_factor."""
391
+ scaling = _object(section, "rope_scaling", source) or {}
392
+ parameters = _object(section, "rope_parameters", source) or {}
393
+ rope_key, rope = ("rope_scaling", scaling) if scaling else ("rope_parameters", parameters)
394
+ values = _rope_fields(rope, rope_key, source)
395
+ layers = []
396
+ if rope and all(isinstance(entry, Mapping) for entry in rope.values()):
397
+ for layer_type, entry in rope.items():
398
+ prefix = f"{rope_key}.{layer_type}"
399
+ fields_read = _rope_fields(entry, prefix, source)
400
+ layers.append(RopeLayer(layer_type, RopeConfig(
401
+ theta=_real(entry, "rope_theta", source, f"{prefix}.rope_theta"),
402
+ partial_rotary_factor=_real(entry, "partial_rotary_factor", source, f"{prefix}.partial_rotary_factor"),
403
+ **fields_read)))
404
+ theta = _real(section, "rope_theta", source)
405
+ if theta is None:
406
+ theta = _real(parameters, "rope_theta", source, "rope_parameters.rope_theta")
407
+ if theta is None:
408
+ theta = _real(scaling, "rope_theta", source, "rope_scaling.rope_theta")
409
+ partial = _real(section, "partial_rotary_factor", source)
410
+ if partial is None:
411
+ partial = _real(rope, "partial_rotary_factor", source, f"{rope_key}.partial_rotary_factor")
412
+ if values["original_max_position_embeddings"] is None:
413
+ values["original_max_position_embeddings"] = _integer(section, "original_max_position_embeddings", source,
414
+ maximum=UINT64_END - 1)
415
+ return RopeConfig(theta=theta, partial_rotary_factor=partial, **values), tuple(layers)
416
+
417
+
418
+ def _moe(section, source):
419
+ experts, key = _first(section, EXPERT_KEYS, _integer, source)
420
+ if not experts:
421
+ return None
422
+ shared, _ = _first(section, ("n_shared_experts", "num_shared_experts"), _integer, source)
423
+ return MoeConfig(experts=experts, experts_key=key,
424
+ experts_per_token=_first(section, EXPERTS_PER_TOKEN_KEYS, _integer, source)[0] or 0,
425
+ shared_experts=shared,
426
+ moe_intermediate_size=_integer(section, "moe_intermediate_size", source),
427
+ shared_expert_intermediate_size=_integer(section, "shared_expert_intermediate_size", source),
428
+ first_k_dense_replace=_integer(section, "first_k_dense_replace", source),
429
+ decoder_sparse_step=_integer(section, "decoder_sparse_step", source),
430
+ n_group=_integer(section, "n_group", source),
431
+ topk_group=_integer(section, "topk_group", source),
432
+ mlp_only_layers=_integers(section, "mlp_only_layers", source),
433
+ norm_topk_prob=_boolean(section, "norm_topk_prob", source),
434
+ routed_scaling_factor=_first(section, ROUTED_SCALING_KEYS, _real, source)[0],
435
+ scoring_func=_string(section, "scoring_func", source) or "",
436
+ topk_method=_string(section, "topk_method", source) or "")
437
+
438
+
439
+ def _mla(section, source):
440
+ rank = _integer(section, "kv_lora_rank", source)
441
+ if not rank:
442
+ return None
443
+ return MlaConfig(kv_lora_rank=rank, qk_rope_head_dim=_integer(section, "qk_rope_head_dim", source) or 0,
444
+ qk_nope_head_dim=_integer(section, "qk_nope_head_dim", source) or 0,
445
+ v_head_dim=_integer(section, "v_head_dim", source) or 0,
446
+ q_lora_rank=_integer(section, "q_lora_rank", source))
447
+
448
+
449
+ def _linear(section, source):
450
+ values = {name: _integer(section, "linear_" + name, source)
451
+ for name in ("num_key_heads", "num_value_heads", "key_head_dim", "value_head_dim", "conv_kernel_dim")}
452
+ return LinearAttentionConfig(**values) if any(value is not None for value in values.values()) else None
453
+
454
+
455
+ # -- one object --------------------------------------------------------------------------------------------------
456
+
457
+ @dataclass(frozen=True)
458
+ class Architecture:
459
+ """A ModelConfig (`config`) with the mechanism sections its text section states, and the rules over them. Every
460
+ field of the ModelConfig reads through it (architecture.hidden_size is config.hidden_size). rope_by_layer_type
461
+ holds one RopeLayer per entry of a rope object keyed by layer type, in file order; layer_passes the looped spans
462
+ ((start, end, passes), ...)."""
463
+ config: ModelConfig
464
+ rope: RopeConfig = field(default_factory=RopeConfig)
465
+ rope_by_layer_type: tuple = ()
466
+ sliding_window: int | None = None
467
+ full_attention_interval: int | None = None
468
+ layer_types: tuple = ()
469
+ moe: MoeConfig | None = None
470
+ mla: MlaConfig | None = None
471
+ linear: LinearAttentionConfig | None = None
472
+ num_nextn_predict_layers: int | None = None
473
+ layer_passes: tuple = ()
474
+
475
+ def __getattr__(self, name):
476
+ if name.startswith("__") or name == "config":
477
+ raise AttributeError(name)
478
+ return getattr(self.config, name)
479
+
480
+ def attention_shape(self):
481
+ return attention_shape(self.section, source=self.source)
482
+
483
+ def attention_geometry(self):
484
+ return attention_geometry(self.section, source=self.source)
485
+
486
+ def layer_kinds(self):
487
+ return layer_kinds(self.section, source=self.source)
488
+
489
+ def kv_elements_per_token(self):
490
+ return kv_elements_per_token(self.section, source=self.source)
491
+
492
+ def fixed_state_bytes(self, kv_bytes_per_element):
493
+ return fixed_state_bytes(self.section, kv_bytes_per_element, source=self.source)
494
+
495
+ def routed_layers(self):
496
+ return routed_layers(self.section, source=self.source)
497
+
498
+ def layer_applications(self):
499
+ return layer_applications(self.section, source=self.source)
500
+
501
+
502
+ def architecture(config, source=CONFIG_NAME):
503
+ """The Architecture of a ModelConfig, an Architecture (returned as it is) or a parsed config mapping."""
504
+ if isinstance(config, Architecture):
505
+ return config
506
+ if not isinstance(config, ModelConfig):
507
+ config = parse_model_config(config, source)
508
+ section, where = config.section, config.source
509
+ rope, rope_by_layer_type = _rope(section, where)
510
+ return Architecture(config=config, rope=rope, rope_by_layer_type=rope_by_layer_type,
511
+ sliding_window=_sliding_window(section, where),
512
+ full_attention_interval=_integer(section, "full_attention_interval", where),
513
+ layer_types=_layer_types(section, where) or (),
514
+ moe=_moe(section, where), mla=_mla(section, where), linear=_linear(section, where),
515
+ num_nextn_predict_layers=_integer(section, "num_nextn_predict_layers", where),
516
+ layer_passes=_layer_passes(section, where))
517
+
518
+
519
+ __all__ = ["Architecture", "ConfigError", "FULL_ATTENTION", "LINEAR_ATTENTION", "LinearAttentionConfig", "MlaConfig",
520
+ "MoeConfig", "OTHER", "RopeConfig", "RopeLayer", "SLIDING_ATTENTION", "architecture", "attention_geometry",
521
+ "attention_shape", "fixed_state_bytes", "kv_elements_per_token", "layer_applications", "layer_kinds",
522
+ "routed_layers"]
@@ -0,0 +1,54 @@
1
+ {
2
+ "about": "Which config.json keys spell each mechanism field, in the order they are tried (crit_models.config loads it). A family that spells a field its own way adds its key here, never a branch in a reader. sliding_layer_ids: the layers that attend a sliding window (the layer kinds of a config without layer_types). sliding_window: the window's size. routed_scaling_factor: the factor the routed experts' weights are scaled by. layer_passes: objects naming a span of layers [start, end) that runs `passes` times in a row with the same weights, each pass with its own state (a looped decoder): the object's key (null: the keys are the config's own) and its keys of the three numbers. layer_type_names: a family's own names of the layer types in layer_types, read as the names they stand for. full_attention_*: the geometry of full-attention layers where it differs from the other attention layers' (num_key_value_heads, head_dim), and a flag that their keys and values are one cached tensor.",
3
+ "experts": [
4
+ "num_experts",
5
+ "num_local_experts",
6
+ "n_routed_experts"
7
+ ],
8
+ "experts_per_token": [
9
+ "num_experts_per_tok",
10
+ "top_k_experts"
11
+ ],
12
+ "full_attention_kv_heads": [
13
+ "num_global_key_value_heads"
14
+ ],
15
+ "full_attention_head_dim": [
16
+ "global_head_dim"
17
+ ],
18
+ "full_attention_keys_equal_values": [
19
+ "attention_k_eq_v"
20
+ ],
21
+ "layer_types": [
22
+ "layer_types",
23
+ "layers_block_type"
24
+ ],
25
+ "sliding_layer_ids": [
26
+ "local_layer_ids"
27
+ ],
28
+ "sliding_window": [
29
+ "sliding_window",
30
+ "sliding_window_size"
31
+ ],
32
+ "routed_scaling_factor": [
33
+ "routed_scaling_factor",
34
+ "route_scale"
35
+ ],
36
+ "layer_passes": [
37
+ {
38
+ "object": "loop_config",
39
+ "start": "core_start",
40
+ "end": "core_end",
41
+ "passes": "num_passes"
42
+ },
43
+ {
44
+ "object": null,
45
+ "start": "loop_layer_index_start",
46
+ "end": "loop_layer_index_end",
47
+ "passes": "loop_num_passes"
48
+ }
49
+ ],
50
+ "layer_type_names": {
51
+ "hybrid": "full_attention",
52
+ "hybrid_sliding": "sliding_attention"
53
+ }
54
+ }
crit_models/gguf.py ADDED
@@ -0,0 +1,65 @@
1
+ """What a GGUF's metadata must agree with in a config.json beside it, for the mechanisms crit_models reads: the
2
+ attention layers' KV heads and head sizes by layer kind, the experts and the rotary base. Core's check of a GGUF folder
3
+ (crit_core.model.gguf.check_gguf_folder) compares the generic shape and runs these through crit_core.registry
4
+ (gguf_checks), which this package registers when it is imported and, installed, by its entry point."""
5
+ from crit_core.model.gguf import _array_or, _same_float
6
+
7
+ from .config import FULL_ATTENTION, SLIDING_ATTENTION, ConfigError, architecture
8
+
9
+
10
+ def compare_attention(model, config, drafts, compare, errors):
11
+ """KV heads and head sizes of the GGUF's attention layers against config.json's per layer kind
12
+ (Architecture.attention_geometry): a per-layer head_count_kv list is compared layer by layer (0 marks a layer
13
+ without attention, draft blocks are not compared), and key_length_swa, where the GGUF has it, is the sliding
14
+ layers' head size beside key_length, the full layers'."""
15
+ get = model.get
16
+ config = architecture(config)
17
+ geometry = config.attention_geometry()
18
+ try:
19
+ kinds = config.layer_kinds() if geometry else None
20
+ except ConfigError:
21
+ kinds = None
22
+ kv = get(".attention.head_count_kv")
23
+ if isinstance(kv, tuple) and kinds and len(kv) in (len(kinds), len(kinds) + drafts):
24
+ for index, (found, kind) in enumerate(zip(kv, kinds)):
25
+ expected = geometry[kind][0] if kind in geometry else None
26
+ if found and expected is not None and found != expected:
27
+ errors.append(f"key/value heads: GGUF {found} at layer {index} ({kind}), config.json {expected}")
28
+ break
29
+ elif geometry and kinds:
30
+ expected = {geometry[kind][0] for kind in set(kinds) if kind in geometry}
31
+ values = {v for v in _array_or(kv) if v} if kv is not None else set()
32
+ if values and expected and not values <= expected:
33
+ errors.append(f"key/value heads: GGUF {sorted(values) if len(values) > 1 else next(iter(values))}, "
34
+ f"config.json {sorted(expected) if len(expected) > 1 else next(iter(expected))}")
35
+ else:
36
+ compare("key/value heads", kv, config.num_key_value_heads)
37
+ declared = config.head_dim is not None
38
+ full_dim = geometry[FULL_ATTENTION][1] if geometry and (declared or geometry[FULL_ATTENTION][1] != geometry[
39
+ SLIDING_ATTENTION][1]) else config.head_dim
40
+ swa = get(".attention.key_length_swa")
41
+ compare("head size", get(".attention.key_length"), full_dim)
42
+ if swa is not None:
43
+ compare("sliding head size", swa, geometry[SLIDING_ATTENTION][1] if geometry and declared else None)
44
+
45
+
46
+ def compare_mlp(model, config, drafts, compare, errors):
47
+ """The MLP width of a dense decoder, or the experts' count, per-token count and width of a mixture of experts."""
48
+ get, config = model.get, architecture(config)
49
+ if config.moe is None:
50
+ compare("MLP width", get(".feed_forward_length"), config.intermediate_size)
51
+ else:
52
+ compare("experts", get(".expert_count"), config.moe.experts)
53
+ compare("experts per token", get(".expert_used_count"), config.moe.experts_per_token)
54
+ compare("expert MLP width", get(".expert_feed_forward_length"), config.moe.moe_intermediate_size)
55
+
56
+
57
+ def compare_rope(model, config, drafts, compare, errors):
58
+ """The rotary base."""
59
+ found, value = model.get(".rope.freq_base"), architecture(config).rope.theta
60
+ if found is not None and value is not None and not _same_float(found, value):
61
+ errors.append(f"RoPE base: GGUF {found}, config.json {value}")
62
+
63
+
64
+ # crit_core.registry gguf_checks: run in name order.
65
+ CHECKS = {"attention": compare_attention, "mlp": compare_mlp, "rope": compare_rope}