code stringlengths 17 6.64M |
|---|
def make_dataset(metrics: dict) -> xr.Dataset:
dset = {}
for (key, val) in metrics.items():
if isinstance(val, list):
import torch
if isinstance(val[0], torch.Tensor):
val = grab_tensor(torch.stack(val))
elif isinstance(val, np.ndarray):
... |
def plot_dataset(dataset: xr.Dataset, nchains: Optional[int]=10, logfreq: Optional[int]=None, outdir: Optional[os.PathLike]=None, title: Optional[str]=None, job_type: Optional[str]=None, save_plots: bool=True) -> None:
tstamp = get_timestamp()
outdir = (Path(outdir) if (outdir is not None) else Path(os.getcwd... |
def analyze_dataset(dataset: xr.Dataset, outdir: os.PathLike, save: bool=True, use_hdf5: bool=True, nchains: Optional[int]=None, title: Optional[str]=None, logfreq: Optional[int]=None, job_type: Optional[str]=None, run: Optional[Any]=None, arun: Optional[Any]=None) -> xr.Dataset:
'Save plot and analyze resultant ... |
def save_and_analyze_data(dataset: xr.Dataset, outdir: os.PathLike, nchains: Optional[int]=None, logfreq: Optional[int]=None, run: Optional[Any]=None, arun: Optional[Any]=None, job_type: Optional[str]=None, rank: Optional[int]=None, framework: Optional[str]=None, summaries: Optional[list[str]]=None, tables: Optional[... |
def avg_diff(y: list[float], x: Optional[list[float]]=None, *, drop: Optional[(float | int)]=None) -> float:
if (x is not None):
assert (len(y) == len(x))
if (drop is not None):
if (isinstance(drop, int) and (drop > 1.0)):
n = drop
elif (isinstance(drop, float) and (drop < ... |
def dict_to_list_of_overrides(d: dict):
return [f'{k}={v}' for (k, v) in flatten_dict(d, sep='.').items()]
|
def flatten_dict(d: dict, sep: str='/', pre='') -> dict:
return ({(((pre + sep) + k) if pre else k): v for (kk, vv) in d.items() for (k, v) in flatten_dict(vv, sep, kk).items()} if isinstance(d, dict) else {pre: d})
|
def add_to_outdirs_file(outdir: os.PathLike):
with open(OUTDIRS_FILE, 'a') as f:
f.write((Path(outdir).resolve.as_posix() + '\n'))
|
def get_jobdir(cfg: DictConfig, job_type: str) -> Path:
jobdir = Path(cfg.get('outdir', os.getcwd())).joinpath(job_type)
jobdir.mkdir(exist_ok=True, parents=True)
assert (jobdir is not None)
add_to_outdirs_file(jobdir)
return jobdir
|
def list_to_str(x: list) -> str:
if isinstance(x[0], int):
return '-'.join([str(int(i)) for i in x])
elif isinstance(x[0], float):
return '-'.join([f'{i:2.1f}' for i in x])
else:
return '-'.join([str(i) for i in x])
|
@dataclass
class State():
x: Any
v: Any
beta: Any
|
@dataclass
@rich.repr.auto
class BaseConfig(ABC):
@abstractmethod
def to_str(self) -> str:
pass
def to_json(self) -> str:
return json.dumps(self.__dict__)
def get_config(self) -> dict:
return asdict(self)
def asdict(self) -> dict:
return asdict(self)
def to... |
@dataclass
class Charges():
intQ: Any
sinQ: Any
|
@dataclass
class LatticeMetrics():
plaqs: Any
charges: Charges
p4x4: Any
def asdict(self) -> dict:
return {'plaqs': self.plaqs, 'sinQ': self.charges.sinQ, 'intQ': self.charges.intQ, 'p4x4': self.p4x4}
|
@dataclass
class EnvConfig():
def __post_init__(self):
import socket
dist_env = udist.query_environment()
self.rank = dist_env['rank']
self.local_rank = dist_env['local_rank']
self.world_size = dist_env['world_size']
try:
self.hostname = socket.gethostn... |
@dataclass
class wandbSetup(BaseConfig):
id: Optional[str] = None
group: Optional[str] = None
save_code: Optional[bool] = True
sync_tensorboard: Optional[bool] = True
tags: Optional[Sequence[str]] = None
mode: Optional[str] = 'online'
resume: Optional[str] = 'allow'
entity: Optional[st... |
@dataclass
class wandbConfig(BaseConfig):
setup: wandbSetup
def to_str(self) -> str:
return self.to_json()
|
@dataclass
class NetWeight(BaseConfig):
'Object for selectively scaling different components of learned fns.\n\n Explicitly,\n - s: scales the v (x) scaling function in the v (x) updates\n - t: scales the translation function in the update\n - q: scales the force (v) transformation function in the ... |
@dataclass
class NetWeights(BaseConfig):
'Object for selectively scaling different components of x, v networks.'
x: NetWeight = NetWeight(1.0, 1.0, 1.0)
v: NetWeight = NetWeight(1.0, 1.0, 1.0)
def to_str(self):
return f'nwx-{self.x.to_str()}-nwv-{self.v.to_str()}'
def to_dict(self):
... |
@dataclass
class LearningRateConfig(BaseConfig):
'Learning rate configuration object.'
lr_init: float = 0.001
mode: str = 'auto'
monitor: str = 'loss'
patience: int = 5
cooldown: int = 0
warmup: int = 1000
verbose: bool = True
min_lr: float = 1e-06
factor: float = 0.98
min_... |
@dataclass
class Steps(BaseConfig):
nera: int
nepoch: int
test: int
log: int = 100
print: int = 200
extend_last_era: Optional[int] = None
def __post_init__(self):
if (self.extend_last_era is None):
self.extend_last_era = 1
self.total = (self.nera * self.nepoch)... |
@dataclass
class ConvolutionConfig(BaseConfig):
filters: Optional[Sequence[int]] = None
sizes: Optional[Sequence[int]] = None
pool: Optional[Sequence[int]] = None
def __post_init__(self):
if (self.filters is None):
return
if (self.sizes is None):
logger.warning... |
@dataclass
class NetworkConfig(BaseConfig):
units: Sequence[int]
activation_fn: str
dropout_prob: float
use_batch_norm: bool = True
def to_str(self):
ustr = '-'.join([str(int(i)) for i in self.units])
dstr = f'dp-{self.dropout_prob:2.1f}'
bstr = f'bn-{self.use_batch_norm}'... |
@dataclass
class DynamicsConfig(BaseConfig):
nchains: int
group: str
latvolume: List[int]
nleapfrog: int
eps: float = 0.01
eps_hmc: float = 0.01
use_ncp: bool = True
verbose: bool = True
eps_fixed: bool = False
use_split_xnets: bool = True
use_separate_networks: bool = True... |
@dataclass
class LossConfig(BaseConfig):
use_mixed_loss: bool = False
charge_weight: float = 0.01
rmse_weight: float = 0.0
plaq_weight: float = 0.0
aux_weight: float = 0.0
def to_str(self) -> str:
return '_'.join([f'qw-{self.charge_weight:2.1f}', f'pw-{self.plaq_weight:2.1f}', f'rw-{s... |
@dataclass
class InputSpec(BaseConfig):
xshape: Sequence[int]
xnet: Optional[Dict[(str, (int | Sequence[int]))]] = None
vnet: Optional[Dict[(str, (int | Sequence[int]))]] = None
def to_str(self):
return '-'.join([str(i) for i in self.xshape])
def __post_init__(self):
if (len(self... |
@dataclass
class FlopsProfiler():
enabled: bool = False
profile_step: int = 1
module_depth: int = (- 1)
top_modules: int = 1
detailed: bool = True
output_file: Optional[((os.PathLike | str) | Path)] = None
def __post_init__(self):
pass
|
@dataclass
class OptimizerConfig():
type: str
params: Optional[dict] = field(default_factory=dict)
|
@dataclass
class fp16Config():
enabled: bool
auto_cast: bool = True
fp16_master_weights_and_grads: bool = False
min_loss_scale: float = 0.0
|
@dataclass
class CommsLogger():
enabled: bool
verbose: bool = True
prof_all: bool = True
debug: bool = False
|
@dataclass
class AutoTuning():
enabled: bool
arg_mappings: Optional[dict] = field(default_factory=dict)
|
@dataclass
class ZeroOptimization():
stage: int
|
@dataclass
class ExperimentConfig(BaseConfig):
wandb: Any
steps: Steps
framework: str
loss: LossConfig
network: NetworkConfig
conv: ConvolutionConfig
net_weights: NetWeights
dynamics: DynamicsConfig
learning_rate: LearningRateConfig
annealing_schedule: AnnealingSchedule
gra... |
@dataclass
class AnnealingSchedule(BaseConfig):
beta_init: float
beta_final: Optional[float] = 1.0
dynamic: bool = False
def to_str(self) -> str:
return f'bi-{self.beta_init}_bf-{self.beta_final}'
def __post_init__(self):
if ((self.beta_final is None) or (self.beta_final < self.b... |
@dataclass
class Annealear():
'Dynamically adjust annealing schedule during training.'
schedule: AnnealingSchedule
patience: int
min_delta: Optional[float] = None
def __post_init__(self):
self.wait = 0
self.best = np.Inf
self._current_era = 0
self._current_beta = s... |
def get_config(overrides: Optional[list[str]]=None):
from hydra import initialize_config_dir, compose
from hydra.core.global_hydra import GlobalHydra
GlobalHydra.instance().clear()
overrides = ([] if (overrides is None) else overrides)
with initialize_config_dir(CONF_DIR.absolute().as_posix(), ver... |
def get_experiment(overrides: Optional[list[str]]=None, build_networks: bool=True, keep: Optional[(str | list[str])]=None, skip: Optional[(str | list[str])]=None):
cfg = get_config(overrides)
if (cfg.framework == 'pytorch'):
from l2hmc.experiment.pytorch.experiment import Experiment
return Exp... |
@dataclass
class DiffusionConfig():
'\n Diffusion Config.\n\n Args:\n - `log_likelihood_fn`: Callable[[torch.Tensor], torch.Tensor]:\n - Your log-likelihood function to be sampled. Must be defined in\n terms of a 1D parameter array `x` and a number of dimensions\n ... |
class BaseExperiment(ABC):
'Convenience class for running framework independent experiments.'
def __init__(self, cfg: DictConfig) -> None:
super().__init__()
self._created = get_timestamp('%Y-%m-%d-%H%M%S')
self.cfg = cfg
self.config: ExperimentConfig = instantiate(cfg)
... |
def train_step(x: torch.Tensor, beta: torch.Tensor, trainer: Trainer) -> tuple[(torch.Tensor, dict)]:
(xout, metrics) = trainer.dynamics_engine((x, beta))
mcstates = metrics.pop('mc_states')
loss = trainer.calc_loss(xinit=mcstates.init.x, xprop=mcstates.proposed.x, acc=metrics['acc'])
loss.register_ho... |
def train(nsteps: int, trainer: Trainer, beta: (float | torch.Tensor), nlog: int=1, nprint: int=1, x: Optional[torch.Tensor]=None, grab: Optional[bool]=None) -> tuple[(torch.Tensor, dict)]:
beta = (torch.tensor(beta) if isinstance(beta, float) else beta)
history = {}
if (x is None):
state = exp.tr... |
def evaluate(nsteps: int, exp: Experiment, beta: (float | torch.Tensor), nlog: int=1, nprint: int=1, job_type: str='eval', eps: Optional[float]=None, nleapfrog: Optional[int]=None, x: Optional[torch.Tensor]=None, grab: Optional[bool]=None) -> tuple[(torch.Tensor, BaseHistory)]:
history = BaseHistory()
beta_ =... |
class Experiment(BaseExperiment):
def __init__(self, cfg: DictConfig, build_networks: bool=True, keep: Optional[(str | list[str])]=None, skip: Optional[(str | list[str])]=None) -> None:
super().__init__(cfg=cfg)
if (not isinstance(self.config, ExperimentConfig)):
self.config = instant... |
class Experiment(BaseExperiment):
def __init__(self, cfg: DictConfig, build_networks: bool=True, keep: Optional[(str | Sequence[str])]=None, skip: Optional[(str | Sequence[str])]=None) -> None:
super().__init__(cfg=cfg)
assert isinstance(self.config, (ExperimentConfig, configs.ExperimentConfig))
... |
class Group(ABC):
'Gauge group represented as matrices in the last two dimensions.'
def __init__(self, dim: int, shape: Sequence[int], dtype: Any, name: Optional[str]=None) -> None:
self._dim = dim
self._shape = shape
self._dtype = dtype
if (name is not None):
self... |
class SU3(Group):
def __init__(self) -> None:
super().__init__(dim=4, shape=[3, 3], dtype=torch.complex128, name='SU3')
def update_gauge(self, x: Tensor, p: Tensor) -> Tensor:
return (torch.matrix_exp(p) @ x)
def checkSU(self, x: Tensor) -> tuple[(Tensor, Tensor)]:
return checkS... |
class SUN():
def __init__(self) -> None:
super(SUN, self).__init__()
def exp(self, x: Tensor, u: Tensor) -> Tensor:
return (x @ expm((x.conj().transpose((- 2), (- 1)) @ u)))
def log(self, x: Tensor, y: Tensor) -> Tensor:
(_, n, _) = x.shape
assert (n == 3), 'Operation su... |
class SU3(Group):
def __init__(self):
self._nc = 3
self._free_params = 8
super().__init__(dim=4, shape=[3, 3], dtype=tf.complex128)
def update_gauge(self, x: Tensor, p: Tensor) -> Tensor:
return tf.matmul(tf.linalg.expm(p), x)
def checkSU(self, x: Tensor) -> tuple[(Tenso... |
def conjT(x: TensorLike) -> TensorLike:
return transpose(conj(x), ((- 2), (- 1)))
|
class SUN():
def __init__(self) -> None:
super(SUN, self).__init__()
def exp(self, x: TensorLike, u: TensorLike) -> TensorLike:
return (x @ expm((conjT(x) @ u)))
def log(self, x: TensorLike, y: TensorLike) -> TensorLike:
(_, n, _) = x.shape
assert (n == 3), 'Operation on... |
def norm2(x: Tensor, axis=[(- 2), (- 1)]) -> Tensor:
'No reduction if axis is empty'
n = tf.math.real(tf.math.multiply(tf.math.conj(x), x))
if (len(axis) == 0):
return n
return tf.math.reduce_sum(n, axis=axis)
|
def norm2_new(x: Tensor, axis: Optional[list[int]]=None, exclude: Optional[list[int]]=None) -> Tensor:
'No reduction if axis is empty'
axis = ([(- 2), (- 1)] if (axis is None) else axis)
if (x.dtype in [tf.complex64, tf.complex128]):
x = tf.abs(x)
n = tf.math.square(x)
if (exclude is None)... |
def randTAH3(shape: list[int]):
s2 = 0.7071067811865476
s3 = 0.5773502691896257
r3 = (s2 * tf.random.normal(shape, dtype=TF_FLOAT))
r8 = ((s2 * s3) * tf.random.normal(shape, dtype=TF_FLOAT))
m00 = tf.dtypes.complex(tf.cast(0.0, TF_FLOAT), (r8 + r3))
m11 = tf.dtypes.complex(tf.cast(0.0, TF_FLOA... |
def eigs3(tr, p2, det):
tr3 = ((1.0 / 3.0) * tr)
p23 = ((1.0 / 3.0) * p2)
tr32 = (tr3 * tr3)
q = tf.math.abs((0.5 * (p23 - tr32)))
r = (((0.25 * tr3) * ((5 * tr32) - p2)) - (0.5 * det))
sq = tf.math.sqrt(q)
sq3 = (q * sq)
isq3 = (1.0 / sq3)
maxv = tf.constant(3e+38, shape=isq3.shap... |
def rsqrtPHM3f(tr: Tensor, p2: Tensor, det: Tensor) -> tuple[(Tensor, Tensor, Tensor)]:
(l0, l1, l2) = eigs3(tr, p2, det)
sl0 = tf.math.sqrt(tf.math.abs(l0))
sl1 = tf.math.sqrt(tf.math.abs(l1))
sl2 = tf.math.sqrt(tf.math.abs(l2))
u = ((sl0 + sl1) + sl2)
w = ((sl0 * sl1) * sl2)
d = (((w * (... |
def rsqrtPHM3(x: Tensor) -> Tensor:
tr = tf.math.real(tf.linalg.trace(x))
x2 = tf.linalg.matmul(x, x)
p2 = tf.math.real(tf.linalg.trace(x2))
det = tf.math.real(tf.linalg.det(x))
(c0_, c1_, c2_) = rsqrtPHM3f(tr, p2, det)
c0 = tf.cast(tf.reshape(c0_, (c0_.shape + [1, 1])), x.dtype)
c1 = tf.c... |
def projectU(x: Tensor) -> Tensor:
"x (x'x)^{-1/2}"
t = (tf.linalg.adjoint(x) @ x)
t2 = rsqrtPHM3(t)
return tf.linalg.matmul(x, t2)
|
def projectSU(x: Tensor) -> Tensor:
nc = tf.constant(x.shape[(- 1)], TF_FLOAT)
m = projectU(x)
d = tf.linalg.det(m)
const = (1.0 / (- nc))
at2 = tf.cast(tf.math.atan2(tf.math.imag(d), tf.math.real(d)), TF_FLOAT)
p = (const * at2)
y = tf.math.multiply(m, tf.cast(tf.reshape(tf.complex(tf.mat... |
def projectTAH(x: Tensor) -> Tensor:
'Returns R = 1/2 (X - X†) - 1/(2 N) tr(X - X†)\n R = - T^a tr[T^a (X - X†)]\n = T^a ∂_a (- tr[X + X†])\n '
nc = tf.constant(x.shape[(- 1)], dtype=x.dtype)
r = (0.5 * (x - tf.linalg.adjoint(x)))
d = (tf.linalg.trace(r) / nc)
r -= (tf.reshape(d, (d.sha... |
def checkU(x: Tensor) -> tuple[(Tensor, Tensor)]:
'Returns the average and maximum of the sum of the deviations of X†X'
nc = tf.constant(x.shape[(- 1)], dtype=x.dtype)
d = norm2((tf.linalg.matmul(x, x, adjoint_a=True) - eyeOf(x)))
a = tf.math.reduce_mean(d, axis=range(1, len(d.shape)))
b = tf.math... |
def checkSU(x: Tensor) -> tuple[(Tensor, Tensor)]:
'Returns the average and maximum of the sumf of deviations of:\n - X† X\n - det(x)\n from unitarity\n '
nc = tf.constant(x.shape[(- 1)], dtype=TF_FLOAT)
d = norm2((tf.linalg.matmul(x, x, adjoint_a=True) - eyeOf(x)))
d += norm2(((... |
def su3_to_vec(x: Tensor) -> Tensor:
'Only for x in 3x3 anti-Hermitian.\n\n Return 8 real numbers, X^a T^a = X - 1/3 tr(X)\n\n Convention: tr{T^a T^a} = -1/2\n X^a = - 2 tr[T^a X]\n '
c = (- 2)
x00 = x[(..., 0, 0)]
x01 = x[(..., 0, 1)]
x11 = x[(..., 1, 1)]
x02 = x[(..., 0, 2)]
... |
def vec_to_su3(v: Tensor) -> Tensor:
'\n X = X^a T^a\n tr{X T^b} = X^a tr{T^a T^b} = X^a (-1/2) 𝛅^ab = -1/2 X^b\n X^a = -2 X_{ij} T^a_{ji}\n '
s3 = 0.5773502691896257
c = (- 0.5)
assert (len(v.shape) > 1)
vT = tf.transpose(v)
v0 = vT[0].T
v1 = vT[1].T
v2 = vT[2].T
v3 =... |
def eyeOf(m):
batch_shape = ([1] * (len(m.shape) - 2))
return tf.eye(*m.shape[(- 2):], batch_shape=batch_shape, dtype=m.dtype)
|
def exp(m: Tensor, order: int=12):
eye = eyeOf(m)
x = (eye + (m / tf.constant(order)))
for i in tf.range((order - 1), 0, (- 1)):
x = (eye + (tf.linalg.matmul(m, x) / tf.constant(tf.cast(i, m.dtype))))
return x
|
def su3fabc(v: tf.Tensor) -> Tensor:
'\n returns f^{abc} v[..., c]\n [T^a, T^b] = f^abc T^c\n '
vT = tf.transpose(v)
a01 = ((+ f012) * vT[2])
a01 = ((+ f012) * vT[2])
a02 = ((- f012) * vT[1])
a03 = ((+ f036) * vT[6])
a04 = ((+ f045) * vT[5])
a05 = ((- f045) * vT[4])
a06 = ... |
def su3dabc(v: Tensor) -> Tensor:
'\n returns d^abc v[...,c]\n {T^a,T^b} = -1/3δ^ab + i d^abc T^c\n '
vT = tf.transpose(v)
a00 = (d007 * vT[7])
a03 = (d035 * vT[5])
a04 = (d046 * vT[6])
a05 = (d035 * vT[3])
a06 = (d046 * vT[4])
a07 = (d007 * vT[0])
a11 = (d117 * vT[7])
... |
def SU3Ad(x: Tensor) -> Tensor:
'\n X T^c X† = AdX T^c = T^b AdX^bc\n Input x must be in SU(3) group.\n AdX^bc = - 2 tr[T^b X T^c X†] = - 2 tr[T^c X† T^b X]\n '
y = tf.expand_dims(x, (- 3))
return su3_to_vec(tf.linalg.matmul(y, tf.linalg.matmul(su3gen(), y), adjoint_a=True))
|
def su3ad(x: Tensor) -> Tensor:
'\n adX^{ab} = - f^{abc} X^c = f^{abc} 2 tr(X T^c) = 2 tr(X [T^a, T^b])\n Input x must be in su(3) algebra.\n '
return su3fabc(tf.negative(su3_to_vec(x)))
|
def su3adapply(adx: Tensor, y: Tensor) -> Tensor:
'\n Note:\n adX(Y) = [X, Y]\n adX(T^b) = T^a adX^{ab}\n = - T^a f^{abc} X^c\n = X^c f^{cba} T^a\n = X^c [T^c, T^b]\n = [X, T^b]\n and\n adX(Y) = T^a adX^{ab} Y^b\n ... |
def gellMann() -> Tensor:
s3 = 0.5773502691896257
zero3 = tf.zeros([3, 3], dtype=tf.float64)
return tf.stack([tf.dtypes.complex(tf.reshape(tf.constant([0, 1, 0, 1, 0, 0, 0, 0, 0], dtype=tf.float64), [3, 3]), zero3), tf.dtypes.complex(zero3, tf.reshape(tf.constant([0, (- 1), 0, 1, 0, 0, 0, 0, 0], dtype=tf.... |
def su3gen() -> Tensor:
'\n T[a,i,j] = T^a_ij\n Traceless Anti-Hermitian basis. tr{T^a T^a} = -1/2\n '
global _su3gen_private_global_cache_
if (_su3gen_private_global_cache_ is None):
_su3gen_private_global_cache_ = (tf.dtypes.complex(tf.constant(0, dtype=tf.float64), tf.constant((- 0.5)... |
def diffprojectTAH(m: Tensor, p: Optional[Tensor]=None) -> Tensor:
'\n returns ∂_c p^a = ∂_c projectTAH(m)^a = - tr[T^a (T^c M + M† T^c)]\n P^a = -2 tr[T^a {- T^d tr[T^d (M - M†)]}]\n = - tr[T^a (M - M†)]\n = - ∂_a tr[M + M†]\n ∂_c P^a = - tr[T^a (T^c M + M† T^c)]\n = - 1/2 tr[{T... |
def diffprojectTAHCross(m: Tensor, x: Optional[Tensor]=None, Adx: Optional[Tensor]=None, p: Optional[Tensor]=None) -> Tensor:
'\n returns\n R^ac = ∇_c p^a\n = ∇_c projectTAH(X Y)^a\n = - ∇_c ∂_a tr[X Y + Y† X†],\n where M = X Y\n\n The derivatives ∂ is on X and ∇ is on Y.\n... |
def diffexp(adX: Tensor, order: int=13) -> Tensor:
'\n return\n J(X) = (1-exp{-adX})/adX\n = Σ_{k=0}^{∞} 1/(k+1)! (-adX)^k\n up to k=order\n\n [exp{-X(t)} d/dt exp{X(t)}]_ij\n = [J(X) d/dt X(t)]_ij\n = T^a_ij J(X)^ab (-2) T^b_kl [d/dt X(t)]_lk\n\n J(X) = 1 + 1/2 (-adX)... |
def SU3GradientTF(f: Callable[([Tensor], Tensor)], x: Tensor) -> tuple[(Tensor, Tensor)]:
'Compute gradient using TensorFlow GradientTape.\n\n y = f(x) must be a real scalar value.\n\n Returns:\n - (f(x), D), where D = T^a D^a = T^a ∂_a f(x)\n\n NOTE: Use real vector derivatives, e.g.\n D^a = ∂... |
def SU3GradientTFMat(f: Callable, x: Tensor) -> tuple[(Tensor, Tensor)]:
'\n Compute gradient using TensorFlow GradientTape.\n f(x) must be a real scalar value.\n Returns (f(x),D), where D = T^a D^a = T^a ∂_a f(x)\n Use Matrix derivatives.\n D^a = ∂_a f(x)\n = [∂_a x_ij] [d/dx_ij f(x)]\n ... |
def SU3JacobianTF(f: Callable, x: Tensor, is_SU3: bool=True) -> tuple[(Tensor, Tensor)]:
"\n Compute Jacobian using TensorFlow GradientTape with real vector\n derivatives.\n Note for TensorFlow,\n ∇_z f = (∂_z f + ∂_z f†)†\n\n In order to have the proper gradient info, we always project the res... |
def SU3JacobianTFMat(f, x, is_SU3=True):
"\n Compute Jacobian using TensorFlow GradientTape with matrix derivatives.\n Note for TensorFlow,\n ∇_z f = (∂_z f + ∂_z f†)†\n\n In order to have the proper gradient info,\n we always project the result to su(3).\n\n If is_SU3 is True, we multiply t... |
def rand_unif(shape: Sequence[int], a: float, b: float, requires_grad: bool=True):
'Return tensor x ~ U(a, b), where a <= x <= b with shape `shape`\n\n >>> import numpy as np\n >>> x = rand_unif([1, 2, 3], -1, 1)\n >>> x.shape\n torch.Size([1, 2, 3])\n >>> (-1. <= x.min()).item()\n True\n >>>... |
def random_angle(shape: Sequence[int], requires_grad: bool=True) -> Tensor:
'Returns random angle with `shape` and values in (-pi, pi).\n '
return rand_unif(shape, (- PI), PI, requires_grad=requires_grad)
|
def eyeOf(x: torch.Tensor) -> torch.Tensor:
batch_dims = ([1] * (len(x.shape) - 1))
eye = torch.zeros((batch_dims + [*x.shape[(- 1):]])).to(x.device)
eye[(- 1):] = torch.eye(x.shape[(- 1)])
return eye
|
class U1Phase(Group):
def __init__(self) -> None:
dim = 2
shape = [1]
dtype = PT_FLOAT
super().__init__(dim=dim, shape=shape, dtype=dtype)
def phase_to_coords(self, phi: Tensor) -> Tensor:
'Convert complex to Cartesian.\n\n exp(i φ) --> [cos φ, sin φ]\n\n ... |
class U1Phase(Group):
def __init__(self):
super(U1Phase, self).__init__(dim=2, shape=[1], dtype=TF_FLOAT)
def phase_to_coords(self, phi: Tensor) -> Tensor:
'Convert complex to Cartesian.\n\n exp(i φ) --> [cos φ, sin φ]\n '
coords = [tf.math.cos(phi), tf.math.sin(phi)]
... |
class Lattice(ABC):
def __init__(self, group: Group, nchains: int, shape: list[int]) -> None:
self.g = group
self.link_shape = self.g._shape
self.xshape = [self.g._dim, *shape]
if (len(self.g._shape) > 1):
self.xshape.extend(self.g._shape)
self.dim = self.g._di... |
@dataclass
class Charges():
intQ: Array
sinQ: Array
def asdict(self):
return {'intQ': self.intQ, 'sinQ': self.sinQ}
|
@dataclass
class LatticeMetrics():
plaqs: Array
charges: Charges
p4x4: Array
def asdict(self):
return {'plaqs': self.plaqs, 'p4x4': self.p4x4, 'sinQ': self.charges.sinQ, 'intQ': self.charges.intQ}
|
def area_law(beta: float, nplaqs: int):
return ((i1(beta) / i0(beta)) ** nplaqs)
|
def plaq_exact(beta: float):
return area_law(beta, nplaqs=1)
|
def project_angle(x: Array) -> Array:
return (x - (TWO_PI * np.floor(((x + PI) / TWO_PI))))
|
class BaseLatticeU1():
def __init__(self, nchains: int, shape: tuple[(int, int)]):
self.nchains = nchains
self._dim = 2
assert (len(shape) == 2)
(self.nt, self.nx) = shape
self.xshape = (self._dim, *shape)
self._shape = (nchains, *self.xshape)
self.nplaqs =... |
def rate(step, model_size, factor, warmup):
if (step == 0):
step = 1
return (factor * ((model_size ** (- 0.5)) * min((step ** (- 0.5)), (step * (warmup ** (- 1.5))))))
|
def lr_schedule(model_size, factor, warmup, optimizer) -> LambdaLR:
return LambdaLR(optimizer=optimizer, lr_lambda=(lambda step: rate(step=step, model_size=model_size, factor=factor, warmup=warmup)))
|
class NoamOpt():
'Optim wrapper that implements rate.'
def __init__(self, model_size, warmup, optimizer):
self.optimizer = optimizer
self._step = 0
self.warmup = warmup
self.model_size = model_size
self._rate = 0
def state_dict(self):
'Returns the state of... |
def moving_average(x: np.ndarray, n: int=1000):
out = np.cumsum(x, dtype=np.float32)
out[n:] = (out[n:] - out[:(- n)])
return (out[(n - 1):] / n)
|
class ReduceLROnPlateau(Callback):
"Reduce learning rate when a metric has stopped improving.\n Models often benefit from reducing the learning rate by a factor\n of 2-10 once learning stagnates. This callback monitors a\n quantity and if no improvement is seen for a 'patience' number\n of epochs, the... |
def mixed_loss(loss: float, weight: float) -> float:
return ((weight / loss) - (loss / weight))
|
class BaseLoss():
def __init__(self, config: LossConfig, metrics_fn: Callable, loss_fns: dict[(str, Callable)], loss_weights: Optional[dict[(str, float)]]=None) -> None:
self.config = config
self.loss_fns = loss_fns
self.metrics_fn = metrics_fn
assert callable(self.metrics_fn)
... |
class LatticeLoss():
def __init__(self, lattice: (LatticeU1 | LatticeSU3), loss_config: LossConfig):
self.lattice = lattice
self.config = loss_config
self.xshape = self.lattice.xshape
self.plaq_weight = torch.tensor(self.config.plaq_weight, dtype=torch.float)
self.charge_w... |
class LatticeLoss():
def __init__(self, lattice: (LatticeU1 | LatticeSU3), loss_config: LossConfig):
self.lattice = lattice
self.config = loss_config
self.plaq_weight = tf.constant(self.config.plaq_weight, dtype=TF_FLOAT)
self.charge_weight = tf.constant(self.config.charge_weight,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.