Jinrui commited on
Commit
0bbb60d
·
verified ·
1 Parent(s): ca230aa

Upload folder using huggingface_hub

Browse files
Files changed (25) hide show
  1. .gitattributes +1 -0
  2. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/added_tokens.json +28 -0
  3. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/config.json +62 -0
  4. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/generation_config.json +7 -0
  5. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  6. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  7. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
  8. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
  9. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/mp_rank_00_model_states.pt +3 -0
  10. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/latest +1 -0
  11. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/merges.txt +0 -0
  12. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/model.safetensors +3 -0
  13. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/modeling_qwen3_hyp.py +182 -0
  14. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_0.pth +3 -0
  15. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_1.pth +3 -0
  16. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_2.pth +3 -0
  17. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_3.pth +3 -0
  18. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/scheduler.pt +3 -0
  19. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/special_tokens_map.json +31 -0
  20. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/tokenizer.json +3 -0
  21. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/tokenizer_config.json +241 -0
  22. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/trainer_state.json +633 -0
  23. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/training_args.bin +3 -0
  24. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/vocab.json +0 -0
  25. checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/zero_to_fp32.py +604 -0
.gitattributes CHANGED
@@ -67,3 +67,4 @@ checkpoints/qwen3/qwen3_p686m_t1_16_suite-owt_scaling_v3_family-qwen3_geometry_i
67
  checkpoints/qwen3/qwen3_p686m_t1_32_suite-owt_scaling_v3_family-qwen3_geometry_id-euclid_variant-base_init_slope-std/attempt1_20260210_015704/checkpoint-768/tokenizer.json filter=lfs diff=lfs merge=lfs -text
68
  checkpoints/qwen3/qwen3_p686m_t1_64_suite-owt_scaling_v3_family-qwen3_geometry_id-euclid_variant-base_init_slope-std/attempt1_20260209_200044/checkpoint-501/tokenizer.json filter=lfs diff=lfs merge=lfs -text
69
  checkpoints/qwen3_hyp/qwen3_hyp_p020m_t1_64_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260211_213320/checkpoint-501/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
67
  checkpoints/qwen3/qwen3_p686m_t1_32_suite-owt_scaling_v3_family-qwen3_geometry_id-euclid_variant-base_init_slope-std/attempt1_20260210_015704/checkpoint-768/tokenizer.json filter=lfs diff=lfs merge=lfs -text
68
  checkpoints/qwen3/qwen3_p686m_t1_64_suite-owt_scaling_v3_family-qwen3_geometry_id-euclid_variant-base_init_slope-std/attempt1_20260209_200044/checkpoint-501/tokenizer.json filter=lfs diff=lfs merge=lfs -text
69
  checkpoints/qwen3_hyp/qwen3_hyp_p020m_t1_64_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260211_213320/checkpoint-501/tokenizer.json filter=lfs diff=lfs merge=lfs -text
70
+ checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/tokenizer.json filter=lfs diff=lfs merge=lfs -text
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3HypForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoModel": "modeling_qwen3_hyp.Qwen3HypForCausalLM",
9
+ "AutoModelForCausalLM": "modeling_qwen3_hyp.Qwen3HypForCausalLM"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "dtype": "bfloat16",
13
+ "eos_token_id": 151645,
14
+ "head_dim": 128,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1536,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 4608,
19
+ "layer_types": [
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention"
44
+ ],
45
+ "lorentz_k0": 1.0,
46
+ "max_position_embeddings": 40960,
47
+ "max_window_layers": 24,
48
+ "model_type": "qwen3",
49
+ "num_attention_heads": 24,
50
+ "num_hidden_layers": 24,
51
+ "num_key_value_heads": 12,
52
+ "rms_norm_eps": 1e-06,
53
+ "rope_scaling": null,
54
+ "rope_theta": 1000000,
55
+ "sliding_window": null,
56
+ "tie_word_embeddings": true,
57
+ "torch_dtype": "bfloat16",
58
+ "transformers_version": "4.51.3",
59
+ "use_cache": false,
60
+ "use_sliding_window": false,
61
+ "vocab_size": 151936
62
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.51.3",
6
+ "use_cache": false
7
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3c7249ad4e510b5321bd46c07b7184c9cd95fb4c2024b5d9e09aee8a17e8468
3
+ size 4649116636
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b1ef916768f5d1a1e62f0e2d3397ecfee26a36126885054cf3b6e062dead27b
3
+ size 4649121116
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:326994942405436f70ce347aff40160559e72cd6a925e8cea9e3f5467c1792db
3
+ size 4649119580
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09691c94f59cbfc8f22cdedadb9ca6fde0f69a63d089bfd20edd76c1ec242e7d
3
+ size 4649113628
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/global_step8192/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ea24852f1f2c7402d8fd25bcb38d96c191de528cb72ab6b150acf3261db188c
3
+ size 3099482616
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step8192
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4129da1575ac4378687d61f61aea116ccfef4ee25982d5e0c7f00198be8b99d
3
+ size 3566487508
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/modeling_qwen3_hyp.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hyperbolic-tail adapter for Qwen3.
3
+
4
+ This wrapper keeps the original Qwen3 stack unchanged and only projects the
5
+ final hidden state onto a Lorentz hyperboloid before the vocabulary projection.
6
+ The projection uses a learnable curvature (softplus-parameterized) and a
7
+ learnable per-dimension scaling to stabilize norms. A new lm_head is created
8
+ with an extra time dimension; existing weights are copied into the spatial
9
+ coordinates and the time coordinate is initialized to zero.
10
+ """
11
+
12
+ import math
13
+ from typing import Any, Optional
14
+
15
+ import torch
16
+ import torch.distributed as dist
17
+ import torch.nn.functional as F
18
+ from transformers.modeling_outputs import CausalLMOutputWithPast
19
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3ForCausalLM
20
+
21
+
22
+ class Qwen3HypForCausalLM(Qwen3ForCausalLM):
23
+ """
24
+ Qwen3 with a hyperbolic (Lorentz) projection applied only at the output.
25
+ Fixed: Uses correct Exponential Map (cosh) and Minkowski Inner Product.
26
+ Includes Logit Scaling to match initialization variance with Euclidean baseline.
27
+ """
28
+
29
+ def __init__(self, config: Any):
30
+ super().__init__(config)
31
+
32
+ hidden = self.lm_head.weight.shape[1]
33
+ vocab = self.lm_head.weight.shape[0]
34
+
35
+ # 1. 曲率参数 (Learnable curvature)
36
+ k0 = getattr(config, "lorentz_k0", 1.0)
37
+ self.k_param = torch.nn.Parameter(torch.log(torch.expm1(torch.tensor(float(k0)))))
38
+
39
+ # 2. 模长缩放 (Norm Scaling)
40
+ # 初始化为 sqrt(hidden) 是个很好的 trick,能让初始输入模长接近 1.0
41
+ init_scale = math.sqrt(hidden)
42
+ self.lora_norm_scale = torch.nn.Parameter(torch.full((hidden,), init_scale))
43
+
44
+ # 3. Logit Scale (Compensation for Hyperbolic Projection norm reduction)
45
+ # 目标:让双曲输入的能量与欧氏 RMSNorm 后的能量一致
46
+ # Ratio = sqrt(D) / sinh(1.0)
47
+ init_scale_factor = math.sqrt(hidden) / math.sinh(1.0)
48
+ # 使用 log 参数化是为了数值稳定,保证 scale 恒为正
49
+ self.logit_scale = torch.nn.Parameter(torch.tensor(math.log(init_scale_factor)))
50
+
51
+ # 4. 备份与初始化 Head
52
+ old_w = self.lm_head.weight.data
53
+ self.euclidean_head = torch.nn.Linear(hidden, vocab, bias=False)
54
+ self.euclidean_head.weight.data.copy_(old_w)
55
+
56
+ # Hyperbolic Head
57
+ # 我们使用 Linear 实现闵可夫斯基内积,但在 forward 中会使用 Input-Flipping Trick
58
+ new_w = torch.zeros((vocab, hidden + 1), dtype=old_w.dtype, device=old_w.device)
59
+ new_w[:, 1:] = old_w
60
+ # 时间维权重初始化为0:初始状态下 <x, w>_L = -0*x0 + ws*xs = Euclidean Dot Product
61
+ # 这保证了模型从欧氏空间平滑过渡。
62
+ self.hyper_head = torch.nn.Linear(hidden + 1, vocab, bias=False)
63
+ self.hyper_head.weight.data.copy_(new_w)
64
+
65
+ self.lm_head = self.hyper_head
66
+
67
+ def _project_hyperbolic(self, x: torch.Tensor) -> torch.Tensor:
68
+ """
69
+ Correct Exponential Map: Tangent Space -> Lorentz Hyperboloid
70
+ """
71
+ # [Stability] 在 Scaling 实验中,双曲函数极易溢出,建议强制 float32
72
+ orig_dtype = x.dtype
73
+ x = x.float()
74
+
75
+ # 1. 计算曲率与归一化
76
+ k_pos = torch.nn.functional.softplus(self.k_param) + 1e-6
77
+ sqrt_k = torch.sqrt(k_pos)
78
+
79
+ # 归一化输入 (Input is v in tangent space)
80
+ x_scaled = x / self.lora_norm_scale.float()
81
+ x_norm_scaled = torch.norm(x_scaled, p=2, dim=-1, keepdim=True)
82
+
83
+ # 2. 计算归一化半径 r / sqrt(k)
84
+ theta = x_norm_scaled / sqrt_k
85
+
86
+ # [Stability] Clamp 防止 exp 溢出 (exp(10) ~ 22000, BF16 安全范围)
87
+ theta = torch.clamp(theta, max=10.0)
88
+
89
+ # 3. 指数映射 (Exponential Map)
90
+ # Time: sqrt(k) * cosh(theta) <-- 修正了 arccosh
91
+ x_time = sqrt_k * torch.cosh(theta)
92
+
93
+ # Space: sqrt(k) * sinh(theta) * (v / |v|)
94
+ # 加上 1e-7 防止除零
95
+ x_dir = x_scaled / x_norm_scaled.clamp(min=1e-7)
96
+ x_space = sqrt_k * torch.sinh(theta) * x_dir
97
+
98
+ # 拼接并还原精度
99
+ out = torch.cat([x_time, x_space], dim=-1)
100
+ return out.to(orig_dtype)
101
+
102
+ def forward(
103
+ self,
104
+ input_ids: Optional[torch.Tensor] = None,
105
+ attention_mask: Optional[torch.Tensor] = None,
106
+ labels: Optional[torch.Tensor] = None,
107
+ **kwargs: Any,
108
+ ):
109
+ # 显式传入 return_dict=True,返回的是对象
110
+ transformer_outputs = self.model(
111
+ input_ids=input_ids,
112
+ attention_mask=attention_mask,
113
+ output_hidden_states=True,
114
+ return_dict=True,
115
+ **kwargs,
116
+ )
117
+
118
+ h = transformer_outputs.hidden_states[-1]
119
+
120
+ # 1. 投影到双曲面
121
+ h_hyp = self._project_hyperbolic(h)
122
+
123
+ # [Monitor] 记录 curvature k
124
+ if self.training:
125
+ k_val = torch.nn.functional.softplus(self.k_param) + 1e-6
126
+ should_log = False
127
+ if dist.is_initialized():
128
+ if dist.get_rank() == 0:
129
+ should_log = True
130
+ else:
131
+ should_log = True
132
+
133
+ if should_log:
134
+ try:
135
+ import wandb
136
+ if wandb.run is not None:
137
+ wandb.log({"train/hyp_k": k_val.item()}, commit=False)
138
+ except ImportError:
139
+ pass
140
+
141
+ # 2. 计算 Logits (Minkowski Inner Product Trick)
142
+ h_hyp_minkowski = h_hyp.clone()
143
+ h_hyp_minkowski[..., 0] = -h_hyp_minkowski[..., 0]
144
+
145
+ # [Logit Scale] 关键修正:把“消失的50倍”乘回来
146
+ logits = self.hyper_head(h_hyp_minkowski) * self.logit_scale.exp()
147
+
148
+ loss = None
149
+ if labels is not None:
150
+ # Shift for next-token prediction
151
+ shift_logits = logits[..., :-1, :].contiguous()
152
+ shift_labels = labels[..., 1:].contiguous()
153
+
154
+ # [Fix Loss Display] 使用 sum reduction 并手动除以 num_items_in_batch
155
+ loss = F.cross_entropy(
156
+ shift_logits.view(-1, shift_logits.size(-1)),
157
+ shift_labels.view(-1),
158
+ ignore_index=-100,
159
+ reduction='sum'
160
+ )
161
+
162
+ num_items = kwargs.get("num_items_in_batch")
163
+ if num_items is not None:
164
+ loss = loss / num_items
165
+ else:
166
+ valid_items = (shift_labels != -100).sum()
167
+ if valid_items > 0:
168
+ loss = loss / valid_items
169
+ else:
170
+ loss = loss / shift_labels.numel()
171
+
172
+ if not kwargs.get("return_dict", True):
173
+ output = (logits,) + (transformer_outputs.past_key_values, transformer_outputs.hidden_states, transformer_outputs.attentions)
174
+ return ((loss,) + output) if loss is not None else output
175
+
176
+ return CausalLMOutputWithPast(
177
+ loss=loss,
178
+ logits=logits,
179
+ past_key_values=transformer_outputs.past_key_values,
180
+ hidden_states=transformer_outputs.hidden_states,
181
+ attentions=transformer_outputs.attentions,
182
+ )
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c5e18f922d0af74d820247ae97bee506ab412554a58345ddf2558abc94ee3e3
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a2dcca6d9741f46592359768ea2212b9321da6408d1fd7d3a80b017bf37f434
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69420ece2c255923c5cbb3c6c9c4a6b9cb38fb57e5d3033c8b7d436a1faf6f13
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66f278b40a1e23b88a657c4e5d03afa8dbbbe14dfeb16f6b4beedaece6cdd0b9
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df87f84f0a212955a37fd9dd335bd892f3f681598bc04cca33bb3ac872593986
3
+ size 1064
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/tokenizer_config.json ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
231
+ "clean_up_tokenization_spaces": false,
232
+ "eos_token": "<|im_end|>",
233
+ "errors": "replace",
234
+ "extra_special_tokens": {},
235
+ "model_max_length": 131072,
236
+ "pad_token": "<|endoftext|>",
237
+ "padding_side": "right",
238
+ "split_special_tokens": false,
239
+ "tokenizer_class": "Qwen2Tokenizer",
240
+ "unk_token": null
241
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/trainer_state.json ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.24644727985168638,
6
+ "eval_steps": 2048,
7
+ "global_step": 8192,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.003008389646627031,
14
+ "grad_norm": 2.679380416870117,
15
+ "learning_rate": 1.544461778471139e-05,
16
+ "loss": 10.2946,
17
+ "step": 100
18
+ },
19
+ {
20
+ "epoch": 0.006016779293254062,
21
+ "grad_norm": 2.508666515350342,
22
+ "learning_rate": 3.104524180967239e-05,
23
+ "loss": 7.5427,
24
+ "step": 200
25
+ },
26
+ {
27
+ "epoch": 0.009025168939881093,
28
+ "grad_norm": 1.519907832145691,
29
+ "learning_rate": 4.664586583463339e-05,
30
+ "loss": 6.5156,
31
+ "step": 300
32
+ },
33
+ {
34
+ "epoch": 0.012033558586508125,
35
+ "grad_norm": 1.2391455173492432,
36
+ "learning_rate": 6.224648985959438e-05,
37
+ "loss": 6.0105,
38
+ "step": 400
39
+ },
40
+ {
41
+ "epoch": 0.015041948233135156,
42
+ "grad_norm": 1.168815016746521,
43
+ "learning_rate": 7.784711388455539e-05,
44
+ "loss": 5.6775,
45
+ "step": 500
46
+ },
47
+ {
48
+ "epoch": 0.018050337879762186,
49
+ "grad_norm": 0.9337369799613953,
50
+ "learning_rate": 9.344773790951638e-05,
51
+ "loss": 5.4113,
52
+ "step": 600
53
+ },
54
+ {
55
+ "epoch": 0.021058727526389216,
56
+ "grad_norm": 1.0306508541107178,
57
+ "learning_rate": 9.99991570755671e-05,
58
+ "loss": 5.1657,
59
+ "step": 700
60
+ },
61
+ {
62
+ "epoch": 0.02406711717301625,
63
+ "grad_norm": 0.7395368218421936,
64
+ "learning_rate": 9.999374483177532e-05,
65
+ "loss": 4.9541,
66
+ "step": 800
67
+ },
68
+ {
69
+ "epoch": 0.02707550681964328,
70
+ "grad_norm": 0.7531330585479736,
71
+ "learning_rate": 9.998332180136788e-05,
72
+ "loss": 4.774,
73
+ "step": 900
74
+ },
75
+ {
76
+ "epoch": 0.030083896466270313,
77
+ "grad_norm": 0.6506842970848083,
78
+ "learning_rate": 9.996788902902707e-05,
79
+ "loss": 4.6253,
80
+ "step": 1000
81
+ },
82
+ {
83
+ "epoch": 0.03309228611289734,
84
+ "grad_norm": 0.5735554099082947,
85
+ "learning_rate": 9.994744806155301e-05,
86
+ "loss": 4.486,
87
+ "step": 1100
88
+ },
89
+ {
90
+ "epoch": 0.03610067575952437,
91
+ "grad_norm": 0.6198335289955139,
92
+ "learning_rate": 9.992200094770852e-05,
93
+ "loss": 4.3821,
94
+ "step": 1200
95
+ },
96
+ {
97
+ "epoch": 0.0391090654061514,
98
+ "grad_norm": 0.6022716164588928,
99
+ "learning_rate": 9.989155023801383e-05,
100
+ "loss": 4.2918,
101
+ "step": 1300
102
+ },
103
+ {
104
+ "epoch": 0.04211745505277843,
105
+ "grad_norm": 0.4854939877986908,
106
+ "learning_rate": 9.985609898449093e-05,
107
+ "loss": 4.2235,
108
+ "step": 1400
109
+ },
110
+ {
111
+ "epoch": 0.04512584469940547,
112
+ "grad_norm": 0.47428321838378906,
113
+ "learning_rate": 9.981565074035767e-05,
114
+ "loss": 4.1561,
115
+ "step": 1500
116
+ },
117
+ {
118
+ "epoch": 0.0481342343460325,
119
+ "grad_norm": 0.5457562804222107,
120
+ "learning_rate": 9.977020955967163e-05,
121
+ "loss": 4.096,
122
+ "step": 1600
123
+ },
124
+ {
125
+ "epoch": 0.05114262399265953,
126
+ "grad_norm": 0.495227575302124,
127
+ "learning_rate": 9.97197799969238e-05,
128
+ "loss": 4.0446,
129
+ "step": 1700
130
+ },
131
+ {
132
+ "epoch": 0.05415101363928656,
133
+ "grad_norm": 0.4741596281528473,
134
+ "learning_rate": 9.966436710658207e-05,
135
+ "loss": 4.0085,
136
+ "step": 1800
137
+ },
138
+ {
139
+ "epoch": 0.05715940328591359,
140
+ "grad_norm": 0.4530254006385803,
141
+ "learning_rate": 9.960397644258464e-05,
142
+ "loss": 3.9634,
143
+ "step": 1900
144
+ },
145
+ {
146
+ "epoch": 0.060167792932540626,
147
+ "grad_norm": 0.4369586110115051,
148
+ "learning_rate": 9.953861405778336e-05,
149
+ "loss": 3.926,
150
+ "step": 2000
151
+ },
152
+ {
153
+ "epoch": 0.061611819962921595,
154
+ "eval_loss": 3.8919522762298584,
155
+ "eval_runtime": 40.3727,
156
+ "eval_samples_per_second": 104.972,
157
+ "eval_steps_per_second": 3.294,
158
+ "step": 2048
159
+ },
160
+ {
161
+ "epoch": 0.06317618257916766,
162
+ "grad_norm": 0.45215803384780884,
163
+ "learning_rate": 9.946828650333706e-05,
164
+ "loss": 3.8851,
165
+ "step": 2100
166
+ },
167
+ {
168
+ "epoch": 0.06618457222579469,
169
+ "grad_norm": 0.4366350769996643,
170
+ "learning_rate": 9.939300082805494e-05,
171
+ "loss": 3.8612,
172
+ "step": 2200
173
+ },
174
+ {
175
+ "epoch": 0.06919296187242172,
176
+ "grad_norm": 0.4654478132724762,
177
+ "learning_rate": 9.931276457769007e-05,
178
+ "loss": 3.8277,
179
+ "step": 2300
180
+ },
181
+ {
182
+ "epoch": 0.07220135151904875,
183
+ "grad_norm": 0.39733171463012695,
184
+ "learning_rate": 9.922758579418314e-05,
185
+ "loss": 3.8112,
186
+ "step": 2400
187
+ },
188
+ {
189
+ "epoch": 0.07520974116567578,
190
+ "grad_norm": 0.46311381459236145,
191
+ "learning_rate": 9.913747301485634e-05,
192
+ "loss": 3.7753,
193
+ "step": 2500
194
+ },
195
+ {
196
+ "epoch": 0.0782181308123028,
197
+ "grad_norm": 0.43699029088020325,
198
+ "learning_rate": 9.904243527155776e-05,
199
+ "loss": 3.7577,
200
+ "step": 2600
201
+ },
202
+ {
203
+ "epoch": 0.08122652045892984,
204
+ "grad_norm": 0.39394611120224,
205
+ "learning_rate": 9.894248208975612e-05,
206
+ "loss": 3.729,
207
+ "step": 2700
208
+ },
209
+ {
210
+ "epoch": 0.08423491010555686,
211
+ "grad_norm": 0.4024145007133484,
212
+ "learning_rate": 9.883762348758603e-05,
213
+ "loss": 3.7192,
214
+ "step": 2800
215
+ },
216
+ {
217
+ "epoch": 0.08724329975218391,
218
+ "grad_norm": 0.38164347410202026,
219
+ "learning_rate": 9.872786997484389e-05,
220
+ "loss": 3.699,
221
+ "step": 2900
222
+ },
223
+ {
224
+ "epoch": 0.09025168939881094,
225
+ "grad_norm": 0.44654878973960876,
226
+ "learning_rate": 9.861323255193458e-05,
227
+ "loss": 3.67,
228
+ "step": 3000
229
+ },
230
+ {
231
+ "epoch": 0.09326007904543797,
232
+ "grad_norm": 0.4474869966506958,
233
+ "learning_rate": 9.849372270876876e-05,
234
+ "loss": 3.6576,
235
+ "step": 3100
236
+ },
237
+ {
238
+ "epoch": 0.096268468692065,
239
+ "grad_norm": 0.4036603271961212,
240
+ "learning_rate": 9.836935242361145e-05,
241
+ "loss": 3.6431,
242
+ "step": 3200
243
+ },
244
+ {
245
+ "epoch": 0.09927685833869203,
246
+ "grad_norm": 0.3846100866794586,
247
+ "learning_rate": 9.824013416188129e-05,
248
+ "loss": 3.6327,
249
+ "step": 3300
250
+ },
251
+ {
252
+ "epoch": 0.10228524798531906,
253
+ "grad_norm": 0.4088261127471924,
254
+ "learning_rate": 9.810608087490127e-05,
255
+ "loss": 3.6103,
256
+ "step": 3400
257
+ },
258
+ {
259
+ "epoch": 0.10529363763194609,
260
+ "grad_norm": 0.38841763138771057,
261
+ "learning_rate": 9.79672059986006e-05,
262
+ "loss": 3.6036,
263
+ "step": 3500
264
+ },
265
+ {
266
+ "epoch": 0.10830202727857312,
267
+ "grad_norm": 0.38686931133270264,
268
+ "learning_rate": 9.782352345216805e-05,
269
+ "loss": 3.5848,
270
+ "step": 3600
271
+ },
272
+ {
273
+ "epoch": 0.11131041692520015,
274
+ "grad_norm": 0.36625438928604126,
275
+ "learning_rate": 9.767504763665684e-05,
276
+ "loss": 3.5719,
277
+ "step": 3700
278
+ },
279
+ {
280
+ "epoch": 0.11431880657182718,
281
+ "grad_norm": 0.39244991540908813,
282
+ "learning_rate": 9.75217934335413e-05,
283
+ "loss": 3.5577,
284
+ "step": 3800
285
+ },
286
+ {
287
+ "epoch": 0.11732719621845421,
288
+ "grad_norm": 0.3740030825138092,
289
+ "learning_rate": 9.736377620322523e-05,
290
+ "loss": 3.5464,
291
+ "step": 3900
292
+ },
293
+ {
294
+ "epoch": 0.12033558586508125,
295
+ "grad_norm": 0.33860936760902405,
296
+ "learning_rate": 9.720101178350244e-05,
297
+ "loss": 3.5344,
298
+ "step": 4000
299
+ },
300
+ {
301
+ "epoch": 0.12322363992584319,
302
+ "eval_loss": 3.5163917541503906,
303
+ "eval_runtime": 40.3211,
304
+ "eval_samples_per_second": 105.106,
305
+ "eval_steps_per_second": 3.299,
306
+ "step": 4096
307
+ },
308
+ {
309
+ "epoch": 0.12334397551170828,
310
+ "grad_norm": 0.4020504355430603,
311
+ "learning_rate": 9.703351648796938e-05,
312
+ "loss": 3.5206,
313
+ "step": 4100
314
+ },
315
+ {
316
+ "epoch": 0.1263523651583353,
317
+ "grad_norm": 0.3544408082962036,
318
+ "learning_rate": 9.686130710438993e-05,
319
+ "loss": 3.511,
320
+ "step": 4200
321
+ },
322
+ {
323
+ "epoch": 0.12936075480496234,
324
+ "grad_norm": 0.3333083689212799,
325
+ "learning_rate": 9.668440089301285e-05,
326
+ "loss": 3.4969,
327
+ "step": 4300
328
+ },
329
+ {
330
+ "epoch": 0.13236914445158937,
331
+ "grad_norm": 0.4492756724357605,
332
+ "learning_rate": 9.650281558484195e-05,
333
+ "loss": 3.4898,
334
+ "step": 4400
335
+ },
336
+ {
337
+ "epoch": 0.1353775340982164,
338
+ "grad_norm": 0.34960809350013733,
339
+ "learning_rate": 9.63165693798587e-05,
340
+ "loss": 3.4848,
341
+ "step": 4500
342
+ },
343
+ {
344
+ "epoch": 0.13838592374484343,
345
+ "grad_norm": 0.38963454961776733,
346
+ "learning_rate": 9.612568094519824e-05,
347
+ "loss": 3.4662,
348
+ "step": 4600
349
+ },
350
+ {
351
+ "epoch": 0.14139431339147046,
352
+ "grad_norm": 0.3429240584373474,
353
+ "learning_rate": 9.59301694132784e-05,
354
+ "loss": 3.467,
355
+ "step": 4700
356
+ },
357
+ {
358
+ "epoch": 0.1444027030380975,
359
+ "grad_norm": 0.3769192099571228,
360
+ "learning_rate": 9.573005437988198e-05,
361
+ "loss": 3.4521,
362
+ "step": 4800
363
+ },
364
+ {
365
+ "epoch": 0.14741109268472452,
366
+ "grad_norm": 0.3522360920906067,
367
+ "learning_rate": 9.552535590219285e-05,
368
+ "loss": 3.4474,
369
+ "step": 4900
370
+ },
371
+ {
372
+ "epoch": 0.15041948233135155,
373
+ "grad_norm": 0.4129360020160675,
374
+ "learning_rate": 9.531609449678555e-05,
375
+ "loss": 3.4369,
376
+ "step": 5000
377
+ },
378
+ {
379
+ "epoch": 0.15342787197797858,
380
+ "grad_norm": 0.34923356771469116,
381
+ "learning_rate": 9.5102291137569e-05,
382
+ "loss": 3.4292,
383
+ "step": 5100
384
+ },
385
+ {
386
+ "epoch": 0.1564362616246056,
387
+ "grad_norm": 0.38432955741882324,
388
+ "learning_rate": 9.48839672536842e-05,
389
+ "loss": 3.4181,
390
+ "step": 5200
391
+ },
392
+ {
393
+ "epoch": 0.15944465127123264,
394
+ "grad_norm": 0.339767187833786,
395
+ "learning_rate": 9.466114472735664e-05,
396
+ "loss": 3.4114,
397
+ "step": 5300
398
+ },
399
+ {
400
+ "epoch": 0.16245304091785967,
401
+ "grad_norm": 0.3229652941226959,
402
+ "learning_rate": 9.443384589170292e-05,
403
+ "loss": 3.3989,
404
+ "step": 5400
405
+ },
406
+ {
407
+ "epoch": 0.1654614305644867,
408
+ "grad_norm": 0.3408010005950928,
409
+ "learning_rate": 9.420209352849238e-05,
410
+ "loss": 3.3982,
411
+ "step": 5500
412
+ },
413
+ {
414
+ "epoch": 0.16846982021111373,
415
+ "grad_norm": 0.3364863693714142,
416
+ "learning_rate": 9.396591086586374e-05,
417
+ "loss": 3.3953,
418
+ "step": 5600
419
+ },
420
+ {
421
+ "epoch": 0.1714782098577408,
422
+ "grad_norm": 0.3384004235267639,
423
+ "learning_rate": 9.372532157599697e-05,
424
+ "loss": 3.3851,
425
+ "step": 5700
426
+ },
427
+ {
428
+ "epoch": 0.17448659950436782,
429
+ "grad_norm": 0.3525841534137726,
430
+ "learning_rate": 9.348034977274063e-05,
431
+ "loss": 3.3776,
432
+ "step": 5800
433
+ },
434
+ {
435
+ "epoch": 0.17749498915099485,
436
+ "grad_norm": 0.355953186750412,
437
+ "learning_rate": 9.32310200091951e-05,
438
+ "loss": 3.374,
439
+ "step": 5900
440
+ },
441
+ {
442
+ "epoch": 0.18050337879762188,
443
+ "grad_norm": 0.3365969955921173,
444
+ "learning_rate": 9.29773572752515e-05,
445
+ "loss": 3.363,
446
+ "step": 6000
447
+ },
448
+ {
449
+ "epoch": 0.1835117684442489,
450
+ "grad_norm": 0.3535282611846924,
451
+ "learning_rate": 9.271938699508713e-05,
452
+ "loss": 3.3554,
453
+ "step": 6100
454
+ },
455
+ {
456
+ "epoch": 0.1848354598887648,
457
+ "eval_loss": 3.3536014556884766,
458
+ "eval_runtime": 40.3642,
459
+ "eval_samples_per_second": 104.994,
460
+ "eval_steps_per_second": 3.295,
461
+ "step": 6144
462
+ },
463
+ {
464
+ "epoch": 0.18652015809087594,
465
+ "grad_norm": 0.33408671617507935,
466
+ "learning_rate": 9.245713502461722e-05,
467
+ "loss": 3.3503,
468
+ "step": 6200
469
+ },
470
+ {
471
+ "epoch": 0.18952854773750297,
472
+ "grad_norm": 0.3293430805206299,
473
+ "learning_rate": 9.219062764890339e-05,
474
+ "loss": 3.3486,
475
+ "step": 6300
476
+ },
477
+ {
478
+ "epoch": 0.19253693738413,
479
+ "grad_norm": 0.32994309067726135,
480
+ "learning_rate": 9.191989157951913e-05,
481
+ "loss": 3.341,
482
+ "step": 6400
483
+ },
484
+ {
485
+ "epoch": 0.19554532703075703,
486
+ "grad_norm": 0.34000661969184875,
487
+ "learning_rate": 9.164495395187267e-05,
488
+ "loss": 3.3317,
489
+ "step": 6500
490
+ },
491
+ {
492
+ "epoch": 0.19855371667738406,
493
+ "grad_norm": 0.324935644865036,
494
+ "learning_rate": 9.13658423224871e-05,
495
+ "loss": 3.323,
496
+ "step": 6600
497
+ },
498
+ {
499
+ "epoch": 0.2015621063240111,
500
+ "grad_norm": 0.35006093978881836,
501
+ "learning_rate": 9.108258466623851e-05,
502
+ "loss": 3.3178,
503
+ "step": 6700
504
+ },
505
+ {
506
+ "epoch": 0.20457049597063812,
507
+ "grad_norm": 0.32165855169296265,
508
+ "learning_rate": 9.079520937355209e-05,
509
+ "loss": 3.3193,
510
+ "step": 6800
511
+ },
512
+ {
513
+ "epoch": 0.20757888561726515,
514
+ "grad_norm": 0.4521687626838684,
515
+ "learning_rate": 9.050374524755663e-05,
516
+ "loss": 3.3075,
517
+ "step": 6900
518
+ },
519
+ {
520
+ "epoch": 0.21058727526389218,
521
+ "grad_norm": 0.3615197241306305,
522
+ "learning_rate": 9.020822150119757e-05,
523
+ "loss": 3.3095,
524
+ "step": 7000
525
+ },
526
+ {
527
+ "epoch": 0.2135956649105192,
528
+ "grad_norm": 0.415609747171402,
529
+ "learning_rate": 8.990866775430913e-05,
530
+ "loss": 3.2966,
531
+ "step": 7100
532
+ },
533
+ {
534
+ "epoch": 0.21660405455714624,
535
+ "grad_norm": 0.39611032605171204,
536
+ "learning_rate": 8.960511403064549e-05,
537
+ "loss": 3.2965,
538
+ "step": 7200
539
+ },
540
+ {
541
+ "epoch": 0.21961244420377327,
542
+ "grad_norm": 0.38692525029182434,
543
+ "learning_rate": 8.929759075487158e-05,
544
+ "loss": 3.2908,
545
+ "step": 7300
546
+ },
547
+ {
548
+ "epoch": 0.2226208338504003,
549
+ "grad_norm": 0.35982415080070496,
550
+ "learning_rate": 8.89861287495137e-05,
551
+ "loss": 3.2897,
552
+ "step": 7400
553
+ },
554
+ {
555
+ "epoch": 0.22562922349702733,
556
+ "grad_norm": 0.3603018820285797,
557
+ "learning_rate": 8.867075923187018e-05,
558
+ "loss": 3.2723,
559
+ "step": 7500
560
+ },
561
+ {
562
+ "epoch": 0.22863761314365436,
563
+ "grad_norm": 0.3258317708969116,
564
+ "learning_rate": 8.835151381088259e-05,
565
+ "loss": 3.276,
566
+ "step": 7600
567
+ },
568
+ {
569
+ "epoch": 0.23164600279028139,
570
+ "grad_norm": 0.32962825894355774,
571
+ "learning_rate": 8.802842448396754e-05,
572
+ "loss": 3.2673,
573
+ "step": 7700
574
+ },
575
+ {
576
+ "epoch": 0.23465439243690842,
577
+ "grad_norm": 0.29885679483413696,
578
+ "learning_rate": 8.770152363380973e-05,
579
+ "loss": 3.2696,
580
+ "step": 7800
581
+ },
582
+ {
583
+ "epoch": 0.23766278208353547,
584
+ "grad_norm": 0.3000599443912506,
585
+ "learning_rate": 8.737084402511622e-05,
586
+ "loss": 3.263,
587
+ "step": 7900
588
+ },
589
+ {
590
+ "epoch": 0.2406711717301625,
591
+ "grad_norm": 0.31807172298431396,
592
+ "learning_rate": 8.70364188013325e-05,
593
+ "loss": 3.2532,
594
+ "step": 8000
595
+ },
596
+ {
597
+ "epoch": 0.24367956137678953,
598
+ "grad_norm": 0.3243562579154968,
599
+ "learning_rate": 8.669828148132062e-05,
600
+ "loss": 3.2479,
601
+ "step": 8100
602
+ },
603
+ {
604
+ "epoch": 0.24644727985168638,
605
+ "eval_loss": 3.2487316131591797,
606
+ "eval_runtime": 40.3323,
607
+ "eval_samples_per_second": 105.077,
608
+ "eval_steps_per_second": 3.298,
609
+ "step": 8192
610
+ }
611
+ ],
612
+ "logging_steps": 100,
613
+ "max_steps": 32021,
614
+ "num_input_tokens_seen": 0,
615
+ "num_train_epochs": 1,
616
+ "save_steps": 4096,
617
+ "stateful_callbacks": {
618
+ "TrainerControl": {
619
+ "args": {
620
+ "should_epoch_stop": false,
621
+ "should_evaluate": false,
622
+ "should_log": false,
623
+ "should_save": true,
624
+ "should_training_stop": false
625
+ },
626
+ "attributes": {}
627
+ }
628
+ },
629
+ "total_flos": 1.6960767303446692e+19,
630
+ "train_batch_size": 4,
631
+ "trial_name": null,
632
+ "trial_params": null
633
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b3f9aca0ee68c0f3031fcaa646e3e85646d8b5528f8cb52e721dacdac62c44b
3
+ size 7544
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260303_124834/checkpoint-8192/zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)