Publish credential-free structural-smoke runner
Browse files- config/benching/fable-router-training-campaign.v1.json +129 -1
- training/fable_router_hybrid.py +66 -5
- training/run_fable_router_full_bank_fit.py +152 -4
- training/run_fable_router_optimizer_smoke.py +121 -8
- training/run_fable_router_stage_a_chunk.py +40 -3
- training/run_fable_router_structural_smoke.py +28 -14
config/benching/fable-router-training-campaign.v1.json
CHANGED
|
@@ -96,12 +96,100 @@
|
|
| 96 |
},
|
| 97 |
"optimizerAdmission": {
|
| 98 |
"requiredBeforeStageA": true,
|
| 99 |
-
"steps":
|
|
|
|
|
|
|
|
|
|
| 100 |
"learningRate": 0.0002,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
"gradientClipNorm": 1.0,
|
| 102 |
"counterfactualLayer": 29,
|
| 103 |
"counterfactualCandidates": [0, 1, 8, 16],
|
| 104 |
"counterfactualScale": 0.025,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
"memoryProof": {
|
| 106 |
"path": "downloads/audits/fable-router-full-bank-training-memory-proof/result.json",
|
| 107 |
"sha256": "64de6936e05e9f1d24df325fc1c2bf2bbb2e5109a45f888e940e3d366adce706",
|
|
@@ -117,12 +205,52 @@
|
|
| 117 |
"four_independent_counterfactual_candidates",
|
| 118 |
"positive_benefit_and_host_only_targets_present",
|
| 119 |
"finite_sft_kl_ranking_and_route_cost_losses",
|
|
|
|
|
|
|
|
|
|
| 120 |
"all_30_router_gates_updated",
|
|
|
|
| 121 |
"expert_scales_bounded_by_stage_a_maximum",
|
| 122 |
"router_and_optimizer_checkpoint_persisted_privately"
|
| 123 |
]
|
| 124 |
},
|
| 125 |
"training": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
"stages": [
|
| 127 |
{"name": "A-host-anchor", "steps": 200},
|
| 128 |
{"name": "B-benefit-gated-routing", "steps": 600},
|
|
|
|
| 96 |
},
|
| 97 |
"optimizerAdmission": {
|
| 98 |
"requiredBeforeStageA": true,
|
| 99 |
+
"steps": 8,
|
| 100 |
+
"rowsPerLane": 4,
|
| 101 |
+
"maximumTokens": 320,
|
| 102 |
+
"coverageStrategy": "four deterministic length-quantile rows per lane; cumulative gate update required across the eight-step smoke",
|
| 103 |
"learningRate": 0.0002,
|
| 104 |
+
"gradientLossScale": 1024.0,
|
| 105 |
+
"donorInputNormalization": {
|
| 106 |
+
"mode": "donor_rms",
|
| 107 |
+
"epsilon": 1e-06,
|
| 108 |
+
"scope": "router_and_frozen_experts_only",
|
| 109 |
+
"sidecars": {
|
| 110 |
+
"kat-coder-v25-dev-q4km": {
|
| 111 |
+
"path": "artifacts/kat-coder-v25-dev-post-attention-rmsnorm.safetensors",
|
| 112 |
+
"bytes": 126520,
|
| 113 |
+
"sha256": "fc300a50b5c33fdf9a95af4975d58250c8566e1d504c37d99ee1ac93a413da04",
|
| 114 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 115 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 116 |
+
},
|
| 117 |
+
"ornith10-35b-q4km": {
|
| 118 |
+
"path": "artifacts/ornith10-35b-post-attention-rmsnorm.safetensors",
|
| 119 |
+
"bytes": 126424,
|
| 120 |
+
"sha256": "9ab2a3f10303fe2fe164940010955d2e2eec4684d2f4589353c494497bd05a18",
|
| 121 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 122 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 123 |
+
},
|
| 124 |
+
"qwen35-35b-base-q4km": {
|
| 125 |
+
"path": "artifacts/qwen35-35b-base-post-attention-rmsnorm.safetensors",
|
| 126 |
+
"bytes": 126504,
|
| 127 |
+
"sha256": "5f93344804e0bfecf02c20357619c558d7f9142d77e61b0846f0b11ef5282401",
|
| 128 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 129 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 130 |
+
},
|
| 131 |
+
"qwen36-35b-base-q4km": {
|
| 132 |
+
"path": "artifacts/qwen36-35b-base-post-attention-rmsnorm.safetensors",
|
| 133 |
+
"bytes": 126504,
|
| 134 |
+
"sha256": "382c973b6b62e03e39f250732b994bd30ed16ef46344a8e872bb4fc4a6b24ecc",
|
| 135 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 136 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
},
|
| 140 |
"gradientClipNorm": 1.0,
|
| 141 |
"counterfactualLayer": 29,
|
| 142 |
"counterfactualCandidates": [0, 1, 8, 16],
|
| 143 |
"counterfactualScale": 0.025,
|
| 144 |
+
"tokenizerContract": {
|
| 145 |
+
"hostRevision": "72d68fcd4b2b91749d2d6a71a0fdf315fe1704c8",
|
| 146 |
+
"transformers5ReferenceClass": "TokenizersBackend",
|
| 147 |
+
"portableLoader": "PreTrainedTokenizerFast",
|
| 148 |
+
"padTokenId": 124893,
|
| 149 |
+
"selectedRows": [
|
| 150 |
+
{
|
| 151 |
+
"id": "reasoning:fd42e6013f2f0bcbb570ef95f9a2fcb33156f3c3b197e2b8a2448bf99a20873d",
|
| 152 |
+
"lane": "host_preservation",
|
| 153 |
+
"tokens": 264
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"id": "reasoning:bda1eef534240e26343576ad40f755bd57006b95b1a72da5ddcfa7d97cb73710",
|
| 157 |
+
"lane": "host_preservation",
|
| 158 |
+
"tokens": 294
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"id": "reasoning:a6ea89c9d196768b04e69a82d8b3c4d49bd14485a2be4aa15ac4068e17f17cc6",
|
| 162 |
+
"lane": "host_preservation",
|
| 163 |
+
"tokens": 306
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"id": "reasoning:c518a5503bc6c33a4f3e26a2b519b90c42a8a6e11934c80a2ba9fad386b81c22",
|
| 167 |
+
"lane": "host_preservation",
|
| 168 |
+
"tokens": 315
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"id": "agent:480ed7c16d7fbc42f787e050bcb7ea4e0cb17eea06a899d543b4575216620a88:1",
|
| 172 |
+
"lane": "verified_expert",
|
| 173 |
+
"tokens": 48
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"id": "agent:66244eb518816ac398c00b351d61fe53e26e279c5d4bf756954fd323669fc650:2",
|
| 177 |
+
"lane": "verified_expert",
|
| 178 |
+
"tokens": 204
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"id": "agent:35d278d1ae43f2d93288060777dcb14a0a7b5eadf88c0a0287df367096a1c1fa:4",
|
| 182 |
+
"lane": "verified_expert",
|
| 183 |
+
"tokens": 260
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"id": "agent:92d464ccdf4cea7bf0f3e04060492f317c99926d2071f19dd89f8eef10372aa8:5",
|
| 187 |
+
"lane": "verified_expert",
|
| 188 |
+
"tokens": 320
|
| 189 |
+
}
|
| 190 |
+
],
|
| 191 |
+
"inputIdsSignatureSha256": "5b65e5dc5e00963a8fa2e639389ba0cbea816960296d42698e2f7116412cf24a"
|
| 192 |
+
},
|
| 193 |
"memoryProof": {
|
| 194 |
"path": "downloads/audits/fable-router-full-bank-training-memory-proof/result.json",
|
| 195 |
"sha256": "64de6936e05e9f1d24df325fc1c2bf2bbb2e5109a45f888e940e3d366adce706",
|
|
|
|
| 205 |
"four_independent_counterfactual_candidates",
|
| 206 |
"positive_benefit_and_host_only_targets_present",
|
| 207 |
"finite_sft_kl_ranking_and_route_cost_losses",
|
| 208 |
+
"loss_scaled_backward_with_preclip_unscale",
|
| 209 |
+
"donor_norm_equation_matches_architecture",
|
| 210 |
+
"optimizer_checkpoint_step_count_matches_smoke",
|
| 211 |
"all_30_router_gates_updated",
|
| 212 |
+
"all_30_router_residuals_numerically_effective",
|
| 213 |
"expert_scales_bounded_by_stage_a_maximum",
|
| 214 |
"router_and_optimizer_checkpoint_persisted_privately"
|
| 215 |
]
|
| 216 |
},
|
| 217 |
"training": {
|
| 218 |
+
"gradientLossScale": 1024.0,
|
| 219 |
+
"donorInputNormalization": {
|
| 220 |
+
"mode": "donor_rms",
|
| 221 |
+
"epsilon": 1e-06,
|
| 222 |
+
"scope": "router_and_frozen_experts_only",
|
| 223 |
+
"sidecars": {
|
| 224 |
+
"kat-coder-v25-dev-q4km": {
|
| 225 |
+
"path": "artifacts/kat-coder-v25-dev-post-attention-rmsnorm.safetensors",
|
| 226 |
+
"bytes": 126520,
|
| 227 |
+
"sha256": "fc300a50b5c33fdf9a95af4975d58250c8566e1d504c37d99ee1ac93a413da04",
|
| 228 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 229 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 230 |
+
},
|
| 231 |
+
"ornith10-35b-q4km": {
|
| 232 |
+
"path": "artifacts/ornith10-35b-post-attention-rmsnorm.safetensors",
|
| 233 |
+
"bytes": 126424,
|
| 234 |
+
"sha256": "9ab2a3f10303fe2fe164940010955d2e2eec4684d2f4589353c494497bd05a18",
|
| 235 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 236 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 237 |
+
},
|
| 238 |
+
"qwen35-35b-base-q4km": {
|
| 239 |
+
"path": "artifacts/qwen35-35b-base-post-attention-rmsnorm.safetensors",
|
| 240 |
+
"bytes": 126504,
|
| 241 |
+
"sha256": "5f93344804e0bfecf02c20357619c558d7f9142d77e61b0846f0b11ef5282401",
|
| 242 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 243 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 244 |
+
},
|
| 245 |
+
"qwen36-35b-base-q4km": {
|
| 246 |
+
"path": "artifacts/qwen36-35b-base-post-attention-rmsnorm.safetensors",
|
| 247 |
+
"bytes": 126504,
|
| 248 |
+
"sha256": "382c973b6b62e03e39f250732b994bd30ed16ef46344a8e872bb4fc4a6b24ecc",
|
| 249 |
+
"referenceClass": "Qwen3_5RMSNorm",
|
| 250 |
+
"storedWeightTransform": "one_plus_stored_delta"
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
},
|
| 254 |
"stages": [
|
| 255 |
{"name": "A-host-anchor", "steps": 200},
|
| 256 |
{"name": "B-benefit-gated-routing", "steps": 600},
|
training/fable_router_hybrid.py
CHANGED
|
@@ -96,6 +96,13 @@ class RouteTrace:
|
|
| 96 |
selected_weights: torch.Tensor
|
| 97 |
off_probability: torch.Tensor
|
| 98 |
active_scale: torch.Tensor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
class FrozenExpertRouterBlock(nn.Module):
|
|
@@ -110,6 +117,8 @@ class FrozenExpertRouterBlock(nn.Module):
|
|
| 110 |
top_k: int = 2,
|
| 111 |
initial_scale: float = 0.005,
|
| 112 |
maximum_scale: float = 0.1,
|
|
|
|
|
|
|
| 113 |
):
|
| 114 |
super().__init__()
|
| 115 |
if len(expert_ids) != 32 or len(set(expert_ids)) != 32:
|
|
@@ -124,6 +133,13 @@ class FrozenExpertRouterBlock(nn.Module):
|
|
| 124 |
self.expert_scale = nn.Parameter(torch.tensor(inverse_softplus(initial_scale)))
|
| 125 |
self.top_k = top_k
|
| 126 |
self.maximum_scale = float(maximum_scale)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
self.enabled = True
|
| 128 |
self.checkpoint_enabled = False
|
| 129 |
self._forced_expert: int | None = None
|
|
@@ -154,6 +170,26 @@ class FrozenExpertRouterBlock(nn.Module):
|
|
| 154 |
with torch.no_grad():
|
| 155 |
self.router.gate.weight.copy_(weight.to(self.router.gate.weight))
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
def materialize_experts(
|
| 158 |
self,
|
| 159 |
bank_path: Path,
|
|
@@ -199,7 +235,15 @@ class FrozenExpertRouterBlock(nn.Module):
|
|
| 199 |
return hidden_states
|
| 200 |
original_shape = hidden_states.shape
|
| 201 |
flat = hidden_states.reshape(-1, original_shape[-1])
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
if self._forced_expert is not None:
|
| 205 |
selected = torch.full(
|
|
@@ -215,12 +259,29 @@ class FrozenExpertRouterBlock(nn.Module):
|
|
| 215 |
off_probability = probabilities[:, -1]
|
| 216 |
scale = torch.clamp(F.softplus(self.expert_scale), max=self.maximum_scale).to(flat.dtype)
|
| 217 |
|
| 218 |
-
expert_output = self._expert_output(
|
| 219 |
host_std = flat.float().std().detach().clamp_min(1e-6)
|
|
|
|
| 220 |
expert_std = expert_output.float().std().detach().clamp_min(1e-6)
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
|
| 226 |
class AugmentedHostLayer(nn.Module):
|
|
|
|
| 96 |
selected_weights: torch.Tensor
|
| 97 |
off_probability: torch.Tensor
|
| 98 |
active_scale: torch.Tensor
|
| 99 |
+
host_std: torch.Tensor
|
| 100 |
+
donor_input_std: torch.Tensor
|
| 101 |
+
expert_std: torch.Tensor
|
| 102 |
+
normalization_factor: torch.Tensor
|
| 103 |
+
residual_std: torch.Tensor
|
| 104 |
+
residual_max_abs: torch.Tensor
|
| 105 |
+
post_add_changed: torch.Tensor
|
| 106 |
|
| 107 |
|
| 108 |
class FrozenExpertRouterBlock(nn.Module):
|
|
|
|
| 117 |
top_k: int = 2,
|
| 118 |
initial_scale: float = 0.005,
|
| 119 |
maximum_scale: float = 0.1,
|
| 120 |
+
donor_input_normalization: str = "none",
|
| 121 |
+
donor_norm_eps: float = 1e-6,
|
| 122 |
):
|
| 123 |
super().__init__()
|
| 124 |
if len(expert_ids) != 32 or len(set(expert_ids)) != 32:
|
|
|
|
| 133 |
self.expert_scale = nn.Parameter(torch.tensor(inverse_softplus(initial_scale)))
|
| 134 |
self.top_k = top_k
|
| 135 |
self.maximum_scale = float(maximum_scale)
|
| 136 |
+
if donor_input_normalization not in {"none", "unit_rms", "donor_rms"}:
|
| 137 |
+
raise ValueError("unsupported donor input normalization")
|
| 138 |
+
self.donor_input_normalization = donor_input_normalization
|
| 139 |
+
self.donor_norm_eps = float(donor_norm_eps)
|
| 140 |
+
self.register_buffer("donor_norm_weight", torch.ones(hidden_size), persistent=False)
|
| 141 |
+
self._donor_norm_loaded = donor_input_normalization != "donor_rms"
|
| 142 |
+
self.donor_norm_weight_transform: str | None = None
|
| 143 |
self.enabled = True
|
| 144 |
self.checkpoint_enabled = False
|
| 145 |
self._forced_expert: int | None = None
|
|
|
|
| 170 |
with torch.no_grad():
|
| 171 |
self.router.gate.weight.copy_(weight.to(self.router.gate.weight))
|
| 172 |
|
| 173 |
+
def load_donor_norm(
|
| 174 |
+
self,
|
| 175 |
+
weight: torch.Tensor,
|
| 176 |
+
*,
|
| 177 |
+
device: torch.device,
|
| 178 |
+
dtype: torch.dtype,
|
| 179 |
+
stored_weight_transform: str,
|
| 180 |
+
) -> None:
|
| 181 |
+
if tuple(weight.shape) != tuple(self.donor_norm_weight.shape):
|
| 182 |
+
raise ValueError(f"donor RMSNorm shape mismatch: {tuple(weight.shape)}")
|
| 183 |
+
if stored_weight_transform == "one_plus_stored_delta":
|
| 184 |
+
effective_weight = 1.0 + weight.float()
|
| 185 |
+
elif stored_weight_transform == "identity":
|
| 186 |
+
effective_weight = weight.float()
|
| 187 |
+
else:
|
| 188 |
+
raise ValueError(f"unsupported donor RMSNorm stored-weight transform: {stored_weight_transform}")
|
| 189 |
+
self.donor_norm_weight = effective_weight.to(device=device, dtype=dtype).contiguous()
|
| 190 |
+
self.donor_norm_weight_transform = stored_weight_transform
|
| 191 |
+
self._donor_norm_loaded = True
|
| 192 |
+
|
| 193 |
def materialize_experts(
|
| 194 |
self,
|
| 195 |
bank_path: Path,
|
|
|
|
| 235 |
return hidden_states
|
| 236 |
original_shape = hidden_states.shape
|
| 237 |
flat = hidden_states.reshape(-1, original_shape[-1])
|
| 238 |
+
donor_input = flat
|
| 239 |
+
if self.donor_input_normalization in {"unit_rms", "donor_rms"}:
|
| 240 |
+
if not self._donor_norm_loaded:
|
| 241 |
+
raise RuntimeError("exact donor RMSNorm weight was not loaded")
|
| 242 |
+
norm_weight = self.donor_norm_weight.float() if self.donor_input_normalization == "donor_rms" else None
|
| 243 |
+
donor_input = F.rms_norm(
|
| 244 |
+
flat.float(), (flat.shape[-1],), weight=norm_weight, eps=self.donor_norm_eps
|
| 245 |
+
).to(flat.dtype)
|
| 246 |
+
logits = self.router(donor_input)
|
| 247 |
|
| 248 |
if self._forced_expert is not None:
|
| 249 |
selected = torch.full(
|
|
|
|
| 259 |
off_probability = probabilities[:, -1]
|
| 260 |
scale = torch.clamp(F.softplus(self.expert_scale), max=self.maximum_scale).to(flat.dtype)
|
| 261 |
|
| 262 |
+
expert_output = self._expert_output(donor_input, selected, weights)
|
| 263 |
host_std = flat.float().std().detach().clamp_min(1e-6)
|
| 264 |
+
donor_input_std = donor_input.float().std().detach().clamp_min(1e-6)
|
| 265 |
expert_std = expert_output.float().std().detach().clamp_min(1e-6)
|
| 266 |
+
normalization = torch.clamp(host_std / expert_std, max=2.0).to(flat.dtype)
|
| 267 |
+
expert_output = expert_output * normalization
|
| 268 |
+
residual = scale * expert_output
|
| 269 |
+
routed_flat = flat + residual
|
| 270 |
+
self.last_trace = RouteTrace(
|
| 271 |
+
logits,
|
| 272 |
+
selected,
|
| 273 |
+
weights,
|
| 274 |
+
off_probability,
|
| 275 |
+
scale,
|
| 276 |
+
host_std,
|
| 277 |
+
donor_input_std,
|
| 278 |
+
expert_std,
|
| 279 |
+
normalization.detach(),
|
| 280 |
+
residual.float().std().detach(),
|
| 281 |
+
residual.float().abs().max().detach(),
|
| 282 |
+
torch.count_nonzero((routed_flat - flat).detach()),
|
| 283 |
+
)
|
| 284 |
+
return routed_flat.reshape(original_shape)
|
| 285 |
|
| 286 |
|
| 287 |
class AugmentedHostLayer(nn.Module):
|
training/run_fable_router_full_bank_fit.py
CHANGED
|
@@ -9,8 +9,10 @@ from __future__ import annotations
|
|
| 9 |
|
| 10 |
import argparse
|
| 11 |
import json
|
|
|
|
| 12 |
import os
|
| 13 |
import platform
|
|
|
|
| 14 |
import shutil
|
| 15 |
import sys
|
| 16 |
import time
|
|
@@ -20,9 +22,9 @@ from pathlib import Path
|
|
| 20 |
from typing import Any
|
| 21 |
|
| 22 |
import torch
|
| 23 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 24 |
from safetensors.torch import load_file, save_file
|
| 25 |
-
from transformers import AutoModelForCausalLM,
|
| 26 |
|
| 27 |
HERE = Path(__file__).resolve().parent
|
| 28 |
if str(HERE) not in sys.path:
|
|
@@ -58,8 +60,151 @@ def now() -> str:
|
|
| 58 |
return datetime.now(timezone.utc).isoformat()
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
def download(repo: str, revision: str, filename: str, repo_type: str, token: str | None) -> Path:
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
def verify_authorization(campaign_path: Path, result: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
@@ -169,7 +314,10 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 169 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 170 |
|
| 171 |
host = config["host"]
|
| 172 |
-
tokenizer =
|
|
|
|
|
|
|
|
|
|
| 173 |
rows = (
|
| 174 |
select_complete_rows(train_path, tokenizer, int(admission["maximumTokens"]))
|
| 175 |
if args.profile == "resident"
|
|
|
|
| 9 |
|
| 10 |
import argparse
|
| 11 |
import json
|
| 12 |
+
import multiprocessing
|
| 13 |
import os
|
| 14 |
import platform
|
| 15 |
+
import queue
|
| 16 |
import shutil
|
| 17 |
import sys
|
| 18 |
import time
|
|
|
|
| 22 |
from typing import Any
|
| 23 |
|
| 24 |
import torch
|
| 25 |
+
from huggingface_hub import HfApi, constants as hf_constants, hf_hub_download
|
| 26 |
from safetensors.torch import load_file, save_file
|
| 27 |
+
from transformers import AutoModelForCausalLM, PreTrainedTokenizerFast
|
| 28 |
|
| 29 |
HERE = Path(__file__).resolve().parent
|
| 30 |
if str(HERE) not in sys.path:
|
|
|
|
| 60 |
return datetime.now(timezone.utc).isoformat()
|
| 61 |
|
| 62 |
|
| 63 |
+
def _latest_incomplete(started_at: float) -> Path | None:
|
| 64 |
+
root = Path(hf_constants.HF_HUB_CACHE)
|
| 65 |
+
if not root.is_dir():
|
| 66 |
+
return None
|
| 67 |
+
candidates = [
|
| 68 |
+
path
|
| 69 |
+
for path in root.rglob("*.incomplete")
|
| 70 |
+
if path.is_file() and path.stat().st_mtime >= started_at - 5
|
| 71 |
+
]
|
| 72 |
+
return max(candidates, key=lambda path: path.stat().st_mtime, default=None)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _download_worker(
|
| 76 |
+
outcome: Any,
|
| 77 |
+
repo: str,
|
| 78 |
+
revision: str,
|
| 79 |
+
filename: str,
|
| 80 |
+
repo_type: str,
|
| 81 |
+
token: str | None,
|
| 82 |
+
) -> None:
|
| 83 |
+
try:
|
| 84 |
+
path = hf_hub_download(
|
| 85 |
+
repo_id=repo,
|
| 86 |
+
revision=revision,
|
| 87 |
+
filename=filename,
|
| 88 |
+
repo_type=repo_type,
|
| 89 |
+
token=token,
|
| 90 |
+
)
|
| 91 |
+
outcome.put({"path": str(path)})
|
| 92 |
+
except BaseException as exc:
|
| 93 |
+
outcome.put({"errorType": type(exc).__name__, "error": str(exc)})
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _download_once_with_progress(
|
| 97 |
+
repo: str,
|
| 98 |
+
revision: str,
|
| 99 |
+
filename: str,
|
| 100 |
+
repo_type: str,
|
| 101 |
+
token: str | None,
|
| 102 |
+
attempt: int,
|
| 103 |
+
) -> Path:
|
| 104 |
+
|
| 105 |
+
started_at = time.time()
|
| 106 |
+
previous_bytes = 0
|
| 107 |
+
previous_at = started_at
|
| 108 |
+
context = multiprocessing.get_context("spawn")
|
| 109 |
+
outcome = context.Queue()
|
| 110 |
+
transfer_mode = "xet" if attempt % 2 else "http"
|
| 111 |
+
transfer_keys = ("HF_HUB_DISABLE_XET", "HF_XET_HIGH_PERFORMANCE", "HF_XET_NUM_CONCURRENT_RANGE_GETS")
|
| 112 |
+
previous_transfer_env = {key: os.environ.get(key) for key in transfer_keys}
|
| 113 |
+
if transfer_mode == "xet":
|
| 114 |
+
os.environ.pop("HF_HUB_DISABLE_XET", None)
|
| 115 |
+
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 116 |
+
os.environ["HF_XET_NUM_CONCURRENT_RANGE_GETS"] = "32"
|
| 117 |
+
else:
|
| 118 |
+
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 119 |
+
os.environ.pop("HF_XET_HIGH_PERFORMANCE", None)
|
| 120 |
+
os.environ.pop("HF_XET_NUM_CONCURRENT_RANGE_GETS", None)
|
| 121 |
+
process = context.Process(
|
| 122 |
+
target=_download_worker,
|
| 123 |
+
args=(outcome, repo, revision, filename, repo_type, token),
|
| 124 |
+
name=f"hub-download-{attempt}",
|
| 125 |
+
daemon=True,
|
| 126 |
+
)
|
| 127 |
+
try:
|
| 128 |
+
process.start()
|
| 129 |
+
finally:
|
| 130 |
+
for key, value in previous_transfer_env.items():
|
| 131 |
+
if value is None:
|
| 132 |
+
os.environ.pop(key, None)
|
| 133 |
+
else:
|
| 134 |
+
os.environ[key] = value
|
| 135 |
+
print(f"download-attempt {filename} attempt={attempt} transferMode={transfer_mode}", flush=True)
|
| 136 |
+
consecutive_slow_samples = 0
|
| 137 |
+
while process.is_alive():
|
| 138 |
+
process.join(timeout=15)
|
| 139 |
+
sampled_at = time.time()
|
| 140 |
+
incomplete = _latest_incomplete(started_at)
|
| 141 |
+
size = incomplete.stat().st_size if incomplete is not None else previous_bytes
|
| 142 |
+
if size == previous_bytes:
|
| 143 |
+
if sampled_at - started_at >= 120 and sampled_at - previous_at >= 90:
|
| 144 |
+
print(
|
| 145 |
+
f"download-stalled-restart {filename} attempt={attempt} "
|
| 146 |
+
f"bytes={size} elapsedSeconds={round(sampled_at-started_at)}",
|
| 147 |
+
flush=True,
|
| 148 |
+
)
|
| 149 |
+
process.terminate()
|
| 150 |
+
process.join(timeout=30)
|
| 151 |
+
if process.is_alive():
|
| 152 |
+
process.kill()
|
| 153 |
+
process.join()
|
| 154 |
+
raise RuntimeError(f"download made no progress for 90 seconds for {filename}")
|
| 155 |
+
continue
|
| 156 |
+
rate = (size - previous_bytes) / max(sampled_at - previous_at, 0.001) / (1024 * 1024)
|
| 157 |
+
print(
|
| 158 |
+
f"download-progress {filename} attempt={attempt} bytes={size} "
|
| 159 |
+
f"deltaBytes={size - previous_bytes} rateMiBs={rate:.2f} "
|
| 160 |
+
f"elapsedSeconds={round(sampled_at - started_at)} transferMode={transfer_mode}",
|
| 161 |
+
flush=True,
|
| 162 |
+
)
|
| 163 |
+
previous_bytes = size
|
| 164 |
+
previous_at = sampled_at
|
| 165 |
+
if sampled_at - started_at >= 120 and rate < 1.0:
|
| 166 |
+
consecutive_slow_samples += 1
|
| 167 |
+
else:
|
| 168 |
+
consecutive_slow_samples = 0
|
| 169 |
+
if consecutive_slow_samples >= 4:
|
| 170 |
+
print(
|
| 171 |
+
f"download-slow-restart {filename} attempt={attempt} "
|
| 172 |
+
f"rateMiBs={rate:.2f} bytes={size} elapsedSeconds={round(sampled_at-started_at)}",
|
| 173 |
+
flush=True,
|
| 174 |
+
)
|
| 175 |
+
process.terminate()
|
| 176 |
+
process.join(timeout=30)
|
| 177 |
+
if process.is_alive():
|
| 178 |
+
process.kill()
|
| 179 |
+
process.join()
|
| 180 |
+
raise RuntimeError(f"sustained download rate below 1 MiB/s for {filename}")
|
| 181 |
+
process.join()
|
| 182 |
+
try:
|
| 183 |
+
observed = outcome.get(timeout=2)
|
| 184 |
+
except queue.Empty as exc:
|
| 185 |
+
raise RuntimeError(f"download worker exited {process.exitcode} without an outcome for {filename}") from exc
|
| 186 |
+
if "error" in observed:
|
| 187 |
+
raise RuntimeError(f"{observed.get('errorType')}: {observed['error']}")
|
| 188 |
+
return Path(str(observed["path"]))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
def download(repo: str, revision: str, filename: str, repo_type: str, token: str | None) -> Path:
|
| 192 |
+
last_error: Exception | None = None
|
| 193 |
+
for attempt in range(1, 7):
|
| 194 |
+
try:
|
| 195 |
+
path = _download_once_with_progress(repo, revision, filename, repo_type, token, attempt)
|
| 196 |
+
print(f"download-complete {filename} attempt={attempt}", flush=True)
|
| 197 |
+
return path
|
| 198 |
+
except Exception as exc:
|
| 199 |
+
last_error = exc
|
| 200 |
+
print(
|
| 201 |
+
f"download-retry {filename} attempt={attempt}/6 error={type(exc).__name__}: {str(exc)[:300]}",
|
| 202 |
+
flush=True,
|
| 203 |
+
)
|
| 204 |
+
if attempt < 6:
|
| 205 |
+
time.sleep(min(20 * attempt, 90))
|
| 206 |
+
assert last_error is not None
|
| 207 |
+
raise last_error
|
| 208 |
|
| 209 |
|
| 210 |
def verify_authorization(campaign_path: Path, result: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
|
|
| 314 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 315 |
|
| 316 |
host = config["host"]
|
| 317 |
+
tokenizer = PreTrainedTokenizerFast.from_pretrained(
|
| 318 |
+
host["repo"], revision=host["revision"], token=token, trust_remote_code=True
|
| 319 |
+
)
|
| 320 |
+
result["tokenizerLoader"] = "PreTrainedTokenizerFast"
|
| 321 |
rows = (
|
| 322 |
select_complete_rows(train_path, tokenizer, int(admission["maximumTokens"]))
|
| 323 |
if args.profile == "resident"
|
training/run_fable_router_optimizer_smoke.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import argparse
|
|
|
|
| 6 |
import json
|
| 7 |
import os
|
| 8 |
import platform
|
|
@@ -16,7 +17,7 @@ from typing import Any
|
|
| 16 |
import torch
|
| 17 |
import torch.nn.functional as F
|
| 18 |
from safetensors.torch import load_file, save_file
|
| 19 |
-
from transformers import AutoModelForCausalLM,
|
| 20 |
|
| 21 |
HERE = Path(__file__).resolve().parent
|
| 22 |
if str(HERE) not in sys.path:
|
|
@@ -97,9 +98,36 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 97 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 98 |
|
| 99 |
host = config["host"]
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
result["rows"] = [{"id": row["id"], "lane": row["lane"], "tokens": len(row["inputIds"])} for row in rows]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
device = torch.device("cuda:0")
|
| 104 |
dtype = compute_dtype(result["gpu"])
|
| 105 |
torch.cuda.reset_peak_memory_stats(device)
|
|
@@ -113,12 +141,45 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 113 |
model.enable_input_require_grads()
|
| 114 |
warm_state = load_file(str(warm_path), device="cpu")
|
| 115 |
blocks: list[FrozenExpertRouterBlock] = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
for layer in range(30):
|
| 117 |
-
block = FrozenExpertRouterBlock(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
attach_router_block(model, layer, block)
|
| 119 |
block.router.to(device=device, dtype=torch.float32)
|
| 120 |
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 121 |
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 123 |
block.checkpoint_enabled = True
|
| 124 |
blocks.append(block)
|
|
@@ -130,6 +191,10 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 130 |
before_state = router_state_dict(model)
|
| 131 |
parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]
|
| 132 |
optimizer = torch.optim.AdamW(parameters, lr=float(optimizer_contract["learningRate"]), weight_decay=0.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
metrics = []
|
| 135 |
positive_and_off = False
|
|
@@ -158,7 +223,7 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 158 |
for column, local_expert in enumerate(candidates):
|
| 159 |
mapped[column_targets == column] = local_expert
|
| 160 |
positive = mapped != blocks[probe_layer].off_class_index
|
| 161 |
-
positive_and_off = bool(positive.any() and (~positive).any())
|
| 162 |
discovery = {
|
| 163 |
"layer": probe_layer,
|
| 164 |
"candidates": candidates,
|
|
@@ -194,7 +259,37 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 194 |
total = routed.loss + kl_weight * kl + ranking_loss + 0.015 * route_cost
|
| 195 |
if not torch.isfinite(total):
|
| 196 |
raise RuntimeError("optimizer smoke produced a non-finite objective")
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
layer_gradients = []
|
| 199 |
for layer, block in enumerate(blocks):
|
| 200 |
gate_grad = block.router.gate.weight.grad
|
|
@@ -230,6 +325,7 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 230 |
"totalLoss": float(total.detach()),
|
| 231 |
"gradientNorm": grad_norm,
|
| 232 |
"discovery": discovery,
|
|
|
|
| 233 |
"layerGradients": layer_gradients,
|
| 234 |
"layerUpdates": layer_updates,
|
| 235 |
})
|
|
@@ -238,6 +334,17 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 238 |
|
| 239 |
if not positive_and_off:
|
| 240 |
raise RuntimeError("counterfactual optimizer smoke did not produce both expert and host-only targets")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
after_state = router_state_dict(model)
|
| 242 |
changed_layers = []
|
| 243 |
update_diagnostics = []
|
|
@@ -260,8 +367,12 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 260 |
output = Path(result["output"])
|
| 261 |
checkpoint = output / "router-checkpoint.safetensors"
|
| 262 |
optimizer_path = output / "optimizer.pt"
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
result["steps"] = metrics
|
| 266 |
result["updateGate"] = {
|
| 267 |
"changedRouterLayers": changed_layers,
|
|
@@ -270,6 +381,7 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 270 |
}
|
| 271 |
result["checkpoint"] = {"path": str(checkpoint), "bytes": checkpoint.stat().st_size, "sha256": sha256(checkpoint)}
|
| 272 |
result["optimizerCheckpoint"] = {"path": str(optimizer_path), "bytes": optimizer_path.stat().st_size, "sha256": sha256(optimizer_path)}
|
|
|
|
| 273 |
result["runtime"] = {
|
| 274 |
"seconds": time.perf_counter() - started,
|
| 275 |
"peakAllocatedVramMiB": torch.cuda.max_memory_allocated(device) / 2**20,
|
|
@@ -290,6 +402,7 @@ def main() -> int:
|
|
| 290 |
parser.add_argument("--bank", required=True)
|
| 291 |
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 292 |
parser.add_argument("--memory-proof", type=Path, required=True)
|
|
|
|
| 293 |
parser.add_argument("--work-dir", type=Path, default=Path("/content/autonoma-fable-training"))
|
| 294 |
args = parser.parse_args()
|
| 295 |
if not args.owner_execute:
|
|
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
import json
|
| 8 |
import os
|
| 9 |
import platform
|
|
|
|
| 17 |
import torch
|
| 18 |
import torch.nn.functional as F
|
| 19 |
from safetensors.torch import load_file, save_file
|
| 20 |
+
from transformers import AutoModelForCausalLM, PreTrainedTokenizerFast
|
| 21 |
|
| 22 |
HERE = Path(__file__).resolve().parent
|
| 23 |
if str(HERE) not in sys.path:
|
|
|
|
| 98 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 99 |
|
| 100 |
host = config["host"]
|
| 101 |
+
# The pinned revision names the Transformers 5 TokenizersBackend class, which
|
| 102 |
+
# is not registered by the pinned Kaggle Transformers 4 runtime. Load the
|
| 103 |
+
# same tokenizer.json explicitly through its version-portable fast base.
|
| 104 |
+
tokenizer = PreTrainedTokenizerFast.from_pretrained(
|
| 105 |
+
host["repo"], revision=host["revision"], token=token, trust_remote_code=True
|
| 106 |
+
)
|
| 107 |
+
result["tokenizerLoader"] = "PreTrainedTokenizerFast"
|
| 108 |
+
rows = select_complete_rows(
|
| 109 |
+
train_path,
|
| 110 |
+
tokenizer,
|
| 111 |
+
int(optimizer_contract["maximumTokens"]),
|
| 112 |
+
rows_per_lane=int(optimizer_contract["rowsPerLane"]),
|
| 113 |
+
)
|
| 114 |
result["rows"] = [{"id": row["id"], "lane": row["lane"], "tokens": len(row["inputIds"])} for row in rows]
|
| 115 |
+
tokenizer_contract = optimizer_contract["tokenizerContract"]
|
| 116 |
+
token_payload = json.dumps(rows, sort_keys=True, separators=(",", ":")).encode()
|
| 117 |
+
token_signature = hashlib.sha256(token_payload).hexdigest()
|
| 118 |
+
result["tokenizerContract"] = {
|
| 119 |
+
"loader": "PreTrainedTokenizerFast",
|
| 120 |
+
"padTokenId": int(tokenizer.pad_token_id),
|
| 121 |
+
"inputIdsSignatureSha256": token_signature,
|
| 122 |
+
"expectedInputIdsSignatureSha256": tokenizer_contract["inputIdsSignatureSha256"],
|
| 123 |
+
"passed": (
|
| 124 |
+
token_signature == tokenizer_contract["inputIdsSignatureSha256"]
|
| 125 |
+
and int(tokenizer.pad_token_id) == int(tokenizer_contract["padTokenId"])
|
| 126 |
+
and result["rows"] == tokenizer_contract["selectedRows"]
|
| 127 |
+
),
|
| 128 |
+
}
|
| 129 |
+
if not result["tokenizerContract"]["passed"]:
|
| 130 |
+
raise RuntimeError("portable tokenizer output differs from the pinned Transformers 5 reference")
|
| 131 |
device = torch.device("cuda:0")
|
| 132 |
dtype = compute_dtype(result["gpu"])
|
| 133 |
torch.cuda.reset_peak_memory_stats(device)
|
|
|
|
| 141 |
model.enable_input_require_grads()
|
| 142 |
warm_state = load_file(str(warm_path), device="cpu")
|
| 143 |
blocks: list[FrozenExpertRouterBlock] = []
|
| 144 |
+
donor_norm = optimizer_contract["donorInputNormalization"]
|
| 145 |
+
result["donorInputNormalization"] = donor_norm
|
| 146 |
+
norm_state = None
|
| 147 |
+
if donor_norm["mode"] == "donor_rms":
|
| 148 |
+
if args.norm_sidecar is None:
|
| 149 |
+
raise RuntimeError("exact donor RMSNorm mode requires --norm-sidecar")
|
| 150 |
+
sidecar = donor_norm["sidecars"].get(args.bank)
|
| 151 |
+
if sidecar is None:
|
| 152 |
+
raise RuntimeError(f"no exact donor RMSNorm sidecar is frozen for {args.bank}")
|
| 153 |
+
if sidecar.get("referenceClass") != "Qwen3_5RMSNorm":
|
| 154 |
+
raise RuntimeError("donor RMSNorm sidecar is not bound to Qwen3_5RMSNorm")
|
| 155 |
+
if sidecar.get("storedWeightTransform") != "one_plus_stored_delta":
|
| 156 |
+
raise RuntimeError("Qwen3_5RMSNorm requires one_plus_stored_delta")
|
| 157 |
+
norm_path = args.norm_sidecar.resolve()
|
| 158 |
+
result["donorNormArtifact"] = verify_file(norm_path, int(sidecar["bytes"]), sidecar["sha256"])
|
| 159 |
+
result["donorNormEquation"] = {
|
| 160 |
+
"referenceClass": sidecar["referenceClass"],
|
| 161 |
+
"storedWeightTransform": sidecar["storedWeightTransform"],
|
| 162 |
+
"equation": "rms_unit(x) * (1 + stored_weight)",
|
| 163 |
+
"passed": True,
|
| 164 |
+
}
|
| 165 |
+
norm_state = load_file(str(norm_path), device="cpu")
|
| 166 |
for layer in range(30):
|
| 167 |
+
block = FrozenExpertRouterBlock(
|
| 168 |
+
selected_expert_ids(bank_definition, layer), top_k=2,
|
| 169 |
+
initial_scale=0.005, maximum_scale=0.025,
|
| 170 |
+
donor_input_normalization=donor_norm["mode"],
|
| 171 |
+
donor_norm_eps=float(donor_norm["epsilon"]),
|
| 172 |
+
)
|
| 173 |
attach_router_block(model, layer, block)
|
| 174 |
block.router.to(device=device, dtype=torch.float32)
|
| 175 |
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 176 |
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
| 177 |
+
if norm_state is not None:
|
| 178 |
+
block.load_donor_norm(
|
| 179 |
+
norm_state[f"model.layers.{layer}.post_attention_layernorm.weight"],
|
| 180 |
+
device=device, dtype=dtype,
|
| 181 |
+
stored_weight_transform=sidecar["storedWeightTransform"],
|
| 182 |
+
)
|
| 183 |
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 184 |
block.checkpoint_enabled = True
|
| 185 |
blocks.append(block)
|
|
|
|
| 191 |
before_state = router_state_dict(model)
|
| 192 |
parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]
|
| 193 |
optimizer = torch.optim.AdamW(parameters, lr=float(optimizer_contract["learningRate"]), weight_decay=0.0)
|
| 194 |
+
gradient_loss_scale = float(optimizer_contract["gradientLossScale"])
|
| 195 |
+
if not gradient_loss_scale >= 1.0:
|
| 196 |
+
raise RuntimeError("optimizer gradient loss scale must be at least one")
|
| 197 |
+
result["gradientLossScale"] = gradient_loss_scale
|
| 198 |
|
| 199 |
metrics = []
|
| 200 |
positive_and_off = False
|
|
|
|
| 223 |
for column, local_expert in enumerate(candidates):
|
| 224 |
mapped[column_targets == column] = local_expert
|
| 225 |
positive = mapped != blocks[probe_layer].off_class_index
|
| 226 |
+
positive_and_off = positive_and_off or bool(positive.any() and (~positive).any())
|
| 227 |
discovery = {
|
| 228 |
"layer": probe_layer,
|
| 229 |
"candidates": candidates,
|
|
|
|
| 259 |
total = routed.loss + kl_weight * kl + ranking_loss + 0.015 * route_cost
|
| 260 |
if not torch.isfinite(total):
|
| 261 |
raise RuntimeError("optimizer smoke produced a non-finite objective")
|
| 262 |
+
layer_forward_diagnostics = []
|
| 263 |
+
for layer, block in enumerate(blocks):
|
| 264 |
+
trace = block.last_trace
|
| 265 |
+
if trace is None:
|
| 266 |
+
raise RuntimeError(f"layer {layer} router trace is missing")
|
| 267 |
+
layer_forward_diagnostics.append({
|
| 268 |
+
"layer": layer,
|
| 269 |
+
"logitsDtype": str(trace.logits.dtype),
|
| 270 |
+
"selectedWeightsDtype": str(trace.selected_weights.dtype),
|
| 271 |
+
"selectedUniqueExperts": int(torch.unique(trace.selected_experts).numel()),
|
| 272 |
+
"meanSelectedWeight": float(trace.selected_weights.float().mean()),
|
| 273 |
+
"meanOffProbability": float(trace.off_probability.float().mean()),
|
| 274 |
+
"activeScale": float(trace.active_scale.float()),
|
| 275 |
+
"hostStd": float(trace.host_std.float()),
|
| 276 |
+
"donorInputStd": float(trace.donor_input_std.float()),
|
| 277 |
+
"expertStd": float(trace.expert_std.float()),
|
| 278 |
+
"normalizationFactor": float(trace.normalization_factor.float()),
|
| 279 |
+
"residualStd": float(trace.residual_std.float()),
|
| 280 |
+
"residualMaxAbs": float(trace.residual_max_abs.float()),
|
| 281 |
+
"postAddChanged": int(trace.post_add_changed),
|
| 282 |
+
})
|
| 283 |
+
# Scaling the scalar objective before backpropagation is numerically
|
| 284 |
+
# neutral after unscaling the FP32 router gradients, while preventing
|
| 285 |
+
# small router signals from underflowing as they traverse the frozen
|
| 286 |
+
# FP16 residual branch. Ornith layer 2 exposed this exact failure:
|
| 287 |
+
# its scale gradient survived but its gate gradient was identically
|
| 288 |
+
# zero across all eight deterministic rows.
|
| 289 |
+
(total * gradient_loss_scale).backward()
|
| 290 |
+
for parameter in parameters:
|
| 291 |
+
if parameter.grad is not None:
|
| 292 |
+
parameter.grad.div_(gradient_loss_scale)
|
| 293 |
layer_gradients = []
|
| 294 |
for layer, block in enumerate(blocks):
|
| 295 |
gate_grad = block.router.gate.weight.grad
|
|
|
|
| 325 |
"totalLoss": float(total.detach()),
|
| 326 |
"gradientNorm": grad_norm,
|
| 327 |
"discovery": discovery,
|
| 328 |
+
"layerForwardDiagnostics": layer_forward_diagnostics,
|
| 329 |
"layerGradients": layer_gradients,
|
| 330 |
"layerUpdates": layer_updates,
|
| 331 |
})
|
|
|
|
| 334 |
|
| 335 |
if not positive_and_off:
|
| 336 |
raise RuntimeError("counterfactual optimizer smoke did not produce both expert and host-only targets")
|
| 337 |
+
effective_layers = sorted({
|
| 338 |
+
int(row["layer"])
|
| 339 |
+
for step in metrics
|
| 340 |
+
for row in step["layerForwardDiagnostics"]
|
| 341 |
+
if int(row["postAddChanged"]) > 0
|
| 342 |
+
})
|
| 343 |
+
result["effectiveResidualLayers"] = effective_layers
|
| 344 |
+
if effective_layers != list(range(30)):
|
| 345 |
+
raise RuntimeError(
|
| 346 |
+
f"not every router residual changed the host activation: {effective_layers}"
|
| 347 |
+
)
|
| 348 |
after_state = router_state_dict(model)
|
| 349 |
changed_layers = []
|
| 350 |
update_diagnostics = []
|
|
|
|
| 367 |
output = Path(result["output"])
|
| 368 |
checkpoint = output / "router-checkpoint.safetensors"
|
| 369 |
optimizer_path = output / "optimizer.pt"
|
| 370 |
+
completed_steps = len(metrics)
|
| 371 |
+
save_file(after_state, str(checkpoint), metadata={
|
| 372 |
+
"autonoma": "non-routing-optimizer-smoke", "bank": args.bank,
|
| 373 |
+
"completed_steps": str(completed_steps),
|
| 374 |
+
})
|
| 375 |
+
torch.save({"optimizer": optimizer.state_dict(), "completedSteps": completed_steps, "bank": args.bank}, optimizer_path)
|
| 376 |
result["steps"] = metrics
|
| 377 |
result["updateGate"] = {
|
| 378 |
"changedRouterLayers": changed_layers,
|
|
|
|
| 381 |
}
|
| 382 |
result["checkpoint"] = {"path": str(checkpoint), "bytes": checkpoint.stat().st_size, "sha256": sha256(checkpoint)}
|
| 383 |
result["optimizerCheckpoint"] = {"path": str(optimizer_path), "bytes": optimizer_path.stat().st_size, "sha256": sha256(optimizer_path)}
|
| 384 |
+
result["optimizerState"] = {"completedSteps": completed_steps, "bank": args.bank}
|
| 385 |
result["runtime"] = {
|
| 386 |
"seconds": time.perf_counter() - started,
|
| 387 |
"peakAllocatedVramMiB": torch.cuda.max_memory_allocated(device) / 2**20,
|
|
|
|
| 402 |
parser.add_argument("--bank", required=True)
|
| 403 |
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 404 |
parser.add_argument("--memory-proof", type=Path, required=True)
|
| 405 |
+
parser.add_argument("--norm-sidecar", type=Path)
|
| 406 |
parser.add_argument("--work-dir", type=Path, default=Path("/content/autonoma-fable-training"))
|
| 407 |
args = parser.parse_args()
|
| 408 |
if not args.owner_execute:
|
training/run_fable_router_stage_a_chunk.py
CHANGED
|
@@ -54,6 +54,7 @@ MAXIMUM_TOKENS = 2048
|
|
| 54 |
MAXIMUM_CHUNK_STEPS = 25
|
| 55 |
LEARNING_RATE = 2e-4
|
| 56 |
GRADIENT_CLIP = 1.0
|
|
|
|
| 57 |
REPLAY_MAXIMUM = 4096
|
| 58 |
|
| 59 |
|
|
@@ -292,9 +293,29 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 292 |
train_cfg = config["curriculum"]["sftTrain"]
|
| 293 |
train_path = args.curriculum_path.resolve()
|
| 294 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
host = config["host"]
|
| 297 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
|
|
|
|
|
|
| 298 |
pools = load_row_pools(train_path, tokenizer)
|
| 299 |
lane_schedule = frozen_lane_schedule(curriculum, SEED)
|
| 300 |
rows = scheduled_rows(pools, lane_schedule, args.start_step, end_step)
|
|
@@ -314,11 +335,22 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 314 |
warm_state = load_file(str(warm_path), device="cpu")
|
| 315 |
blocks: list[FrozenExpertRouterBlock] = []
|
| 316 |
for layer in range(30):
|
| 317 |
-
block = FrozenExpertRouterBlock(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
attach_router_block(model, layer, block)
|
| 319 |
block.router.to(device=device, dtype=torch.float32)
|
| 320 |
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 321 |
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 323 |
block.checkpoint_enabled = True
|
| 324 |
blocks.append(block)
|
|
@@ -414,7 +446,10 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 414 |
)
|
| 415 |
if not torch.isfinite(total):
|
| 416 |
raise RuntimeError("Stage-A chunk produced a non-finite objective")
|
| 417 |
-
total.backward()
|
|
|
|
|
|
|
|
|
|
| 418 |
gradient_norm = float(torch.nn.utils.clip_grad_norm_(parameters, GRADIENT_CLIP))
|
| 419 |
optimizer.step()
|
| 420 |
maximum_scale = max(float(F.softplus(block.expert_scale).detach()) for block in blocks)
|
|
@@ -483,6 +518,7 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 483 |
"assistant_only_prefix_stable_supervision": True,
|
| 484 |
"complete_rows_without_truncation": True,
|
| 485 |
"host_and_experts_frozen": True,
|
|
|
|
| 486 |
"deterministic_lane_and_expert_coverage": True,
|
| 487 |
"counterfactual_off_class_and_positive_replay": True,
|
| 488 |
"stage_a_scale_cap": True,
|
|
@@ -498,6 +534,7 @@ def main() -> int:
|
|
| 498 |
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 499 |
parser.add_argument("--optimizer-proof", type=Path, required=True)
|
| 500 |
parser.add_argument("--optimizer-consolidation", type=Path, required=True)
|
|
|
|
| 501 |
parser.add_argument("--start-step", type=int, required=True)
|
| 502 |
parser.add_argument("--steps", type=int, default=MAXIMUM_CHUNK_STEPS)
|
| 503 |
parser.add_argument("--resume-dir", type=Path)
|
|
|
|
| 54 |
MAXIMUM_CHUNK_STEPS = 25
|
| 55 |
LEARNING_RATE = 2e-4
|
| 56 |
GRADIENT_CLIP = 1.0
|
| 57 |
+
GRADIENT_LOSS_SCALE = 1024.0
|
| 58 |
REPLAY_MAXIMUM = 4096
|
| 59 |
|
| 60 |
|
|
|
|
| 293 |
train_cfg = config["curriculum"]["sftTrain"]
|
| 294 |
train_path = args.curriculum_path.resolve()
|
| 295 |
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 296 |
+
donor_norm = campaign["training"]["donorInputNormalization"]
|
| 297 |
+
if donor_norm["mode"] != "donor_rms" or args.norm_sidecar is None:
|
| 298 |
+
raise RuntimeError("Stage A requires an exact donor RMSNorm sidecar")
|
| 299 |
+
sidecar = donor_norm["sidecars"].get(args.bank)
|
| 300 |
+
if sidecar is None:
|
| 301 |
+
raise RuntimeError(f"no exact donor RMSNorm sidecar is frozen for {args.bank}")
|
| 302 |
+
if sidecar.get("referenceClass") != "Qwen3_5RMSNorm" or sidecar.get("storedWeightTransform") != "one_plus_stored_delta":
|
| 303 |
+
raise RuntimeError("Stage A donor norm is not architecture-faithful Qwen3_5RMSNorm")
|
| 304 |
+
norm_path = args.norm_sidecar.resolve()
|
| 305 |
+
result["donorInputNormalization"] = donor_norm
|
| 306 |
+
result["donorNormArtifact"] = verify_file(norm_path, int(sidecar["bytes"]), sidecar["sha256"])
|
| 307 |
+
result["donorNormEquation"] = {
|
| 308 |
+
"referenceClass": sidecar["referenceClass"],
|
| 309 |
+
"storedWeightTransform": sidecar["storedWeightTransform"],
|
| 310 |
+
"equation": "rms_unit(x) * (1 + stored_weight)",
|
| 311 |
+
"passed": True,
|
| 312 |
+
}
|
| 313 |
+
norm_state = load_file(str(norm_path), device="cpu")
|
| 314 |
|
| 315 |
host = config["host"]
|
| 316 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 317 |
+
host["repo"], revision=host["revision"], token=token, trust_remote_code=True
|
| 318 |
+
)
|
| 319 |
pools = load_row_pools(train_path, tokenizer)
|
| 320 |
lane_schedule = frozen_lane_schedule(curriculum, SEED)
|
| 321 |
rows = scheduled_rows(pools, lane_schedule, args.start_step, end_step)
|
|
|
|
| 335 |
warm_state = load_file(str(warm_path), device="cpu")
|
| 336 |
blocks: list[FrozenExpertRouterBlock] = []
|
| 337 |
for layer in range(30):
|
| 338 |
+
block = FrozenExpertRouterBlock(
|
| 339 |
+
selected_expert_ids(definition, layer), top_k=2,
|
| 340 |
+
initial_scale=0.005, maximum_scale=0.025,
|
| 341 |
+
donor_input_normalization=donor_norm["mode"],
|
| 342 |
+
donor_norm_eps=float(donor_norm["epsilon"]),
|
| 343 |
+
)
|
| 344 |
attach_router_block(model, layer, block)
|
| 345 |
block.router.to(device=device, dtype=torch.float32)
|
| 346 |
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 347 |
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
| 348 |
+
block.load_donor_norm(
|
| 349 |
+
norm_state[f"model.layers.{layer}.post_attention_layernorm.weight"],
|
| 350 |
+
device=device,
|
| 351 |
+
dtype=dtype,
|
| 352 |
+
stored_weight_transform=sidecar["storedWeightTransform"],
|
| 353 |
+
)
|
| 354 |
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 355 |
block.checkpoint_enabled = True
|
| 356 |
blocks.append(block)
|
|
|
|
| 446 |
)
|
| 447 |
if not torch.isfinite(total):
|
| 448 |
raise RuntimeError("Stage-A chunk produced a non-finite objective")
|
| 449 |
+
(total * GRADIENT_LOSS_SCALE).backward()
|
| 450 |
+
for parameter in parameters:
|
| 451 |
+
if parameter.grad is not None:
|
| 452 |
+
parameter.grad.div_(GRADIENT_LOSS_SCALE)
|
| 453 |
gradient_norm = float(torch.nn.utils.clip_grad_norm_(parameters, GRADIENT_CLIP))
|
| 454 |
optimizer.step()
|
| 455 |
maximum_scale = max(float(F.softplus(block.expert_scale).detach()) for block in blocks)
|
|
|
|
| 518 |
"assistant_only_prefix_stable_supervision": True,
|
| 519 |
"complete_rows_without_truncation": True,
|
| 520 |
"host_and_experts_frozen": True,
|
| 521 |
+
"donor_norm_equation_matches_architecture": True,
|
| 522 |
"deterministic_lane_and_expert_coverage": True,
|
| 523 |
"counterfactual_off_class_and_positive_replay": True,
|
| 524 |
"stage_a_scale_cap": True,
|
|
|
|
| 534 |
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 535 |
parser.add_argument("--optimizer-proof", type=Path, required=True)
|
| 536 |
parser.add_argument("--optimizer-consolidation", type=Path, required=True)
|
| 537 |
+
parser.add_argument("--norm-sidecar", type=Path, required=True)
|
| 538 |
parser.add_argument("--start-step", type=int, required=True)
|
| 539 |
parser.add_argument("--steps", type=int, default=MAXIMUM_CHUNK_STEPS)
|
| 540 |
parser.add_argument("--resume-dir", type=Path)
|
training/run_fable_router_structural_smoke.py
CHANGED
|
@@ -34,7 +34,7 @@ import torch
|
|
| 34 |
import torch.nn.functional as F
|
| 35 |
from huggingface_hub import HfApi, hf_hub_download
|
| 36 |
from safetensors.torch import load_file, save_file
|
| 37 |
-
from transformers import AutoModelForCausalLM,
|
| 38 |
|
| 39 |
HERE = Path(__file__).resolve().parent
|
| 40 |
if str(HERE) not in sys.path:
|
|
@@ -84,9 +84,16 @@ def render_and_tokenize(tokenizer: Any, messages: list[dict[str, Any]]) -> list[
|
|
| 84 |
return list(tokenizer(rendered, add_special_tokens=False)["input_ids"])
|
| 85 |
|
| 86 |
|
| 87 |
-
def select_complete_rows(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
wanted = ("host_preservation", "verified_expert")
|
| 89 |
-
|
| 90 |
for row in iter_jsonl(path):
|
| 91 |
validate_curriculum_row(row, "train")
|
| 92 |
lane = str(row["lane"])
|
|
@@ -95,16 +102,23 @@ def select_complete_rows(path: Path, tokenizer: Any, maximum_tokens: int) -> lis
|
|
| 95 |
ids = render_and_tokenize(tokenizer, row["messages"])
|
| 96 |
if len(ids) > maximum_tokens:
|
| 97 |
continue
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
best[lane] = (len(ids), row, ids)
|
| 101 |
-
missing = sorted(set(wanted) - set(best))
|
| 102 |
if missing:
|
| 103 |
-
raise RuntimeError(
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
def batch_rows(rows: list[dict[str, Any]], pad_token_id: int, device: torch.device) -> dict[str, torch.Tensor]:
|
|
@@ -247,10 +261,10 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 247 |
)
|
| 248 |
|
| 249 |
host = config["host"]
|
| 250 |
-
tokenizer =
|
| 251 |
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
|
| 252 |
-
fix_mistral_regex=True,
|
| 253 |
)
|
|
|
|
| 254 |
rows = select_complete_rows(train_path, tokenizer, int(smoke["maximumTokens"]))
|
| 255 |
result["retokenization"] = {
|
| 256 |
"maximumTokens": int(smoke["maximumTokens"]),
|
|
|
|
| 34 |
import torch.nn.functional as F
|
| 35 |
from huggingface_hub import HfApi, hf_hub_download
|
| 36 |
from safetensors.torch import load_file, save_file
|
| 37 |
+
from transformers import AutoModelForCausalLM, PreTrainedTokenizerFast
|
| 38 |
|
| 39 |
HERE = Path(__file__).resolve().parent
|
| 40 |
if str(HERE) not in sys.path:
|
|
|
|
| 84 |
return list(tokenizer(rendered, add_special_tokens=False)["input_ids"])
|
| 85 |
|
| 86 |
|
| 87 |
+
def select_complete_rows(
|
| 88 |
+
path: Path,
|
| 89 |
+
tokenizer: Any,
|
| 90 |
+
maximum_tokens: int,
|
| 91 |
+
rows_per_lane: int = 1,
|
| 92 |
+
) -> list[dict[str, Any]]:
|
| 93 |
+
if rows_per_lane < 1:
|
| 94 |
+
raise ValueError("rows_per_lane must be positive")
|
| 95 |
wanted = ("host_preservation", "verified_expert")
|
| 96 |
+
eligible: dict[str, list[tuple[int, str, dict[str, Any], list[int]]]] = {lane: [] for lane in wanted}
|
| 97 |
for row in iter_jsonl(path):
|
| 98 |
validate_curriculum_row(row, "train")
|
| 99 |
lane = str(row["lane"])
|
|
|
|
| 102 |
ids = render_and_tokenize(tokenizer, row["messages"])
|
| 103 |
if len(ids) > maximum_tokens:
|
| 104 |
continue
|
| 105 |
+
eligible[lane].append((len(ids), str(row["id"]), row, ids))
|
| 106 |
+
missing = sorted(lane for lane in wanted if len(eligible[lane]) < rows_per_lane)
|
|
|
|
|
|
|
| 107 |
if missing:
|
| 108 |
+
raise RuntimeError(
|
| 109 |
+
f"fewer than {rows_per_lane} complete <= {maximum_tokens}-token rows for lanes {missing}"
|
| 110 |
+
)
|
| 111 |
+
selected = []
|
| 112 |
+
for lane in wanted:
|
| 113 |
+
ordered = sorted(eligible[lane], key=lambda item: (item[0], item[1]))
|
| 114 |
+
if rows_per_lane == 1:
|
| 115 |
+
indexes = [0]
|
| 116 |
+
else:
|
| 117 |
+
indexes = [round(index * (len(ordered) - 1) / (rows_per_lane - 1)) for index in range(rows_per_lane)]
|
| 118 |
+
for index in indexes:
|
| 119 |
+
_, _, row, ids = ordered[index]
|
| 120 |
+
selected.append({"id": row["id"], "lane": lane, "inputIds": ids})
|
| 121 |
+
return selected
|
| 122 |
|
| 123 |
|
| 124 |
def batch_rows(rows: list[dict[str, Any]], pad_token_id: int, device: torch.device) -> dict[str, torch.Tensor]:
|
|
|
|
| 261 |
)
|
| 262 |
|
| 263 |
host = config["host"]
|
| 264 |
+
tokenizer = PreTrainedTokenizerFast.from_pretrained(
|
| 265 |
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
|
|
|
|
| 266 |
)
|
| 267 |
+
result["tokenizerLoader"] = "PreTrainedTokenizerFast"
|
| 268 |
rows = select_complete_rows(train_path, tokenizer, int(smoke["maximumTokens"]))
|
| 269 |
result["retokenization"] = {
|
| 270 |
"maximumTokens": int(smoke["maximumTokens"]),
|