#!/usr/bin/env python3 """CPU regression checks with non-identity random flows, not the 3B checkpoint.""" import copy import json from pathlib import Path import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import torch from transformer_flow import Model from nf_roundtrip import block_diagnostics, cfg_diagnostics, error_metrics, sequential_forward @torch.no_grad() def main(): torch.set_num_threads(2) results = [] for sos, cond_top_only, order in [(True, True, 'L2R'), (False, True, 'R2L'), (True, False, 'R2L')]: torch.manual_seed(42) model = Model(in_channels=4, img_size=4, patch_size=1, channels=64, num_blocks=3, layers_per_block=[1, 1, 2], head_dim=64, rope=True, sos=sos, txt_size=4, txt_dim=16, cond_top_only=cond_top_only, use_softplus=True, use_final_norm=True, soft_clip=4, seq_order=order).eval() # The default projection is zero-initialized, making an identity test # vacuous. Nonzero projections exercise affine scales and dependence. for block in model.blocks: block.proj_out.weight.normal_(std=0.045) block.proj_out.bias.normal_(std=0.05) x, y = torch.randn(2, 4, 4, 4), torch.randn(2, 4, 16) # Use identical BF16-representable VAE/text inputs for every method, # isolating NF error from a difference in input quantization. x, y = x.bfloat16().float(), y.bfloat16().float() z, _, states, logdets = model(x, y) seq = model(z, y, reverse=True, return_sequence=True) cached_z, _, cached_states, cached_ld = sequential_forward(model, x, y) cached_seq = model(cached_z, y, reverse=True, return_sequence=True) torch.testing.assert_close(seq[-1], x, atol=2e-5, rtol=2e-5) torch.testing.assert_close(cached_z, z, atol=2e-5, rtol=2e-5) torch.testing.assert_close(cached_seq[-1], x, atol=2e-5, rtol=2e-5) metrics = block_diagnostics(model, states, logdets, seq, slice(0, 1)) assert [r['block_index'] for r in metrics] == [2, 1, 0] assert max(r['cumulative_reverse_error']['max_abs'] for r in metrics) < 2e-5 block_diagnostics(model, cached_states, cached_ld, cached_seq, slice(1, 2)) for guidance in ((0, 3.6) if cond_top_only else (0,)): condition = torch.cat([y, torch.randn_like(y)]) if guidance else y inputs = torch.cat([x, x]) if guidance else x guided_z, _, guided_states, _ = model(inputs, condition, guidance=guidance) guided_z = guided_z[:len(x)] guided_seq = model(guided_z, condition, reverse=True, guidance=guidance, return_sequence=True) reports = cfg_diagnostics(model, guided_states[-2], guided_z, condition, guidance, guided_seq[1]) json.dumps(reports, allow_nan=False) assert len(reports) == len(x) for report in reports: assert len(report['tokens']) == 16 assert report['first_free_token_above_threshold'] is None for name in ('parallel_replay_z_error', 'teacher_forced_mu_error', 'teacher_forced_sigma_error', 'teacher_forced_reconstruction_error', 'free_reconstruction_error'): assert report[name]['max_abs'] < 2e-5 assert not model.blocks[-1].proj_out._forward_hooks repeated_guided = model(guided_z, condition, reverse=True, guidance=guidance) torch.testing.assert_close(repeated_guided, guided_seq[-1], atol=0, rtol=0) if guidance: perturbed_seq = model(guided_z + 0.1, condition, reverse=True, guidance=guidance, return_sequence=True) perturbed_reports = cfg_diagnostics(model, guided_states[-2], guided_z + 0.1, condition, guidance, perturbed_seq[1]) for report in perturbed_reports: assert report['teacher_forced_mu_error']['max_abs'] < 2e-5 assert report['teacher_forced_sigma_error']['max_abs'] < 2e-5 assert report['teacher_forced_reconstruction_error']['mae'] > 0.01 assert report['first_free_token_above_threshold'] == 0 # Independent repeated decoding must not accidentally reuse a source cache. repeated = model(cached_z, y, reverse=True) torch.testing.assert_close(repeated, cached_seq[-1], atol=0, rtol=0) perturbed = model(cached_z + 0.1, y, reverse=True) assert (perturbed - repeated).abs().mean() > 0.01 low_model = copy.deepcopy(model).bfloat16() with torch.autocast('cpu', dtype=torch.bfloat16): low_z, _, _, _ = low_model(x.bfloat16(), y.bfloat16()) low_x = low_model(low_z, y.bfloat16(), reverse=True) results.append({ 'sos': sos, 'cond_top_only': cond_top_only, 'order': order, 'fp32_parallel': error_metrics(seq[-1], x), 'fp32_sequential': error_metrics(cached_seq[-1], x), 'bf16_unwrapped_cpu': error_metrics(low_x, x), }) print(json.dumps(results, indent=2)) print('PASS: nontrivial roundtrips, sequential encoder, block alignment, cache isolation, CFG diagnostics') if __name__ == '__main__': main()