File size: 18,872 Bytes
2cf4a54 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | #!/usr/bin/env python3
"""CPU checks for exact NF density gradients and the editing solver."""
from contextlib import nullcontext, redirect_stdout
from dataclasses import replace
import io
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import torch
import nf_likelihood_ratio_editing as editing
class TriangularFlow(torch.nn.Module):
def forward(self, u, condition):
scale, mean, slope = condition.unbind(1)
x, y = u.unbind(1)
z = torch.stack((x * (-scale).exp(), (y - mean) * (-slope * x).exp()), 1)
return z, None, [], [-scale[:, None], (-slope * x)[:, None]]
class ShiftFlow(torch.nn.Module):
def forward(self, u, condition):
shift = condition.reshape(-1, *([1] * (u.ndim - 1)))
return u - shift, None, [], [torch.zeros_like(u)]
class EditingTests(unittest.TestCase):
def setUp(self):
self.source = torch.tensor([[0.0]])
self.target = torch.tensor([[1.0]])
self.config = editing.SolverConfig(kappa=1, penalty_weight=1, max_steps=10,
step_size=0.5, loss_tol=0, grad_tol=1e-6)
def test_density_and_nonconstant_logdet_gradient(self):
model = TriangularFlow().eval().requires_grad_(False)
u = torch.tensor([[0.4, -0.3]])
cs = torch.tensor([[0.2, -0.1, 0.3]])
ct = torch.tensor([[-0.1, 0.8, -0.4]])
expected_gradients = []
for condition in (cs, ct):
scale, mean, slope = condition[0].tolist()
x, y = u[0].tolist()
expected = (torch.distributions.Normal(0, math.exp(scale)).log_prob(u[0, 0]) +
torch.distributions.Normal(mean, math.exp(slope * x)).log_prob(u[0, 1]))
actual = editing.conditional_density(model, u, condition)[0, 0]
self.assertAlmostEqual(actual.item(), expected.item(), places=6)
expected_gradients.append(torch.tensor([[
-x * math.exp(-2 * scale) + slope * (y - mean) ** 2 * math.exp(-2 * slope * x) - slope,
-(y - mean) * math.exp(-2 * slope * x),
]]))
for checkpointing in (False, True):
gradients = editing.density_gradients(model, u, cs, ct, checkpointing)
for actual, expected in zip(gradients, expected_gradients):
torch.testing.assert_close(actual, expected)
def test_joint_penalty_first_update_and_fixed_target_reference(self):
config = replace(self.config, target_gain=0.25, target_penalty_weight=2,
step_size=0.1, max_steps=1)
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
# At the source, g_R = g_t = 1: eta * (lambda_R*kappa_R + lambda_T*kappa_T).
torch.testing.assert_close(u, torch.tensor([[0.15]]))
self.assertAlmostEqual(result['initial']['loss'], 0.5 + 0.25 ** 2)
self.assertAlmostEqual(result['final']['delta_target_log_density'], 0.13875, places=6)
self.assertAlmostEqual(result['final']['target_violation'], 0.25 - 0.13875, places=6)
for state in trace:
self.assertAlmostEqual(state['delta_target_log_density'],
state['target_log_density'] - result['initial']['target_log_density'])
def test_ratio_feasible_is_not_jointly_feasible(self):
config = replace(self.config, target_gain=0.6, target_penalty_weight=1e-6,
penalty_weight=9, step_size=1, max_steps=1)
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
self.assertTrue(result['ratio_constraint_satisfied'])
self.assertFalse(result['target_constraint_satisfied'])
self.assertFalse(result['constraint_satisfied'])
self.assertFalse(result['strict_constraint_satisfied'])
self.assertEqual(result['selection'], 'lowest_loss_infeasible')
self.assertGreater(result['final']['target_violation'], 0.1)
def test_nearest_jointly_feasible_candidate_is_selected(self):
config = replace(self.config, kappa=0.1, target_gain=0.4, penalty_weight=9,
target_penalty_weight=9, step_size=1, max_steps=3)
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
self.assertTrue(trace[-1]['ratio_feasible'])
self.assertFalse(trace[-1]['target_feasible'])
self.assertTrue(result['constraint_satisfied'])
self.assertEqual(result['selected_step'], 2)
torch.testing.assert_close(u, torch.tensor([[0.5625]]))
self.assertEqual(result['final']['cost'], min(state['cost'] for state in trace if state['feasible']))
def test_target_floor_rejects_loss_decreasing_anti_target_steps(self):
source_latent = torch.tensor([[2.0]])
config = replace(self.config, max_steps=1, max_backtracks=4, target_tol=0)
_, original, _ = editing.optimize_latent(ShiftFlow(), source_latent, self.source,
self.target, config, verbose=False)
self.assertLess(original['final']['delta_target_log_density'], 0)
u, protected, trace = editing.optimize_latent(
ShiftFlow(), source_latent, self.source, self.target,
replace(config, target_gain=0), verbose=False)
torch.testing.assert_close(u, source_latent)
self.assertEqual(protected['stop_reason'], 'target_floor_blocked')
self.assertEqual(protected['line_search_rejections']['target_floor'], 5)
self.assertEqual(protected['line_search_rejections']['armijo'], 0)
self.assertLess(trace[0]['target_directional_derivative'], 0)
self.assertEqual(len(trace), 1)
def test_rms_step_limit_uses_all_latent_dimensions(self):
source_latent = torch.zeros(1, 4)
config = replace(self.config, max_steps=4, step_size=1, max_step_rms=0.05)
u, result, trace = editing.optimize_latent(ShiftFlow(), source_latent, self.source,
self.target, config, verbose=False)
self.assertAlmostEqual(trace[1]['step_size'], 0.05)
self.assertTrue(trace[1]['step_limited'])
for state in trace[1:]:
self.assertLessEqual(state['step_rms'], config.max_step_rms * (1 + 1e-6))
self.assertAlmostEqual(result['final']['cost'], 0.5 * u.double().square().sum().item())
def test_zero_ratio_gain_still_optimizes_positive_target_gain(self):
config = replace(self.config, kappa=0, target_gain=0.25, target_penalty_weight=2,
max_steps=1, step_size=0.1)
u, result, _ = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
torch.testing.assert_close(u, torch.tensor([[0.05]]))
self.assertEqual(result['accepted_steps'], 1)
self.assertTrue(result['ratio_constraint_satisfied'])
self.assertFalse(result['target_constraint_satisfied'])
def test_finite_penalty_returns_analytic_infeasible_minimum(self):
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, self.config, verbose=False)
torch.testing.assert_close(u, torch.tensor([[0.5]]))
self.assertFalse(result['constraint_satisfied'])
self.assertAlmostEqual(result['final']['violation'], 0.5)
self.assertEqual(result['stop_reason'], 'gradient_tolerance')
self.assertEqual(len(trace), 2)
def test_backtracking_and_nearest_feasible_selection(self):
config = replace(self.config, penalty_weight=9, step_size=1, max_steps=8)
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
self.assertTrue(result['constraint_satisfied'])
self.assertGreater(trace[1]['backtracks'], 0)
feasible = [state for state in trace if state['feasible']]
self.assertEqual(result['final']['cost'], min(state['cost'] for state in feasible))
self.assertLess(result['selected_step'], result['accepted_steps'])
self.assertAlmostEqual(u.item(), 1.125)
for previous, accepted in zip(trace, trace[1:]):
bound = previous['loss'] - config.armijo * accepted['step_size'] * previous['gradient_norm'] ** 2
self.assertLessEqual(accepted['loss'], bound)
final = result['final']
self.assertAlmostEqual(final['delta_ratio'],
final['delta_target_log_density'] - final['delta_source_log_density'])
def test_last_accepted_update_is_considered(self):
config = replace(self.config, max_steps=1)
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
self.target, config, verbose=False)
self.assertEqual(result['selected_step'], 1)
self.assertEqual(result['stop_reason'], 'max_steps')
self.assertEqual(len(trace), 2)
self.assertAlmostEqual(u.item(), 0.5)
def test_failure_and_identity_cases(self):
cases = [
(replace(self.config, penalty_weight=9, step_size=1, max_backtracks=0), False,
self.target, 'line_search_failed'),
(self.config, True, self.source, 'same_condition_infeasible'),
(replace(self.config, kappa=0), True, self.source, 'same_condition_no_edit'),
]
for config, same, target, reason in cases:
with self.subTest(reason=reason):
u, result, trace = editing.optimize_latent(ShiftFlow(), self.source, self.source,
target, config, same, verbose=False)
torch.testing.assert_close(u, self.source)
self.assertEqual(result['stop_reason'], reason)
self.assertEqual(len(trace), 1)
def test_nonfinite_trial_preserves_last_valid_candidate(self):
class LimitedFlow(ShiftFlow):
def forward(self, u, condition):
z, y, states, logdets = super().forward(u, condition)
return torch.where(u > 2, torch.full_like(z, float('nan')), z), y, states, logdets
config = replace(self.config, penalty_weight=9, step_size=1)
u, result, trace = editing.optimize_latent(LimitedFlow(), self.source, self.source,
self.target, config, verbose=False)
torch.testing.assert_close(u, self.source)
self.assertEqual(result['stop_reason'], 'nonfinite_trial')
json.dumps(result, allow_nan=False)
def test_starflow_density_matches_explicit_jacobian(self):
from transformer_flow import Model
torch.manual_seed(7)
model = Model(in_channels=1, img_size=2, patch_size=1, channels=32,
num_blocks=2, layers_per_block=[1, 1], head_dim=32, rope=True,
sos=True, txt_size=2, txt_dim=3, cond_top_only=True, use_softplus=True)
with torch.no_grad():
for block in model.blocks:
block.proj_out.weight.normal_(std=0.1)
model.eval().requires_grad_(False)
u = torch.randn(1, 1, 2, 2)
cs, ct = torch.randn(1, 2, 3), torch.randn(1, 2, 3)
density = editing.conditional_density(model, u, ct)[0]
jacobian = torch.autograd.functional.jacobian(
lambda flat: model(flat.reshape_as(u), ct)[0].flatten(), u.flatten())
_, logdet = torch.linalg.slogdet(jacobian.double())
torch.testing.assert_close(density[2], logdet, rtol=1e-5, atol=1e-6)
source_grad, target_grad = editing.density_gradients(model, u, cs, ct, False)
checkpointed = editing.density_gradients(model, u, cs, ct, True)
torch.testing.assert_close(source_grad, checkpointed[0])
torch.testing.assert_close(target_grad, checkpointed[1])
reference = target_grad - source_grad
self.assertGreater(reference.norm().item(), 0)
direction = torch.randn_like(u)
epsilon = 1e-3
ratios = []
for point in (u - epsilon * direction, u + epsilon * direction):
ratios.append((editing.conditional_density(model, point, ct)[0, 0] -
editing.conditional_density(model, point, cs)[0, 0]).item())
derivative = (ratios[1] - ratios[0]) / (2 * epsilon)
self.assertAlmostEqual((reference * direction).sum().item(), derivative, delta=5e-4)
self.assertTrue(all(parameter.grad is None for parameter in model.parameters()))
def test_single_image_pipeline_and_outputs(self):
from PIL import Image
class FakeVAE(torch.nn.Module):
def __init__(self):
super().__init__()
self.scaling_factor = 1
self.downsample_factor = 1
self.vae = SimpleNamespace(encode=lambda image: SimpleNamespace(
latent_dist=SimpleNamespace(mode=lambda: image)))
def decode(self, latent):
return latent
components = (SimpleNamespace(img_size=2, txt_size=4), ShiftFlow(), FakeVAE(), None,
torch.nn.Identity(), SimpleNamespace(distributed=False), torch.device('cpu'))
mocks = {
'pie_bench_nf_components': SimpleNamespace(load_components=lambda cli: components),
'utils': SimpleNamespace(encode_text=lambda *args: torch.tensor([[0.0], [1.0]])),
}
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
image_path = root / 'input.v1.png'
Image.new('RGB', (4, 3), (128, 100, 80)).save(image_path)
output = root / 'output'
argv = ['editing', '--image-path', str(image_path), '--source-prompt', 'source',
'--target-prompt', 'target', '--output-dir', str(output),
'--kappa', '1', '--max-steps', '1', '--step-size', '0.01',
'--target-gain', '0.01', '--target-penalty-weight', '2', '--max-step-rms', '0.005']
with patch.dict(sys.modules, mocks), patch.object(sys, 'argv', argv), \
patch.object(torch.cuda, 'is_available', return_value=True), \
patch.object(torch.cuda, 'get_device_name', return_value='CPU test'), \
patch.object(torch, 'autocast', side_effect=lambda *a, **k: nullcontext()), \
redirect_stdout(io.StringIO()):
editing.main()
with self.assertRaises(FileExistsError):
editing.main()
metadata = json.loads((output / 'metadata/single/input.v1.json').read_text())
self.assertEqual(metadata['selected_step'], 1)
self.assertTrue(metadata['target_constraint_enabled'])
self.assertTrue(metadata['target_constraint_satisfied'])
self.assertFalse(metadata['constraint_satisfied'])
self.assertTrue((output / 'editing/single/input.v1.png').is_file())
with Image.open(output / 'editing/single/input.v1.png') as edited_image:
self.assertEqual(edited_image.size, (2, 2))
latents = torch.load(output / 'latents/single/input.v1.pt', weights_only=True)
self.assertEqual(latents['edited_latent'].dtype, torch.float32)
self.assertEqual(len((output / 'trajectory/single/input.v1.jsonl').read_text().splitlines()), 2)
summary = json.loads((output / 'summary.json').read_text())
self.assertEqual(summary['count'], 1)
self.assertEqual(summary['target_feasible_count'], 1)
self.assertEqual(summary['feasible_count'], 0)
self.assertGreater(summary['mean_delta_target_log_density'], 0)
def test_experiment_runner_dispatch_and_existing_output_protection(self):
runner = Path(editing.ROOT) / 'scripts/run_nf_likelihood_ratio_target_density.sh'
script = runner.read_text().replace(
'source /mnt/bn/jiangzhongtao/miniconda3/etc/profile.d/conda.sh', ':').replace(
'conda activate pvd', ':')
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
binary_dir = root / 'bin'
binary_dir.mkdir()
fake_python = binary_dir / 'python'
fake_python.write_text(
f'#!{sys.executable}\n'
'import json, os, sys\n'
'with open(os.environ["NF_LR_MOCK_CALLS"], "a") as handle:\n'
' handle.write(json.dumps(sys.argv[1:]) + "\\n")\n')
fake_python.chmod(0o755)
calls_path = root / 'calls.jsonl'
output_root = root / 'experiments'
environment = dict(os.environ, PATH=str(binary_dir) + os.pathsep + os.environ['PATH'],
NF_LR_OUTPUT_ROOT=str(output_root), NF_LR_MOCK_CALLS=str(calls_path))
command = ['bash', '-c', script, str(runner), '--max-steps', '7']
completed = subprocess.run(command, env=environment, capture_output=True, text=True)
self.assertEqual(completed.returncode, 0, completed.stderr)
calls = [json.loads(line) for line in calls_path.read_text().splitlines()]
self.assertEqual(len(calls), 4)
for call, label, target in zip(calls, ('ratio_only', 'target_floor', 'target_gain25', 'target_gain50'),
(None, '0', '25', '50')):
self.assertEqual(call[-2:], ['--output-dir', str(output_root / label)])
self.assertEqual(call[call.index('--max-step-rms') + 1], '0.02')
self.assertEqual(call[call.index('--max-steps', call.index('--max-steps') + 1) + 1], '7')
if target is None:
self.assertNotIn('--target-gain', call)
else:
self.assertEqual(call[call.index('--target-gain') + 1], target)
self.assertTrue((output_root / (label + '.log')).is_file())
repeated = subprocess.run(command, env=environment, capture_output=True, text=True)
self.assertNotEqual(repeated.returncode, 0)
self.assertEqual(len(calls_path.read_text().splitlines()), 4)
if __name__ == '__main__':
torch.set_num_threads(1)
unittest.main()
|