Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
106 commits
Select commit Hold shift + click to select a range
2db9a15
Add GLM-5.1 model config with 4-layer sanity training check
notabee Jul 14, 2026
23b2d89
Register glm5.1-744b model name in Pydantic schema
notabee Jul 14, 2026
394d434
Set default attention backend to dot_product for GLM-5.1
notabee Jul 14, 2026
ac4abef
Configure dtype and weight_dtype to bfloat16 for GLM-5.1
notabee Jul 14, 2026
27c9f07
fix(ci): add minimum version limits to tokenizer dependencies and wra…
notabee Jul 15, 2026
a0039da
feat(checkpoint): register glm5.1-744b model config and parameter map…
notabee Jul 15, 2026
963fc53
Optimize LazyHFLoader by caching open safetensors file readers
notabee Jul 22, 2026
53412b7
Update GLM-5.1 model config to use full 78 decoder layers by default
notabee Jul 27, 2026
c691c6a
fix: move model_prefix scope in logit checker to prevent UnboundLocal…
notabee Jul 28, 2026
c044181
feat: GLM-5.1 onboarding with per-head MLA projection mapping, interl…
notabee Jul 29, 2026
e915590
ci: backport zizmor workflow security audit fixes from upstream
notabee Aug 5, 2026
711038d
Merge remote-tracking branch 'origin/main' into onboard-glm5.1
notabee Aug 5, 2026
614d378
fix(lint): remove duplicate imports and apply minimal pyink formattin…
notabee Aug 5, 2026
72aa2f0
fix(test): guard chex import with pytest.importorskip in pallas_mosai…
notabee Aug 5, 2026
2a97b6e
fix(lint): add blank line before importorskip in pallas_mosaic_tpu_v2…
notabee Aug 5, 2026
3943faa
fix(init): remove unused torch and transformers imports from maxtext.…
notabee Aug 5, 2026
3d2b79d
Merge remote-tracking branch 'origin/main' into onboard-glm5.1
notabee Aug 6, 2026
9747716
fix(attention): restore standard Attention to use RotaryEmbedding and…
notabee Aug 6, 2026
6bd8ad3
feat(checkpoint): restore GLM-5.1 MLA transpose hooks and end-to-end …
notabee Aug 6, 2026
940ceb0
Fix 3D scanned tensor layer dimension scrambling in GLM wkv_b and wq_…
notabee Aug 6, 2026
08c52f3
pyink formatting
notabee Aug 6, 2026
b7828c4
fix(checkpoint): correctly transpose scanned layer dimensions for GLM…
notabee Aug 7, 2026
bad4164
fix(checkpoint_conversion): bounded memory cache in LazyHFLoader to p…
notabee Aug 7, 2026
5fde5d7
Fix GLM-5.1 MoE routing and pre_bias_logits in MaxText
notabee Aug 7, 2026
0218e5e
Fix MoE inference combine_mask weights and indexer RoPE interleave fo…
notabee Aug 7, 2026
04b383c
Fix parameter mapping bounds and 4D/3D/2D transpose hooks for GLM-5.1
notabee Aug 8, 2026
5bb2fd2
style: format param_mapping.py with pyink
notabee Aug 9, 2026
b3505ca
Remove partial layer truncation logic and use full config layer counts
notabee Aug 9, 2026
a0b4279
feat: support metadata_axis_name in NNXDecoder._apply_layers_sequenti…
notabee Aug 10, 2026
8125ca4
Merge remote-tracking branch 'origin/main' into onboard-glm5.1
notabee Aug 10, 2026
5e6236b
style: format with pyink 2-space indentation and clean up pylint warn…
notabee Aug 10, 2026
fd0e960
feat(glm5.2): add native cross-layer IndexShare and checkpoint conver…
notabee Aug 10, 2026
97318ff
refactor(glm5): isolate GLM decoder layers into models/glm5.py and re…
notabee Aug 10, 2026
874baa2
fix(config): add glm5.2-744b to ModelName Literal in types.py
notabee Aug 10, 2026
c984596
fix(glm5): register DecoderBlockType.GLM5 in get_norm_layer, decoder …
notabee Aug 10, 2026
4c2cf74
fix(conversion): transparently resolve missing indexer keys on shared…
notabee Aug 10, 2026
9fc3767
fix(utils): export get_donor_layer_idx in index_share_utils.py
notabee Aug 10, 2026
71a1f3f
fix(conversion): dynamically find matching indexer donor layers from …
notabee Aug 10, 2026
5bdce25
feat(tests): add GLM-5.2 end-to-end conversion and execution test scr…
notabee Aug 11, 2026
3bc1393
feat(glm5.2): explicitly pass IndexShare configuration in test script
notabee Aug 11, 2026
325e42f
feat(eval): add GLM-5.2 sanity evaluation and prompt generation script
notabee Aug 11, 2026
5d47740
feat(xprof): add named scopes glm_full_layer_indexer and glm_shared_l…
notabee Aug 11, 2026
edd4688
fix(glm5): initialize default is_shared_layer and served_group_size f…
notabee Aug 11, 2026
a5b64e6
feat(glm5.2): enable IndexShare carry in scanned layers execution
notabee Aug 11, 2026
00eb672
fix(profiler): block until ready on active profiled steps to capture …
notabee Aug 11, 2026
ecc8152
fix(indexshare): provide invariant concrete dummy tensor structure fo…
notabee Aug 11, 2026
64bc8e5
fix(decoder): fix indentation of scanned use_index_share execution block
notabee Aug 11, 2026
171a6ba
fix(mla): call correct mla_query_projection method
notabee Aug 11, 2026
aae73ee
fix(mla): use jax.lax.cond for scanned indexer conditional execution
notabee Aug 11, 2026
e55e0a7
fix(indexshare): match exact dummy indexer mask and score shapes and …
notabee Aug 11, 2026
6a07b6e
chore: remove scratch script from repository
notabee Aug 11, 2026
b8b5183
fix(glm5.2): address review comments for indexshare and checkpoint co…
notabee Aug 13, 2026
0cb9cce
[re-verification] fix(mla): store indexshare metadata as static tuple…
notabee Aug 16, 2026
9e0c63f
[re-verification] fix(mla): bypass indexer cond branch when seqlen <=…
notabee Aug 16, 2026
ddaa018
[re-verification] fix(conversion): correct GLM scanned layer transpos…
notabee Aug 16, 2026
8551103
[re-verification] fix(glm5): add **kwargs to GLMDenseLayer and GLMMoE…
notabee Aug 16, 2026
25f6aea
Fix GLM MLA wq_b and wkv_b global split weight mapping in param_mappi…
notabee Aug 17, 2026
5b51084
Update reshape_out_kernel and reshape_indexer_wq_b_kernel to adaptive…
notabee Aug 17, 2026
d157b9d
Create dedicated GLM_MAXTEXT_TO_HF_PARAM_MAPPING and GLM_MAXTEXT_TO_H…
notabee Aug 17, 2026
e520cb4
Register GLM in HF_SHAPE
notabee Aug 17, 2026
0c676e3
fix(glm5.2): update rope_theta to 8000000 and index_share_pattern to …
notabee Aug 17, 2026
12c710d
fix(glm5.2): correct wkv_b and wq_b projection reshape hooks for per-…
notabee Aug 17, 2026
7305512
fix(conversion): align unscan key names in GLM hook mapping
notabee Aug 17, 2026
76ef8f4
fix(nnx): add fallback for Pytree import to support Flax 0.10
notabee Aug 18, 2026
588864b
fix(compatibility): alias MutableHiType to HiType for Flax 0.12 JAX c…
notabee Aug 18, 2026
7c0843f
feat: add standalone generation test for GLM-5.2 on TPU
notabee Aug 18, 2026
9491873
fix(mesh): correctly instantiate jax Mesh in verify_glm52_generation.py
notabee Aug 18, 2026
0288483
perf(decode): add @nnx.jit and streaming token printing for GLM-5.2 g…
notabee Aug 18, 2026
104fe6d
fix(import): import maxtext first to apply compatibility hooks
notabee Aug 18, 2026
505693e
feat: test user prompts with chat template and base completion on GLM…
notabee Aug 18, 2026
340a7a2
feat: match exact raw token inputs from golden dataset
notabee Aug 18, 2026
11a53e3
Fix GLM-5.1/5.2 RoPE interleave configuration and verify_glm52_genera…
notabee Aug 18, 2026
18174ae
fix(verify_glm52): extract input_ids when apply_chat_template returns…
notabee Aug 18, 2026
aeba8a7
feat(verify_glm52): add temperature and top-p sampling with special t…
notabee Aug 19, 2026
004d47b
fix(verify_glm52): use decode_sampling_temperature and decode_samplin…
notabee Aug 19, 2026
322c827
feat(glm5.2): enable float32 gate logits for router precision
notabee Aug 20, 2026
9114ae3
fix(maxengine): support scanned layers in kv cache insertion
notabee Aug 22, 2026
ca3e0f7
fix(glm5.2): prevent duplicate self_attention init and support glm5 i…
notabee Aug 22, 2026
ab65feb
fix(attentions): use qk_head_dim and v_head_dim in init_kv_caches
notabee Aug 22, 2026
3d5a0fc
fix(maxengine): add gc.collect after parameter loading
notabee Aug 22, 2026
941235c
fix(maxengine): import gc module
notabee Aug 22, 2026
b4bb1ef
feat(inference): enable clean decoupled tokenizer in decode and maxen…
notabee Aug 22, 2026
de180ff
fix(gcloud_stub): robust HuggingFace/PreTrainedTokenizerFast/tokenize…
notabee Aug 22, 2026
95a58f8
fix(gcloud_stub): use hf_hub_download for tokenizer.json
notabee Aug 22, 2026
1bd7548
fix(maxengine): safely check pad_token_id on tokenizers backend
notabee Aug 22, 2026
59df06c
fix(gcloud_stub): register ResultTokens as JAX PyTree node
notabee Aug 22, 2026
c2244ee
fix(gcloud_stub): implement get_result_at_slot on ResultTokens
notabee Aug 22, 2026
27eedca
chore: remove unused verify script and revert gcloud_stub, decode, an…
notabee Aug 22, 2026
de0cfc9
clean: remove temporary monkeypatch from __init__.py
notabee Aug 22, 2026
a2e2bb5
feat(gcloud_stub): provide complete decoupled HuggingFaceTokenizer an…
notabee Aug 22, 2026
a959e8a
revert: keep gcloud_stub and decode completely untouched matching main
notabee Aug 22, 2026
83a6fce
feat(gcloud_stub): provide complete decoupled HuggingFaceTokenizer an…
notabee Aug 22, 2026
7472ed0
fix(glm5.2): make group_size loss scaling compatible with JAX scan tr…
notabee Aug 23, 2026
ac4278e
Merge branch 'main' into feat/glm5.2-indexshare
notabee Aug 23, 2026
ab14b28
fix(inference): add decoupled tokenizer fallbacks, pytree result toke…
notabee Aug 23, 2026
6e23fea
style: apply pyink formatting and resolve all pylint warnings
notabee Aug 23, 2026
ebd548b
test(glm5): validate end-to-end test scripts for GLM-5.1 and GLM-5.2 …
notabee Aug 23, 2026
e290570
chore: remove Run_GLM5.md and glm-5.1 end-to-end tests
notabee Aug 23, 2026
36a5744
fix(indexshare): return new_indexer_state from MLA.__call__ avoiding …
notabee Aug 24, 2026
44e2201
fix(indexshare): pass cached_indexer_state directly through sequentia…
notabee Aug 24, 2026
e31918d
style: resolve unbalanced-tuple-unpacking linter warnings in unit tests
notabee Aug 24, 2026
e01237a
fix: use getattr with defaults in print_compiled_memory_stats for JAX…
notabee Aug 24, 2026
acd8745
fix: safely extract setup_params in train_loop for NNX and Linen models
notabee Aug 24, 2026
27e8ba0
fix: safely handle zero limit in print_mem_stats
notabee Aug 24, 2026
d23a819
fix: safely guard optional pathwaysutils import in train.py
notabee Aug 24, 2026
f4769ba
fix: safely guard multi_tier_checkpointing import in max_utils.py
notabee Aug 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/dependencies/requirements/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ pylint
pytest
pytype
qwix>=0.1.6
sentencepiece
sentencepiece>=0.2.0
tensorboard-plugin-profile
tensorboardx
tensorflow-datasets
tensorflow-text
tensorflow
tiktoken
tiktoken>=0.5.0
tokamax>=0.0.4
transformers
google-jetstream @ https://github.com/AI-Hypercomputer/JetStream/archive/29329e8e73820993f77cfc8efe34eb2a73f5de98.zip
Expand Down
78 changes: 74 additions & 4 deletions src/maxtext/checkpoint_conversion/to_maxtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
from functools import partial
import json
import os
import re
import sys
import threading
import time
Expand Down Expand Up @@ -119,20 +120,25 @@ def __init__(self, model_id, token, revision=None):
self.current_shard_content = {}
# Cache for resolved local shard paths
self._local_shard_paths = {}
# Cache for open safetensors file readers
self._open_files = {}
# Use a lock to serialize heavy RAM operations, but NOT downloads
self._ram_lock = threading.Lock()
self._initialize_index()

def __getstate__(self):
"""Allows pickling/copying by excluding the non-pickleable lock."""
"""Allows pickling/copying by excluding the non-pickleable lock and files."""
state = self.__dict__.copy()
del state["_ram_lock"]
if "_open_files" in state:
del state["_open_files"]
return state

def __setstate__(self, state):
"""Restores state after pickling/copying and recreates a new lock."""
"""Restores state after pickling/copying and recreates a new lock and file cache."""
self.__dict__.update(state)
self._ram_lock = threading.Lock()
self._open_files = {}

def _initialize_index(self):
"""Fetches and parses the Hugging Face model index file to build a shard map."""
Expand Down Expand Up @@ -206,7 +212,17 @@ def get_tensor(self, key: str) -> np.ndarray:
# This prevents multiple threads from simultaneously allocating large chunks of RAM.
with self._ram_lock:
with safe_open(local_path, framework="np", device="cpu") as f:
return f.get_tensor(key)
tensor = f.get_tensor(key)
# Prune older downloaded shards if downloading remotely to prevent disk/RAM exhaustion
if not self.is_local and len(self._local_shard_paths) > 3:
oldest_shard = next(iter(self._local_shard_paths))
oldest_path = self._local_shard_paths.pop(oldest_shard)
if os.path.exists(oldest_path):
try:
os.remove(oldest_path)
except OSError:
pass
return tensor


class LazyTensor:
Expand Down Expand Up @@ -448,7 +464,28 @@ def _build_single_axis_stacked_tensor(
if isinstance(hf_key_single, (list, tuple)):
hf_tensor_numpy = tuple(tensor_getter_fn(k) for k in hf_key_single)
else:
hf_tensor_numpy = tensor_getter_fn(hf_key_single)
try:
hf_tensor_numpy = tensor_getter_fn(hf_key_single)
except (ValueError, KeyError) as e:
if "indexer" in str(hf_key_single) and str(hf_key_single).startswith("model.layers."):
m = re.match(r"model\.layers\.(\d+)\.(.+)", str(hf_key_single))
if m:
layer_idx = int(m.group(1))
rest = m.group(2)
# Search backwards for the closest preceding donor layer containing the key
for candidate_idx in range(layer_idx - 1, -1, -1):
donor_key = f"model.layers.{candidate_idx}.{rest}"
try:
hf_tensor_numpy = tensor_getter_fn(donor_key)
break
except Exception: # pylint: disable=broad-exception-caught
continue
else:
hf_tensor_numpy = np.zeros(mt_slice_shape, dtype=np.float32)
else:
raise e
else:
raise e
processed_hf_tensor = apply_hook_fns(hf_tensor_numpy, mt_slice_shape, hook_fns)
tensors_to_stack.append(processed_hf_tensor)

Expand Down Expand Up @@ -984,6 +1021,16 @@ def main(

def _eager_getter(key):
if key not in hf_state_dict_numpy:
if getattr(config, "use_index_share", False) and "indexer" in key and key.startswith("model.layers."):
m = re.match(r"model\.layers\.(\d+)\.(.+)", key)
if m:
layer_idx = int(m.group(1))
rest = m.group(2)
# Search backwards for the closest preceding donor layer containing the key
for candidate_idx in range(layer_idx - 1, -1, -1):
donor_key = f"model.layers.{candidate_idx}.{rest}"
if donor_key in hf_state_dict_numpy:
return _eager_getter(donor_key)
raise ValueError(f"HuggingFace key {key} not found in state_dict.")
v = hf_state_dict_numpy[key]
# target dtype is "float32"
Expand All @@ -1002,6 +1049,29 @@ def _eager_getter(key):

tensor_getter = _eager_getter

if getattr(config, "use_index_share", False):
orig_tensor_getter = tensor_getter

def _index_share_tensor_getter(key):
try:
return orig_tensor_getter(key)
except (ValueError, KeyError) as e:
if "indexer" in key and key.startswith("model.layers."):
m = re.match(r"model\.layers\.(\d+)\.(.+)", key)
if m:
layer_idx = int(m.group(1))
rest = m.group(2)
# Search backwards for the closest preceding donor layer containing the key
for candidate_idx in range(layer_idx - 1, -1, -1):
donor_key = f"model.layers.{candidate_idx}.{rest}"
try:
return orig_tensor_getter(donor_key)
except (ValueError, KeyError):
continue
raise e

tensor_getter = _index_share_tensor_getter

if is_merge_mode:
tensor_getter = _setup_merge_mode_getter(tensor_getter, config, hf_lora_adapter_path, revision)

Expand Down
19 changes: 19 additions & 0 deletions src/maxtext/checkpoint_conversion/utils/hf_model_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1884,8 +1884,27 @@ def __init__(self, **kwargs):
qwen3_vl_30b_a3b_config = PTConfig(**qwen3_vl_30b_a3b_dict)


glm5_1_744b_dict = {
"architectures": ["GlmMoeDsaForCausalLM"],
"num_hidden_layers": 78,
"first_k_dense_replace": 3,
"n_routed_experts": 256,
}
glm5_1_744b_config = transformers.DeepseekV3Config(**glm5_1_744b_dict)

glm5_2_744b_dict = {
"architectures": ["GlmMoeDsaForCausalLM"],
"num_hidden_layers": 78,
"first_k_dense_replace": 3,
"n_routed_experts": 256,
}
glm5_2_744b_config = transformers.DeepseekV3Config(**glm5_2_744b_dict)


# {maxtext model name: hf model config}
HF_MODEL_CONFIGS = {
"glm5.1-744b": glm5_1_744b_config,
"glm5.2-744b": glm5_2_744b_config,
"gemma2-2b": gemma2_2b_config,
"gemma2-9b": gemma2_9b_config,
"gemma2-27b": gemma2_27b_config,
Expand Down
2 changes: 2 additions & 0 deletions src/maxtext/checkpoint_conversion/utils/hf_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,8 @@ def DEEPSEEKV4_HF_WEIGHTS_TO_SHAPE(config):
"deepseek3-671b": DEEPSEEK_HF_WEIGHTS_TO_SHAPE,
"deepseek3.2-671b": DEEPSEEK_HF_WEIGHTS_TO_SHAPE,
"deepseek4-284b": DEEPSEEKV4_HF_WEIGHTS_TO_SHAPE,
"glm5.1-744b": DEEPSEEK_HF_WEIGHTS_TO_SHAPE,
"glm5.2-744b": DEEPSEEK_HF_WEIGHTS_TO_SHAPE,
"gpt-oss-20b": GPT_OSS_HF_WEIGHTS_TO_SHAPE,
"gpt-oss-120b": GPT_OSS_HF_WEIGHTS_TO_SHAPE,
"mixtral-8x7b": MIXTRAL_HF_WEIGHTS_TO_SHAPE,
Expand Down
Loading
Loading