File size: 2,104 Bytes
b389bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train an amortized neural quantile network for ALL sliced projections of an
8-mode Gaussian mixture ring in 2D, then save it so gradient_flow.py can reuse
it without retraining.
"""
import os
import sys

_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_ROOT_DIR = os.path.dirname(_THIS_DIR)
_AMORTIZED_DIR = os.path.join(_ROOT_DIR, "Amortized_simulation")
for p in (_ROOT_DIR, _AMORTIZED_DIR):
    if p not in sys.path:
        sys.path.insert(0, p)

import torch
from target import make_ring_mixture
from sw_common import (
    set_seed,
    train_amortized_phi,
    evaluate_and_plot,
    sample_mixture_gaussian,
    mixture_gaussian_true_quantiles,
)

CHECKPOINT_PATH = os.path.join(_THIS_DIR, "checkpoints", "quantile_net_ring8.pt")

set_seed(42)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

n_dim = 2
n_components = 8
embedding_dim = 128
num_cosines = 128

means, covs, weights = make_ring_mixture(n_components=n_components, radius=5.0, std=0.3, device=device)


def sample_fn(n_samples):
    return sample_mixture_gaussian(n_samples, means, covs, weights, n_dim, device)


def true_quantile_fn(test_thetas, taus_test):
    return mixture_gaussian_true_quantiles(test_thetas, taus_test, means, covs, weights)


if __name__ == "__main__":
    model = train_amortized_phi(
        sample_fn,
        d=n_dim,
        device=device,
        n_samples=64,
        L=100,
        epochs=10000,
        lr=1e-4,
        embedding_dim=embedding_dim,
        num_cosines=num_cosines,
        lambda_reg=1e-6,
    )

    evaluate_and_plot(
        model, d=n_dim, device=device,
        true_quantile_fn=true_quantile_fn,
        sample_fn=sample_fn,
        title="Amortized Quantile Function — 8-mode Gaussian Ring",
    )

    os.makedirs(os.path.dirname(CHECKPOINT_PATH), exist_ok=True)
    torch.save({
        "state_dict": model.state_dict(),
        "embedding_dim": embedding_dim,
        "num_cosines": num_cosines,
        "d": n_dim,
    }, CHECKPOINT_PATH)
    print(f"Saved trained quantile network to {CHECKPOINT_PATH}")