Download scripts/nf_roundtrip.py from Lingmin-Ran/SADAE: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_roundtrip.py
- Command line
-
hf download hf://Lingmin-Ran/SADAE/scripts/nf_roundtrip.py
-
curl -L -o nf_roundtrip.py https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_roundtrip.py
12.8 kB
| """Numerical diagnostics for the image STARFlow (no source cache in decoding).""" | |
| import torch | |
| import torch.nn.functional as F | |
| from transformer_flow import IdentityBlock, INV_SOFTPLUS_1, KVCache | |
| def error_metrics(actual, expected): | |
| dtype = torch.float64 if torch.float64 in (actual.dtype, expected.dtype) else torch.float32 | |
| actual, expected = actual.to(dtype), expected.to(dtype) | |
| delta = actual - expected | |
| return { | |
| 'mae': delta.abs().mean().item(), | |
| 'rmse': delta.square().mean().sqrt().item(), | |
| 'max_abs': delta.abs().max().item(), | |
| 'relative_l2': (delta.norm() / expected.norm().clamp_min(1e-12)).item(), | |
| 'finite': bool(torch.isfinite(actual).all()), | |
| } | |
| def sequential_forward(model, latent, condition): | |
| """Encode with the same token/KV-cache path as autoregressive decoding. | |
| Intended for an unwrapped FP32 image model. Each block uses the known input | |
| prefix to predict its affine parameters. Decoding must use fresh caches; | |
| no input prefix or intermediate activation is supplied to the decoder. | |
| This removes the full-sequence versus token-at-a-time kernel discrepancy, | |
| but does not guarantee exact inversion of an ill-conditioned flow. | |
| """ | |
| if latent.ndim != 4 or model.temporal_causal or model.shallow_block_local: | |
| raise ValueError('sequential_forward supports image flows only') | |
| if latent.dtype != torch.float32 or next(model.parameters()).dtype != torch.float32: | |
| raise ValueError('sequential_forward requires FP32 inputs and weights') | |
| x = model.patchify(latent) | |
| outputs, logdets = [x], [] | |
| for index, block in enumerate(model.blocks): | |
| if isinstance(block, IdentityBlock): | |
| outputs.append(x) | |
| logdets.append(torch.zeros_like(x)) | |
| continue | |
| rope = model.feat_rope_gen if index == len(model.blocks) - 1 else model.feat_rope | |
| freqs = block.get_freqs_cis(x, condition, rope) if rope is not None else None | |
| cache = KVCache() | |
| if freqs is None: | |
| raise ValueError('This diagnostic requires the RoPE image configuration') | |
| block.initialize_kv_cache(cache, x, freqs) | |
| target = block.permutation(x) | |
| position = block.permutation(block.pos_embed, dim=0) if block.pos_embed is not None else None | |
| try: | |
| if block.txt_dim > 0: | |
| block.reverse_step_condition(condition, cache, position, freqs_cis=freqs) | |
| z = target.clone() | |
| logdet = torch.zeros_like(target) | |
| steps = target.size(1) if block.use_sos else target.size(1) - 1 | |
| for t in range(steps): | |
| raw_scale, shift = block.reverse_step(target, t, cache, position, condition, freqs_cis=freqs) | |
| scale = F.softplus(raw_scale.float() + INV_SOFTPLUS_1) if block.use_softplus else raw_scale.float().exp() | |
| slot = t if block.use_sos else t + 1 | |
| z[:, slot:slot + 1] = (target[:, slot:slot + 1] - shift.float()) / scale | |
| logdet[:, slot:slot + 1] = -scale.log() | |
| x = block.permutation(z, inverse=True) | |
| outputs.append(x) | |
| logdets.append(logdet) | |
| finally: | |
| cache.delete() | |
| return model.unpatchify(x), None, outputs, logdets | |
| def _check_closed_loop_model(model): | |
| if not model.use_rope or not model.cond_top_only or model.temporal_causal or model.shallow_block_local: | |
| raise ValueError('Closed-loop reconstruction requires an image RoPE model with cond_top_only') | |
| if next(model.parameters()).dtype != torch.float32: | |
| raise ValueError('Closed-loop reconstruction requires FP32 model weights') | |
| def _closed_loop_block(block, value, condition, rope, guidance, reverse=False): | |
| batch_size = value.size(0) | |
| network_value = value.float() | |
| if guidance > 0: | |
| network_value = torch.cat([network_value, network_value]) | |
| freqs = block.get_freqs_cis(network_value, condition, rope) | |
| cache = KVCache() | |
| block.initialize_kv_cache(cache, network_value, freqs) | |
| tokens = block.permutation(value).double() | |
| output = torch.empty_like(tokens) | |
| prefix = torch.zeros_like(tokens, dtype=torch.float32) | |
| if guidance > 0: | |
| prefix = torch.cat([prefix, prefix]) | |
| try: | |
| if block.txt_dim > 0: | |
| block.reverse_step_condition(condition, cache, freqs_cis=freqs) | |
| if not block.use_sos: | |
| output[:, :1] = tokens[:, :1] | |
| first = tokens[:, :1].float() | |
| prefix[:, :1] = torch.cat([first, first]) if guidance > 0 else first | |
| steps = tokens.size(1) if block.use_sos else tokens.size(1) - 1 | |
| for t in range(steps): | |
| raw_scale, mean = block.reverse_step(prefix, t, cache, freqs_cis=freqs) | |
| raw_scale, mean = raw_scale.double(), mean.double() | |
| scale = F.softplus(raw_scale + INV_SOFTPLUS_1) if block.use_softplus else raw_scale.exp() | |
| if guidance > 0: | |
| mean, scale = block.guidance(scale, mean, guidance) | |
| mean, scale = mean[:batch_size], scale[:batch_size] | |
| slot = t if block.use_sos else t + 1 | |
| token = tokens[:, slot:slot + 1] | |
| if reverse: | |
| reconstructed = token * scale + mean | |
| output[:, slot:slot + 1] = reconstructed | |
| else: | |
| noise = (token - mean) / scale | |
| reconstructed = noise * scale + mean | |
| output[:, slot:slot + 1] = noise | |
| # Both CFG branches consume the prefix produced by the same FP64 affine update. | |
| reconstructed = reconstructed.float() | |
| prefix[:, slot:slot + 1] = (torch.cat([reconstructed, reconstructed]) | |
| if guidance > 0 else reconstructed) | |
| return (block.permutation(output, inverse=True), | |
| block.permutation(prefix[:batch_size], inverse=True)) | |
| finally: | |
| cache.delete() | |
| def closed_loop_forward(model, latent, condition, guidance): | |
| """Encode the deep block with decoder feedback and FP64 affine arithmetic.""" | |
| _check_closed_loop_model(model) | |
| if latent.ndim != 4 or latent.dtype != torch.float32: | |
| raise ValueError('Closed-loop encoding requires FP32 image latents') | |
| x = model.patchify(latent) | |
| states = [x] | |
| source_condition = condition[:latent.size(0)] | |
| for block in model.blocks[:-1]: | |
| x, _, _ = block(x, source_condition, model.feat_rope) | |
| states.append(x) | |
| z, simulated_top = _closed_loop_block(model.blocks[-1], x, condition, model.feat_rope_gen, guidance) | |
| states.append(z) | |
| return model.unpatchify(z), states, model.unpatchify(simulated_top) | |
| def closed_loop_reverse(model, z, condition, guidance, return_sequence=False): | |
| """Decode from FP64 z alone, using fresh caches and an FP32 network prefix.""" | |
| _check_closed_loop_model(model) | |
| if z.dtype != torch.float64: | |
| raise ValueError('Closed-loop decoding requires the original FP64 z') | |
| top, _ = _closed_loop_block(model.blocks[-1], model.patchify(z), condition, | |
| model.feat_rope_gen, guidance, reverse=True) | |
| top = model.unpatchify(top) | |
| sequence = [z, top] | |
| caches = [KVCache() for _ in model.blocks] | |
| result = model.reverse_shallow(top.float(), condition[:z.size(0)], guidance=0, | |
| kv_caches=caches, seq=sequence) | |
| return sequence if return_sequence else result | |
| def block_diagnostics(model, forward_states, logdets, reverse_states, item): | |
| """Errors after each reverse block against its matching forward input.""" | |
| rows = [] | |
| count = len(model.blocks) | |
| for reverse_index in range(count): | |
| block_index = count - 1 - reverse_index | |
| expected = model.unpatchify(forward_states[block_index])[item] | |
| actual = reverse_states[reverse_index + 1][item] | |
| # logdet = -log(scale); these are teacher-forced forward scales. | |
| scale = (-logdets[block_index][item].float()).exp() | |
| rows.append({ | |
| 'block_index': block_index, | |
| 'cumulative_reverse_error': error_metrics(actual, expected), | |
| 'forward_scale_min': scale.min().item(), | |
| 'forward_scale_max': scale.max().item(), | |
| 'forward_state_dtype': str(forward_states[block_index + 1].dtype), | |
| 'reverse_state_dtype': str(actual.dtype), | |
| }) | |
| return rows | |
| def cfg_diagnostics(model, top_input, z, condition, guidance, recovered_top): | |
| """Compare deep-block affine predictions at identical teacher-forced prefixes.""" | |
| block = model.blocks[-1] | |
| batch_size = z.size(0) | |
| raw_projection = [] | |
| hook = block.proj_out.register_forward_hook( | |
| lambda module, inputs, output: raw_projection.append(output.detach())) | |
| try: | |
| replay_z, _, _ = block(top_input, condition, model.feat_rope_gen, guidance=guidance) | |
| finally: | |
| hook.remove() | |
| raw = raw_projection[0] | |
| if block.soft_clip > 0: | |
| raw = block.soft_clip * torch.tanh(raw / block.soft_clip) | |
| if not block.use_sos: | |
| raw = torch.cat([torch.zeros_like(raw[:, :1]), raw[:, :-1]], dim=1) | |
| scale, mu = raw.float().chunk(2, dim=-1) | |
| sigma = F.softplus(scale + INV_SOFTPLUS_1) if block.use_softplus else scale.exp() | |
| if guidance > 0: | |
| mu, sigma = block.guidance(sigma, mu, guidance) | |
| freqs = block.get_freqs_cis(top_input, condition, model.feat_rope_gen) | |
| cache = KVCache() | |
| block.initialize_kv_cache(cache, top_input, freqs) | |
| target = block.permutation(top_input) | |
| position = block.permutation(block.pos_embed, dim=0) if block.pos_embed is not None else None | |
| cached_mu, cached_sigma = mu.clone(), sigma.clone() | |
| try: | |
| if block.txt_dim > 0: | |
| block.reverse_step_condition(condition, cache, position, freqs_cis=freqs) | |
| steps = target.size(1) if block.use_sos else target.size(1) - 1 | |
| for t in range(steps): | |
| raw_scale, shift = block.reverse_step(target, t, cache, position, condition, freqs_cis=freqs) | |
| scale = F.softplus(raw_scale.float() + INV_SOFTPLUS_1) if block.use_softplus else raw_scale.float().exp() | |
| scale, shift = scale.squeeze(1), shift.float().squeeze(1) | |
| if guidance > 0: | |
| shift, scale = block.guidance(scale, shift, guidance) | |
| slot = t if block.use_sos else t + 1 | |
| cached_mu[:, slot], cached_sigma[:, slot] = shift, scale | |
| finally: | |
| cache.delete() | |
| paired_z = torch.cat([z, z]) if guidance > 0 else z | |
| noise = block.permutation(model.patchify(paired_z)) | |
| local_reconstruction = (noise * cached_sigma + cached_mu)[:batch_size] | |
| free_reconstruction = block.permutation(model.patchify(recovered_top)) | |
| target = target[:batch_size] | |
| mu, sigma = mu[:batch_size], sigma[:batch_size] | |
| cached_mu, cached_sigma = cached_mu[:batch_size], cached_sigma[:batch_size] | |
| # Reduce on-device, then transfer once rather than synchronize for every token. | |
| token_errors = torch.stack([ | |
| (cached_mu - mu).abs().mean(-1), | |
| (cached_mu - mu).abs().amax(-1), | |
| (cached_sigma - sigma).abs().mean(-1), | |
| (cached_sigma - sigma).abs().amax(-1), | |
| (local_reconstruction - target).abs().mean(-1), | |
| (free_reconstruction - target).abs().mean(-1), | |
| (free_reconstruction - target).abs().amax(-1), | |
| ], dim=-1).cpu().tolist() | |
| names = ('mu_mae', 'mu_max_abs', 'sigma_mae', 'sigma_max_abs', | |
| 'teacher_forced_reconstruction_mae', 'free_reconstruction_mae', 'free_reconstruction_max_abs') | |
| expected_z = model.patchify(z) | |
| reports = [] | |
| for index in range(batch_size): | |
| tokens = [dict(token_index=t, **dict(zip(names, errors))) | |
| for t, errors in enumerate(token_errors[index])] | |
| reports.append({ | |
| 'block_index': len(model.blocks) - 1, | |
| 'guidance': guidance, | |
| 'token_index_base': 0, | |
| 'token_order': 'deep_block_permutation', | |
| 'parallel_replay_z_error': error_metrics(replay_z[index], expected_z[index]), | |
| 'teacher_forced_mu_error': error_metrics(cached_mu[index], mu[index]), | |
| 'teacher_forced_sigma_error': error_metrics(cached_sigma[index], sigma[index]), | |
| 'teacher_forced_reconstruction_error': error_metrics(local_reconstruction[index], target[index]), | |
| 'free_reconstruction_error': error_metrics(free_reconstruction[index], target[index]), | |
| 'free_error_threshold': 1e-3, | |
| 'first_free_token_above_threshold': next( | |
| (row['token_index'] for row in tokens if row['free_reconstruction_mae'] > 1e-3), None), | |
| 'tokens': tokens, | |
| }) | |
| return reports | |