PowerMachine commited on
Commit
b4a2ba0
·
verified ·
1 Parent(s): d855e28

Delete scripts/smoke_test.py

Browse files
Files changed (1) hide show
  1. scripts/smoke_test.py +0 -354
scripts/smoke_test.py DELETED
@@ -1,354 +0,0 @@
1
- #!/usr/bin/env python3
2
- """smoke_test.py — Smoke test do pipeline BiGRU_T_version.
3
-
4
- Verifica:
5
- 1. Importação de todos os módulos
6
- 2. Criação do UnifiedModel
7
- 3. Forward pass sem erro
8
- 4. Backward pass sem erro
9
- 5. QuantizedLinear funcionando (W8A8 fake quant)
10
- 6. ModuleSelector produzindo alpha + entropy_reg
11
- 7. apply_gradient_surgery sem erro
12
- 8. MetaConfigurator sem erro
13
- 9. KillSwitch detectando condições de kill
14
- 10. Multimodal encoders importáveis
15
-
16
- NÃO treina — apenas valida que o pipeline está íntegro.
17
- """
18
- from __future__ import annotations
19
-
20
- import os
21
- import sys
22
- from pathlib import Path
23
-
24
- sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
25
-
26
- os.environ.setdefault("OMP_NUM_THREADS", "2")
27
- os.environ.setdefault("MKL_NUM_THREADS", "2")
28
-
29
- import torch
30
- torch.set_num_threads(2)
31
-
32
-
33
- def test_imports():
34
- """Testa importação de todos os módulos."""
35
- print("=== Test 1: Imports ===")
36
- try:
37
- from bigru_t import (
38
- UnifiedModel, UnifiedModelConfig, create_unified_model,
39
- u8cell_T, BiGRU4, TransformerUnit, OrqCell, TrainT, HypT,
40
- ModuleSelector,
41
- QuantizedLinear, quantize_tensor, apply_w8a8,
42
- apply_gradient_surgery, orthogonalize_gradient,
43
- MetaConfigurator,
44
- KillSwitch, KillSwitchState,
45
- BiGRU_T_Trainer, TrainerConfig,
46
- )
47
- print(" OK: all imports successful")
48
- return True
49
- except Exception as e:
50
- print(f" FAIL: {e}")
51
- import traceback; traceback.print_exc()
52
- return False
53
-
54
-
55
- def test_model_forward():
56
- """Testa forward pass do UnifiedModel."""
57
- print("\n=== Test 2: Model forward ===")
58
- try:
59
- from bigru_t import create_unified_model, UnifiedModelConfig
60
- config = UnifiedModelConfig(
61
- vocab_size=1000,
62
- d_model=32,
63
- max_seq_len=16,
64
- pad_token_id=1,
65
- max_modules=2, # pequeno para teste rápido
66
- bigru_hidden=8,
67
- d_transformer=16,
68
- nhead_tu=2,
69
- d_ff_tu=32,
70
- output_dim_u8cell=16,
71
- cache_len=4,
72
- d_cache=32,
73
- nhead_orq=2,
74
- d_ff_orq=64,
75
- trainT_dim=32,
76
- nhead_train=2,
77
- d_ff_train=64,
78
- num_layers_train=1,
79
- hypT_dim=32,
80
- nhead_hyp=2,
81
- d_ff_hyp=64,
82
- num_layers_hyp=1,
83
- )
84
- model, _ = create_unified_model(config)
85
- params = model.count_parameters()
86
- print(f" params: {params['total']:,} ({params['total_M']:.3f}M)")
87
-
88
- # Forward com token IDs
89
- x = torch.randint(0, 1000, (2, 16)) # (batch=2, T=16)
90
- y_hat, delta = model(x, temperature=1.0, use_hypothesis=False)
91
- assert y_hat.shape == (2, 1000), f"y_hat shape {y_hat.shape} != (2, 1000)"
92
- assert delta.shape == (2, 1000), f"delta shape {delta.shape} != (2, 1000)"
93
- print(f" OK: forward y_hat {y_hat.shape}, delta {delta.shape}")
94
-
95
- # Forward com hipótese
96
- y_hat, delta = model(x, temperature=1.0, use_hypothesis=True, stop_grad_hyp=True)
97
- assert y_hat.shape == (2, 1000)
98
- assert delta.shape == (2, 1000)
99
- print(f" OK: forward with hypothesis")
100
-
101
- # Forward com return_aux
102
- y_hat, delta, aux = model(x, temperature=1.0, use_hypothesis=False, return_aux=True)
103
- assert "entropy_reg" in aux
104
- assert "alpha" in aux
105
- assert aux["alpha"].shape == (2,)
106
- print(f" OK: return_aux entropy_reg={aux['entropy_reg'].item():.4f}, alpha={aux['alpha'].tolist()}")
107
-
108
- return True
109
- except Exception as e:
110
- print(f" FAIL: {e}")
111
- import traceback; traceback.print_exc()
112
- return False
113
-
114
-
115
- def test_backward():
116
- """Testa backward pass."""
117
- print("\n=== Test 3: Backward ===")
118
- try:
119
- from bigru_t import create_unified_model, UnifiedModelConfig
120
- import torch.nn.functional as F
121
- config = UnifiedModelConfig(
122
- vocab_size=100, d_model=16, max_seq_len=8, pad_token_id=1,
123
- max_modules=2, bigru_hidden=4, d_transformer=8, nhead_tu=2, d_ff_tu=16,
124
- output_dim_u8cell=8, cache_len=4, d_cache=16, nhead_orq=2, d_ff_orq=32,
125
- trainT_dim=16, nhead_train=2, d_ff_train=32, num_layers_train=1,
126
- hypT_dim=16, nhead_hyp=2, d_ff_hyp=32, num_layers_hyp=1,
127
- )
128
- model, _ = create_unified_model(config)
129
- x = torch.randint(0, 100, (2, 8))
130
- target = torch.randint(0, 100, (2,))
131
- y_hat, _ = model(x, use_hypothesis=False)
132
- loss = F.cross_entropy(y_hat, target)
133
- loss.backward()
134
- # Verifica que gradientes foram computados
135
- n_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0)
136
- n_total = sum(1 for p in model.parameters() if p.requires_grad)
137
- print(f" OK: backward done, loss={loss.item():.4f}, {n_with_grad}/{n_total} params have grad")
138
- return True
139
- except Exception as e:
140
- print(f" FAIL: {e}")
141
- import traceback; traceback.print_exc()
142
- return False
143
-
144
-
145
- def test_quantized_linear():
146
- """Testa QuantizedLinear (Lema 3)."""
147
- print("\n=== Test 4: QuantizedLinear (W8A8) ===")
148
- try:
149
- from bigru_t.quantization.quantized_linear import QuantizedLinear, quantize_tensor
150
- # Test quantize_tensor
151
- x = torch.randn(100)
152
- x_q = quantize_tensor(x, num_bits=8)
153
- err = (x - x_q).abs().max().item()
154
- print(f" quantize_tensor max err: {err:.4f}")
155
-
156
- # Test QuantizedLinear
157
- ql = QuantizedLinear(10, 5)
158
- x = torch.randn(2, 10)
159
- y = ql(x)
160
- assert y.shape == (2, 5)
161
- print(f" OK: QuantizedLinear forward {y.shape}")
162
-
163
- # Backward
164
- y.sum().backward()
165
- assert ql.weight.grad is not None
166
- print(f" OK: QuantizedLinear backward, grad norm {ql.weight.grad.norm().item():.4f}")
167
- return True
168
- except Exception as e:
169
- print(f" FAIL: {e}")
170
- return False
171
-
172
-
173
- def test_gradient_surgery():
174
- """Testa apply_gradient_surgery (Lema 2)."""
175
- print("\n=== Test 5: Gradient surgery ===")
176
- try:
177
- from bigru_t.training.gradient_surgery import orthogonalize_gradient, apply_gradient_surgery
178
- from bigru_t import create_unified_model, UnifiedModelConfig
179
- import torch.nn.functional as F
180
-
181
- # Test orthogonalize_gradient — caso conflitante
182
- g_main = torch.tensor([1.0, 0.0])
183
- g_hyp = torch.tensor([-1.0, 0.0]) # conflitante (dot = -1 < 0)
184
- g_orth = orthogonalize_gradient(g_main, g_hyp)
185
- # Projeção: g_hyp - (dot/norm_sq) * g_main = (-1, 0) - (-1/1) * (1, 0) = (0, 0)
186
- assert torch.allclose(g_orth, torch.zeros(2), atol=1e-6), f"Expected (0,0), got {g_orth}"
187
- print(f" OK: orthogonalize conflitante → {g_orth.tolist()} (should be [0, 0])")
188
-
189
- # Test orthogonalize_gradient — caso alinhado
190
- g_main = torch.tensor([1.0, 0.0])
191
- g_hyp = torch.tensor([0.5, 0.0]) # alinhado (dot = 0.5 > 0)
192
- g_orth = orthogonalize_gradient(g_main, g_hyp)
193
- # Sem projeção: g_hyp permanece
194
- assert torch.allclose(g_orth, g_hyp), f"Expected {g_hyp}, got {g_orth}"
195
- print(f" OK: orthogonalize alinhado → {g_orth.tolist()} (should be [0.5, 0.0])")
196
-
197
- # Test apply_gradient_surgery end-to-end
198
- config = UnifiedModelConfig(
199
- vocab_size=50, d_model=8, max_seq_len=4, pad_token_id=1,
200
- max_modules=2, bigru_hidden=2, d_transformer=4, nhead_tu=2, d_ff_tu=8,
201
- output_dim_u8cell=4, cache_len=2, d_cache=8, nhead_orq=2, d_ff_orq=16,
202
- trainT_dim=8, nhead_train=2, d_ff_train=16, num_layers_train=1,
203
- hypT_dim=8, nhead_hyp=2, d_ff_hyp=16, num_layers_hyp=1,
204
- )
205
- model, _ = create_unified_model(config)
206
- x = torch.randint(0, 50, (2, 4))
207
- target = torch.randint(0, 50, (2,))
208
- y_hat_main, delta = model(x, use_hypothesis=True, stop_grad_hyp=True)
209
- loss_main = F.cross_entropy(y_hat_main, target)
210
- loss_hyp = F.cross_entropy(y_hat_main + delta, target)
211
- apply_gradient_surgery(model, loss_main, loss_hyp)
212
- n_with_grad = sum(1 for p in model.parameters() if p.grad is not None)
213
- print(f" OK: apply_gradient_surgery, {n_with_grad} params have .grad")
214
- return True
215
- except Exception as e:
216
- print(f" FAIL: {e}")
217
- import traceback; traceback.print_exc()
218
- return False
219
-
220
-
221
- def test_meta_configurator():
222
- """Testa MetaConfigurator (Lema 4)."""
223
- print("\n=== Test 6: MetaConfigurator ===")
224
- try:
225
- from bigru_t import create_unified_model, UnifiedModelConfig
226
- from bigru_t.training.meta_configurator import MetaConfigurator
227
-
228
- config = UnifiedModelConfig(
229
- vocab_size=50, d_model=8, max_seq_len=4, pad_token_id=1,
230
- max_modules=2, bigru_hidden=2, d_transformer=4, nhead_tu=2, d_ff_tu=8,
231
- output_dim_u8cell=4, cache_len=2, d_cache=8, nhead_orq=2, d_ff_orq=16,
232
- trainT_dim=8, nhead_train=2, d_ff_train=16, num_layers_train=1,
233
- hypT_dim=8, nhead_hyp=2, d_ff_hyp=16, num_layers_hyp=1,
234
- )
235
- model, _ = create_unified_model(config)
236
- meta = MetaConfigurator(model, meta_lr=0.01, sharpness_lambda=0.01)
237
-
238
- # Initial T and tau
239
- print(f" Initial: T={meta.temperature:.4f}, tau={meta.tau:.4f}")
240
-
241
- # Run one meta step
242
- x = torch.randint(0, 50, (2, 4))
243
- target = torch.randint(0, 50, (2,))
244
- result = meta.forward_with_meta(x, target)
245
- print(f" After 1 step: T={result['T_new']:.4f}, tau={result['tau_new']:.4f}, "
246
- f"loss_val={result['loss_val']:.4f}, sharpness={result['sharpness']:.4f}")
247
-
248
- # Check tau was synced to model
249
- assert model.tau.item() == result["tau_new"], f"model.tau {model.tau.item()} != {result['tau_new']}"
250
- print(f" OK: MetaConfigurator synced model.tau = {model.tau.item():.4f}")
251
- return True
252
- except Exception as e:
253
- print(f" FAIL: {e}")
254
- import traceback; traceback.print_exc()
255
- return False
256
-
257
-
258
- def test_kill_switch():
259
- """Testa KillSwitch."""
260
- print("\n=== Test 7: KillSwitch ===")
261
- try:
262
- from bigru_t.training.kill_switch import KillSwitch
263
- ks = KillSwitch(loss_patience=3, ram_threshold_pct=99.9, disk_min_free_gb=0.001)
264
-
265
- # Simula 5 steps com loss não decrescente
266
- for i in range(5):
267
- state = ks.check(i, loss=10.0, active_modules=2)
268
- assert state.reason is not None, "Expected kill after patience exhausted"
269
- print(f" OK: kill triggered after {state.step} steps: {state.reason}")
270
-
271
- # Resumo
272
- summary = ks.summary()
273
- print(f" OK: summary keys: {list(summary.keys())}")
274
- return True
275
- except Exception as e:
276
- print(f" FAIL: {e}")
277
- return False
278
-
279
-
280
- def test_multimodal_imports():
281
- """Testa importação dos encoders multimodais (reaproveitados)."""
282
- print("\n=== Test 8: Multimodal imports ===")
283
- try:
284
- # Não importa os módulos diretamente (podem ter dependências pesadas)
285
- # Apenas verifica que os arquivos existem
286
- multimodal_dir = Path(__file__).parent.parent / "src" / "bigru_t" / "multimodal"
287
- expected = ["text_encoder.py", "image_encoder.py", "audio_encoder.py", "video_encoder.py", "modal_router.py", "fusion_layer.py"]
288
- for f in expected:
289
- assert (multimodal_dir / f).exists(), f"Missing {f}"
290
- print(f" OK: {len(expected)} multimodal modules present")
291
- return True
292
- except Exception as e:
293
- print(f" FAIL: {e}")
294
- return False
295
-
296
-
297
- def test_utils_reused():
298
- """Verifica que módulos utilitários reaproveitados estão presentes."""
299
- print("\n=== Test 9: Reused utility modules ===")
300
- try:
301
- utils_dir = Path(__file__).parent.parent / "src" / "bigru_t" / "utils"
302
- expected = ["hardware_detector.py", "xeon_runtime.py", "oom_guard.py", "memory_monitor.py", "tensor_ops.py", "validators.py", "logging_utils.py"]
303
- for f in expected:
304
- assert (utils_dir / f).exists(), f"Missing {f}"
305
- print(f" OK: {len(expected)} utility modules present")
306
-
307
- # Test xeon_runtime import
308
- try:
309
- from bigru_t.utils.xeon_runtime import optimize_xeon_environment
310
- optimize_xeon_environment()
311
- print(f" OK: optimize_xeon_environment() called")
312
- except Exception as e:
313
- print(f" WARN: xeon_runtime optimize failed: {e}")
314
- return True
315
- except Exception as e:
316
- print(f" FAIL: {e}")
317
- return False
318
-
319
-
320
- def main():
321
- print("=" * 60)
322
- print("BiGRU_T_version — Smoke Test")
323
- print("=" * 60)
324
-
325
- tests = [
326
- test_imports,
327
- test_model_forward,
328
- test_backward,
329
- test_quantized_linear,
330
- test_gradient_surgery,
331
- test_meta_configurator,
332
- test_kill_switch,
333
- test_multimodal_imports,
334
- test_utils_reused,
335
- ]
336
- results = []
337
- for t in tests:
338
- try:
339
- r = t()
340
- results.append(r)
341
- except Exception as e:
342
- print(f" CRASH: {e}")
343
- results.append(False)
344
-
345
- print("\n" + "=" * 60)
346
- passed = sum(results)
347
- total = len(results)
348
- print(f"Smoke test: {passed}/{total} passed")
349
- print("=" * 60)
350
- sys.exit(0 if passed == total else 1)
351
-
352
-
353
- if __name__ == "__main__":
354
- main()