Jinrui commited on
Commit
65ec4db
·
verified ·
1 Parent(s): fbbe3e2

Upload folder using huggingface_hub

Browse files
Files changed (25) hide show
  1. .gitattributes +1 -0
  2. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/added_tokens.json +28 -0
  3. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/config.json +58 -0
  4. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/generation_config.json +7 -0
  5. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  6. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  7. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
  8. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
  9. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/mp_rank_00_model_states.pt +3 -0
  10. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/latest +1 -0
  11. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/merges.txt +0 -0
  12. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/model.safetensors +3 -0
  13. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/modeling_qwen3_hyp.py +182 -0
  14. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_0.pth +3 -0
  15. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_1.pth +3 -0
  16. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_2.pth +3 -0
  17. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_3.pth +3 -0
  18. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/scheduler.pt +3 -0
  19. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/special_tokens_map.json +31 -0
  20. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/tokenizer.json +3 -0
  21. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/tokenizer_config.json +241 -0
  22. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/trainer_state.json +292 -0
  23. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/training_args.bin +3 -0
  24. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/vocab.json +0 -0
  25. checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/zero_to_fp32.py +604 -0
.gitattributes CHANGED
@@ -72,3 +72,4 @@ checkpoints/qwen3_hyp/qwen3_hyp_p1083m_t1_4_suite-owt_scaling_v3_family-qwen3_ge
72
  checkpoints/qwen3_hyp/qwen3_hyp_p2324m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260209_141700/checkpoint-251/tokenizer.json filter=lfs diff=lfs merge=lfs -text
73
  checkpoints/qwen3_hyp/qwen3_hyp_p407m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260312_143830/checkpoint-8192/tokenizer.json filter=lfs diff=lfs merge=lfs -text
74
  checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_2_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260219_093238/checkpoint-8192/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
72
  checkpoints/qwen3_hyp/qwen3_hyp_p2324m_t1_128_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt3_20260209_141700/checkpoint-251/tokenizer.json filter=lfs diff=lfs merge=lfs -text
73
  checkpoints/qwen3_hyp/qwen3_hyp_p407m_t1_1_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260312_143830/checkpoint-8192/tokenizer.json filter=lfs diff=lfs merge=lfs -text
74
  checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_2_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260219_093238/checkpoint-8192/tokenizer.json filter=lfs diff=lfs merge=lfs -text
75
+ checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/tokenizer.json filter=lfs diff=lfs merge=lfs -text
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 1280,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 3840,
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
+ ],
41
+ "lorentz_k0": 1.0,
42
+ "max_position_embeddings": 40960,
43
+ "max_window_layers": 20,
44
+ "model_type": "qwen3",
45
+ "num_attention_heads": 20,
46
+ "num_hidden_layers": 20,
47
+ "num_key_value_heads": 10,
48
+ "rms_norm_eps": 1e-06,
49
+ "rope_scaling": null,
50
+ "rope_theta": 1000000,
51
+ "sliding_window": null,
52
+ "tie_word_embeddings": true,
53
+ "torch_dtype": "bfloat16",
54
+ "transformers_version": "4.51.3",
55
+ "use_cache": false,
56
+ "use_sliding_window": false,
57
+ "vocab_size": 151936
58
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/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:e89eb6b32bc55283c67111da9d49e92945068c2417206237d7b8388c963954ed
3
+ size 3225502960
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/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:b94cdefb9e1d395b0ab7682c51a98341e57031fbcff4bf86403f77f1d178c879
3
+ size 3225508336
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/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:57bc87c0c45250d8c03704eae628078c18bac54a932f7abd3a8c8ea6e6b9ed97
3
+ size 3225505072
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/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:a75e92ba6d057dea61b59bfce03e0701a0db19ea4952e017b81ec77d449f62e8
3
+ size 3225500912
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/global_step3072/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8d2f762ef273ca8996bdb963b66569ba67d005e56e13e0f3ad8706c255c1f1a
3
+ size 2150395192
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step3072
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e483654b326b07eb11bbf76301ff0bff5da570ba84b4adc71d4c1bd6db9832ce
3
+ size 2539616244
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef002048764051a71fb00f8f978e9ec32b780dc850bdb059af362cc56494234b
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37194a6d48612e1a46a2d5d317ead97c70d9fc4569b0118fcd5f84c3dc9daa5a
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17c179483659a784aa1ace2427daff48c556a6bcc3c330e6f3274e4dc95e4b49
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b56857c9b117629f35af2c3d64f522d33a9d8aa94faa81ec6956380a895118c4
3
+ size 15024
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2819acc651556e7afe4455bcce325e923c7d86faf0bd0546f95f11de8f251294
3
+ size 1064
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/trainer_state.json ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.0924177299443824,
6
+ "eval_steps": 512,
7
+ "global_step": 3072,
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": 1.4079504013061523,
15
+ "learning_rate": 6.149068322981368e-05,
16
+ "loss": 9.3539,
17
+ "step": 100
18
+ },
19
+ {
20
+ "epoch": 0.006016779293254062,
21
+ "grad_norm": 1.252025842666626,
22
+ "learning_rate": 9.999421087841762e-05,
23
+ "loss": 6.6429,
24
+ "step": 200
25
+ },
26
+ {
27
+ "epoch": 0.009025168939881093,
28
+ "grad_norm": 0.8464359045028687,
29
+ "learning_rate": 9.992366890377964e-05,
30
+ "loss": 5.8777,
31
+ "step": 300
32
+ },
33
+ {
34
+ "epoch": 0.012033558586508125,
35
+ "grad_norm": 0.8979347944259644,
36
+ "learning_rate": 9.9773076750685e-05,
37
+ "loss": 5.4891,
38
+ "step": 400
39
+ },
40
+ {
41
+ "epoch": 0.015041948233135156,
42
+ "grad_norm": 0.7227486968040466,
43
+ "learning_rate": 9.954267588633746e-05,
44
+ "loss": 5.2154,
45
+ "step": 500
46
+ },
47
+ {
48
+ "epoch": 0.015402954990730399,
49
+ "eval_loss": 5.0861992835998535,
50
+ "eval_runtime": 28.6174,
51
+ "eval_samples_per_second": 148.092,
52
+ "eval_steps_per_second": 4.648,
53
+ "step": 512
54
+ },
55
+ {
56
+ "epoch": 0.018050337879762186,
57
+ "grad_norm": 0.6411813497543335,
58
+ "learning_rate": 9.923283574733313e-05,
59
+ "loss": 5.0171,
60
+ "step": 600
61
+ },
62
+ {
63
+ "epoch": 0.021058727526389216,
64
+ "grad_norm": 0.6219043731689453,
65
+ "learning_rate": 9.8844053147287e-05,
66
+ "loss": 4.8501,
67
+ "step": 700
68
+ },
69
+ {
70
+ "epoch": 0.02406711717301625,
71
+ "grad_norm": 0.6222556829452515,
72
+ "learning_rate": 9.837695148021635e-05,
73
+ "loss": 4.7037,
74
+ "step": 800
75
+ },
76
+ {
77
+ "epoch": 0.02707550681964328,
78
+ "grad_norm": 0.6238115429878235,
79
+ "learning_rate": 9.78322797209587e-05,
80
+ "loss": 4.5693,
81
+ "step": 900
82
+ },
83
+ {
84
+ "epoch": 0.030083896466270313,
85
+ "grad_norm": 0.6507419943809509,
86
+ "learning_rate": 9.721091122422707e-05,
87
+ "loss": 4.4618,
88
+ "step": 1000
89
+ },
90
+ {
91
+ "epoch": 0.030805909981460797,
92
+ "eval_loss": 4.389865398406982,
93
+ "eval_runtime": 28.5812,
94
+ "eval_samples_per_second": 148.279,
95
+ "eval_steps_per_second": 4.653,
96
+ "step": 1024
97
+ },
98
+ {
99
+ "epoch": 0.03309228611289734,
100
+ "grad_norm": 0.5398547053337097,
101
+ "learning_rate": 9.651384232422814e-05,
102
+ "loss": 4.3667,
103
+ "step": 1100
104
+ },
105
+ {
106
+ "epoch": 0.03610067575952437,
107
+ "grad_norm": 0.6056393980979919,
108
+ "learning_rate": 9.574219073708867e-05,
109
+ "loss": 4.2899,
110
+ "step": 1200
111
+ },
112
+ {
113
+ "epoch": 0.0391090654061514,
114
+ "grad_norm": 0.5178854465484619,
115
+ "learning_rate": 9.489719376865203e-05,
116
+ "loss": 4.221,
117
+ "step": 1300
118
+ },
119
+ {
120
+ "epoch": 0.04211745505277843,
121
+ "grad_norm": 0.4748992323875427,
122
+ "learning_rate": 9.398020633051834e-05,
123
+ "loss": 4.1702,
124
+ "step": 1400
125
+ },
126
+ {
127
+ "epoch": 0.04512584469940547,
128
+ "grad_norm": 0.5286852121353149,
129
+ "learning_rate": 9.299269876750955e-05,
130
+ "loss": 4.1169,
131
+ "step": 1500
132
+ },
133
+ {
134
+ "epoch": 0.0462088649721912,
135
+ "eval_loss": 4.072985649108887,
136
+ "eval_runtime": 28.6335,
137
+ "eval_samples_per_second": 148.009,
138
+ "eval_steps_per_second": 4.645,
139
+ "step": 1536
140
+ },
141
+ {
142
+ "epoch": 0.0481342343460325,
143
+ "grad_norm": 0.48330968618392944,
144
+ "learning_rate": 9.19362545000429e-05,
145
+ "loss": 4.0688,
146
+ "step": 1600
147
+ },
148
+ {
149
+ "epoch": 0.05114262399265953,
150
+ "grad_norm": 0.4792095422744751,
151
+ "learning_rate": 9.08125674851932e-05,
152
+ "loss": 4.0287,
153
+ "step": 1700
154
+ },
155
+ {
156
+ "epoch": 0.05415101363928656,
157
+ "grad_norm": 0.5017923712730408,
158
+ "learning_rate": 8.962343950051497e-05,
159
+ "loss": 3.9919,
160
+ "step": 1800
161
+ },
162
+ {
163
+ "epoch": 0.05715940328591359,
164
+ "grad_norm": 0.45991232991218567,
165
+ "learning_rate": 8.83707772549795e-05,
166
+ "loss": 3.959,
167
+ "step": 1900
168
+ },
169
+ {
170
+ "epoch": 0.060167792932540626,
171
+ "grad_norm": 0.45571720600128174,
172
+ "learning_rate": 8.705658933165981e-05,
173
+ "loss": 3.9288,
174
+ "step": 2000
175
+ },
176
+ {
177
+ "epoch": 0.061611819962921595,
178
+ "eval_loss": 3.8978145122528076,
179
+ "eval_runtime": 28.7591,
180
+ "eval_samples_per_second": 147.362,
181
+ "eval_steps_per_second": 4.625,
182
+ "step": 2048
183
+ },
184
+ {
185
+ "epoch": 0.06317618257916766,
186
+ "grad_norm": 0.4395545721054077,
187
+ "learning_rate": 8.568298296706507e-05,
188
+ "loss": 3.8941,
189
+ "step": 2100
190
+ },
191
+ {
192
+ "epoch": 0.06618457222579469,
193
+ "grad_norm": 0.4189292788505554,
194
+ "learning_rate": 8.425216067228932e-05,
195
+ "loss": 3.8736,
196
+ "step": 2200
197
+ },
198
+ {
199
+ "epoch": 0.06919296187242172,
200
+ "grad_norm": 0.4565911591053009,
201
+ "learning_rate": 8.276641670139183e-05,
202
+ "loss": 3.8446,
203
+ "step": 2300
204
+ },
205
+ {
206
+ "epoch": 0.07220135151904875,
207
+ "grad_norm": 0.3999106287956238,
208
+ "learning_rate": 8.122813337267216e-05,
209
+ "loss": 3.8308,
210
+ "step": 2400
211
+ },
212
+ {
213
+ "epoch": 0.07520974116567578,
214
+ "grad_norm": 0.4241749942302704,
215
+ "learning_rate": 7.963977724873853e-05,
216
+ "loss": 3.8009,
217
+ "step": 2500
218
+ },
219
+ {
220
+ "epoch": 0.077014774953652,
221
+ "eval_loss": 3.7836685180664062,
222
+ "eval_runtime": 28.6535,
223
+ "eval_samples_per_second": 147.905,
224
+ "eval_steps_per_second": 4.642,
225
+ "step": 2560
226
+ },
227
+ {
228
+ "epoch": 0.0782181308123028,
229
+ "grad_norm": 0.4040316343307495,
230
+ "learning_rate": 7.800389518149431e-05,
231
+ "loss": 3.7858,
232
+ "step": 2600
233
+ },
234
+ {
235
+ "epoch": 0.08122652045892984,
236
+ "grad_norm": 0.419279545545578,
237
+ "learning_rate": 7.632311022838487e-05,
238
+ "loss": 3.7617,
239
+ "step": 2700
240
+ },
241
+ {
242
+ "epoch": 0.08423491010555686,
243
+ "grad_norm": 0.41915661096572876,
244
+ "learning_rate": 7.460011744645226e-05,
245
+ "loss": 3.7543,
246
+ "step": 2800
247
+ },
248
+ {
249
+ "epoch": 0.08724329975218391,
250
+ "grad_norm": 0.40949028730392456,
251
+ "learning_rate": 7.283767957094212e-05,
252
+ "loss": 3.739,
253
+ "step": 2900
254
+ },
255
+ {
256
+ "epoch": 0.09025168939881094,
257
+ "grad_norm": 0.3878908157348633,
258
+ "learning_rate": 7.103862258539194e-05,
259
+ "loss": 3.7121,
260
+ "step": 3000
261
+ },
262
+ {
263
+ "epoch": 0.0924177299443824,
264
+ "eval_loss": 3.6991801261901855,
265
+ "eval_runtime": 28.6363,
266
+ "eval_samples_per_second": 147.994,
267
+ "eval_steps_per_second": 4.644,
268
+ "step": 3072
269
+ }
270
+ ],
271
+ "logging_steps": 100,
272
+ "max_steps": 8006,
273
+ "num_input_tokens_seen": 0,
274
+ "num_train_epochs": 1,
275
+ "save_steps": 1024,
276
+ "stateful_callbacks": {
277
+ "TrainerControl": {
278
+ "args": {
279
+ "should_epoch_stop": false,
280
+ "should_evaluate": false,
281
+ "should_log": false,
282
+ "should_save": true,
283
+ "should_training_stop": false
284
+ },
285
+ "attributes": {}
286
+ }
287
+ },
288
+ "total_flos": 4.2553369455650406e+18,
289
+ "train_batch_size": 4,
290
+ "trial_name": null,
291
+ "trial_params": null
292
+ }
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4561c62b4529babe6f1b9d1634ae524a3b841005c70c0e4f7ad61219e311d366
3
+ size 7544
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/qwen3_hyp/qwen3_hyp_p686m_t1_4_suite-owt_scaling_v3_family-qwen3_geometry_id-hyp_variant-base_init_slope-std/attempt2_20260214_093947/checkpoint-3072/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)