Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
GNOT
GNOT-master/readme.md
# GNOT: General Neural Operator Transformer (ICML 2023) Code for [GNOT: A General Neural Operator Transformer for Operator Learning](https://arxiv.org/abs/2302.14376), accepted at International Conference on Machine Learning (ICML 2023). - GNOT is a flexible Transformer with linear complexity attention for learning operators or parametric PDEs. - GNOT could handle arbituary number of source functions/shapes/parameters. - GNOT achieves the state-of-the-art results (SOTA) among 7 highly challenging datasets chosen from fluids, heat, and electromagnetism. ![fig1](./resources/fig1.png) A pretrained GNOT could serves as the surrogate model for predicting physical fields. The inference speed is much more faster compared with traditional numerical solvers. To enabling training neural operators on realistic FEM/FVM simulation data, we design several components to deal with the three challenges, i.e. irregular mesh, multiple (types of) input functions, and multi-scale objective functions. <p align="center"> <img width="40%" src="https://raw.githubusercontent.com/HaoZhongkai/GNOT/master/resources/fig2.png"/> </p> Experiments of GNOT are conducted on multiple challenging datasets selected from multiple domains to show its capacity for generally solving parametric PDE problems. Here is an overview of these datasets: <p align="center"> <img width="60%" src="https://raw.githubusercontent.com/HaoZhongkai/GNOT/master/resources/fig5.png"/> </p> ### Get Start Add dataset folder if it does not exists, ``mdkir data`` ``cd data`` In this folder, you can build two folders to store training logs and models ``mkdir logs checkpoints`` Then moves datasets in this folder. For your custom datasets, you might need to modify `args` and `data_utils/get_dataset` functions. **Dataset Link** Datasets can be found in these links, - Darcy2d and NS2d-time (from FNO's experiments): [FNO datasets](https://drive.google.com/drive/folders/1UnbQh2WWc6knEHbLn-ZaXrKUZhp7pjt-) - Naca2d and Elas2d (from GeoFNO's experiments): [GeoFNO datasets](https://drive.google.com/drive/folders/1YBuaoTdOSr_qzaow-G-iwvbUI7fiUzu8) - Heat2d, ns2d, Inductor2d, Heatsink3d: [Our GNOT datasets](https://drive.google.com/drive/folders/1kicZyL1t4z6a7B-6DJEOxIrX877gjBC0) **Data Format:** The format of our multi-input-output dataset (MIODataset) should be as follows: ```python Dataset = [ [X1, Y1, Theta1, Inputs_funcs1], [X2, Y2, Theta2, Inputs_funcs2], ... ] ``` - **X**: (N x N_in) numpy array, representing input mesh points - N: number of points - N_in: input spatial dimension - **Y**: (N x N_out) numpy array, representing physical fields defined on these mesh points - N_out: output dimension, N_out must be at least 1, shape (N,) is not allowed - **Theta**: (N_theta,) numpy array, global parameters for this sample - N_theta: dimension of global parameters - **Input_funcs**: `tuple (inputs_1, ..., inputs_n)`,every `inputs_i` is a numary array of shape (N_i, f_i), it can be (None,) : - N_i: number of points used to discretize this input function - f_i: dimension of this input function plus the dimension of geometry, actually it is the concat of (x_i, f(x_i)). - **Note:** - For a single sample, The number of points must match, i.e, ``X.shape[0]=Y.shape[0]``, but it can vary with samples - For global parameters, the dimension must be the same across all samples ### Training To train GNOT model, parameters could be updated using argparser or modifying args.py file ```python python train.py --gpu 0 --dataset ns2d_4ball --use-normalizer unit --normalize_x unit --component all --comment rel2 --loss-name rel2 --epochs 500 --batch-size 4 --model-name CGPT --optimizer AdamW --weight-decay 0.00005 --lr 0.001 --lr-method cycle --grad-clip 1000.0 --n-hidden 128 --n-layers 3 --use-tb 0 ``` ### Results of GNOT Main experimental result for GNOT: ![fig3](./resources/fig3.png) Besides, as a transformer architecture, we verify its scaling properties with more data and larger network capacity. This suggests that it is possible to scaling up the architecture for solving larger problems. ![fig4](./resources/fig4.png) ### Code Structure - ``args.py:`` specify hyperparameters for models - ``train.py:`` main training function - ``data_utils.py:`` includes dataset, loss functions - ``models/`` folder for GNOT ### Citation If you use GNOT in your research, please use the following BibTeX entry. ``` @article{hao2023gnot, title={GNOT: A General Neural Operator Transformer for Operator Learning}, author={Hao, Zhongkai and Ying, Chengyang and Wang, Zhengyi and Su, Hang and Dong, Yinpeng and Liu, Songming and Cheng, Ze and Zhu, Jun and Song, Jian}, journal={arXiv preprint arXiv:2302.14376}, year={2023} } ```
4,815
38.154472
406
md
GNOT
GNOT-master/train.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import sys import os sys.path.append('../..') sys.path.append('..') import re import time import pickle import numpy as np import torch import torch.nn as nn from torch.optim.lr_scheduler import OneCycleLR, StepLR, LambdaLR from torch.utils.tensorboard import SummaryWriter from args import get_args from data_utils import get_dataset, get_model, get_loss_func, collate_op, MIODataLoader from utils import get_seed, get_num_params from models.optimizer import Adam, AdamW ''' A general code framework for training neural operator on irregular domains ''' EPOCH_SCHEDULERS = ['ReduceLROnPlateau', 'StepLR', 'MultiplicativeLR', 'MultiStepLR', 'ExponentialLR', 'LambdaLR'] def train(model, loss_func, metric_func, train_loader, valid_loader, optimizer, lr_scheduler, epochs=10, writer=None, device="cuda", patience=10, grad_clip=0.999, start_epoch: int = 0, print_freq: int = 20, model_save_path='./data/checkpoints/', save_mode='state_dict', # 'state_dict' or 'entire' model_name='model.pt', result_name='result.pt'): loss_train = [] loss_val = [] loss_epoch = [] lr_history = [] it = 0 if patience is None or patience == 0: patience = epochs result = None start_epoch = start_epoch end_epoch = start_epoch + epochs best_val_metric = np.inf best_val_epoch = None save_mode = 'state_dict' if save_mode is None else save_mode stop_counter = 0 is_epoch_scheduler = any(s in str(lr_scheduler.__class__)for s in EPOCH_SCHEDULERS) for epoch in range(start_epoch, end_epoch): model.train() torch.cuda.empty_cache() for batch in train_loader: loss = train_batch(model, loss_func, batch, optimizer, lr_scheduler, device, grad_clip=grad_clip) loss = np.array(loss) loss_epoch.append(loss) it += 1 lr = optimizer.param_groups[0]['lr'] lr_history.append(lr) log = f"epoch: [{epoch+1}/{end_epoch}]" if loss.ndim == 0: # 1 target loss _loss_mean = np.mean(loss_epoch) log += " loss: {:.6f}".format(_loss_mean) else: _loss_mean = np.mean(loss_epoch, axis=0) for j in range(len(_loss_mean)): log += " | loss {}: {:.6f}".format(j, _loss_mean[j]) log += " | current lr: {:.3e}".format(lr) if it % print_freq==0: print(log) if writer is not None: for j in range(len(_loss_mean)): writer.add_scalar("train_loss_{}".format(j),_loss_mean[j], it) #### loss 0 seems to be the sum of all loss loss_train.append(_loss_mean) loss_epoch = [] val_result = validate_epoch(model, metric_func, valid_loader, device) loss_val.append(val_result["metric"]) val_metric = val_result["metric"].sum() if val_metric < best_val_metric: best_val_epoch = epoch best_val_metric = val_metric if lr_scheduler and is_epoch_scheduler: if 'ReduceLROnPlateau' in str(lr_scheduler.__class__): lr_scheduler.step(val_metric) else: lr_scheduler.step() if val_result["metric"].size == 1: log = "| val metric 0: {:.6f} ".format(val_metric) else: log = '' for i, metric_i in enumerate(val_result['metric']): log += '| val metric {} : {:.6f} '.format(i, metric_i) if writer is not None: if val_result["metric"].size == 1: writer.add_scalar('val loss {}'.format(metric_func.component),val_metric, epoch) else: for i, metric_i in enumerate(val_result['metric']): writer.add_scalar('val loss {}'.format(i), metric_i, epoch) log += "| best val: {:.6f} at epoch {} | current lr: {:.3e}".format(best_val_metric, best_val_epoch+1, lr) desc_ep = "" if _loss_mean.ndim == 0: # 1 target loss desc_ep += "| loss: {:.6f}".format(_loss_mean) else: for j in range(len(_loss_mean)): if _loss_mean[j] > 0: desc_ep += "| loss {}: {:.3e}".format(j, _loss_mean[j]) desc_ep += log print(desc_ep) result = dict( best_val_epoch=best_val_epoch, best_val_metric=best_val_metric, loss_train=np.asarray(loss_train), loss_val=np.asarray(loss_val), lr_history=np.asarray(lr_history), # best_model=best_model_state_dict, optimizer_state=optimizer.state_dict() ) pickle.dump(result, open(os.path.join(model_save_path, result_name),'wb')) return result def train_batch(model, loss_func, data, optimizer, lr_scheduler, device, grad_clip=0.999): optimizer.zero_grad() g, u_p, g_u = data g, g_u, u_p = g.to(device), g_u.to(device), u_p.to(device) out = model(g, u_p, g_u) y_pred, y = out.squeeze(), g.ndata['y'].squeeze() loss, reg, _ = loss_func(g, y_pred, y) loss = loss + reg loss.backward() nn.utils.clip_grad_norm_(model.parameters(), grad_clip) optimizer.step() if lr_scheduler: lr_scheduler.step() return (loss.item(), reg.item()) def validate_epoch(model, metric_func, valid_loader, device): model.eval() metric_val = [] for _, data in enumerate(valid_loader): with torch.no_grad(): g, u_p, g_u = data g, g_u, u_p = g.to(device), g_u.to(device), u_p.to(device) out = model(g, u_p, g_u) y_pred, y = out.squeeze(), g.ndata['y'].squeeze() _, _, metric = metric_func(g, y_pred, y) metric_val.append(metric) return dict(metric=np.mean(metric_val, axis=0)) if __name__ == "__main__": args = get_args() if not args.no_cuda and torch.cuda.is_available(): device = torch.device('cuda:{}'.format(str(args.gpu))) else: device = torch.device("cpu") kwargs = {'pin_memory': False} if args.gpu else {} get_seed(args.seed, printout=False) train_dataset, test_dataset = get_dataset(args) # test_dataset = get_dataset(args) train_loader = MIODataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, drop_last=False) test_loader = MIODataLoader(test_dataset, batch_size=args.batch_size, shuffle=True, drop_last=False) args.space_dim = int(re.search(r'\d', args.dataset).group()) args.normalizer = train_dataset.y_normalizer.to(device) if train_dataset.y_normalizer is not None else None #### set random seeds get_seed(args.seed) torch.cuda.empty_cache() loss_func = get_loss_func(name=args.loss_name,args= args, regularizer=True,normalizer=args.normalizer) metric_func = get_loss_func(name='rel2', args=args, regularizer=False, normalizer=args.normalizer) model = get_model(args) model = model.to(device) print(f"\nModel: {model.__name__}\t Number of params: {get_num_params(model)}") path_prefix = args.dataset + '_{}_'.format(args.component) + model.__name__ + args.comment + time.strftime('_%m%d_%H_%M_%S') model_path, result_path = path_prefix + '.pt', path_prefix + '.pkl' print(f"Saving model and result in ./../models/checkpoints/{model_path}\n") if args.use_tb: writer_path = './data/logs/' + path_prefix log_path = writer_path + '/params.txt' writer = SummaryWriter(log_dir=writer_path) fp = open(log_path, "w+") sys.stdout = fp else: writer = None log_path = None print(model) # print(config) epochs = args.epochs lr = args.lr if args.optimizer == 'Adam': optimizer = Adam(model.parameters(), lr=lr, weight_decay=args.weight_decay,betas=(0.9,0.999)) elif args.optimizer == "AdamW": optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=args.weight_decay,betas=(0.9, 0.999)) else: raise NotImplementedError if args.lr_method == 'cycle': print('Using cycle learning rate schedule') scheduler = OneCycleLR(optimizer, max_lr=lr, div_factor=1e4, pct_start=0.2, final_div_factor=1e4, steps_per_epoch=len(train_loader), epochs=epochs) elif args.lr_method == 'step': print('Using step learning rate schedule') scheduler = StepLR(optimizer, step_size=args.lr_step_size*len(train_loader), gamma=0.7) elif args.lr_method == 'warmup': print('Using warmup learning rate schedule') scheduler = LambdaLR(optimizer, lambda steps: min((steps+1)/(args.warmup_epochs * len(train_loader)), np.power(args.warmup_epochs * len(train_loader)/float(steps + 1), 0.5))) time_start = time.time() result = train(model, loss_func, metric_func, train_loader, test_loader, optimizer, scheduler, epochs=epochs, grad_clip=args.grad_clip, patience=None, model_name=model_path, model_save_path='./data/checkpoints/', result_name=result_path, writer=writer, device=device) print('Training takes {} seconds.'.format(time.time() - time_start)) # result['args'], result['config'] = args, config checkpoint = {'args':args, 'model':model.state_dict(),'optimizer':optimizer.state_dict()} torch.save(checkpoint, os.path.join('./data/checkpoints/{}'.format(model_path))) model.eval() val_metric = validate_epoch(model, metric_func, test_loader, device) print(f"\nBest model's validation metric in this run: {val_metric}")
10,040
31.079872
182
py
GNOT
GNOT-master/utils.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import os import torch import numpy as np import operator import matplotlib.pyplot as plt import torch import numpy as np import torch.special as ts from scipy import interpolate from functools import reduce def get_seed(s, printout=True, cudnn=True): # rd.seed(s) os.environ['PYTHONHASHSEED'] = str(s) np.random.seed(s) # pd.core.common.random_state(s) # Torch torch.manual_seed(s) torch.cuda.manual_seed(s) if cudnn: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False if torch.cuda.is_available(): torch.cuda.manual_seed_all(s) message = f''' os.environ['PYTHONHASHSEED'] = str({s}) numpy.random.seed({s}) torch.manual_seed({s}) torch.cuda.manual_seed({s}) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False if torch.cuda.is_available(): torch.cuda.manual_seed_all({s}) ''' if printout: print("\n") print(f"The following code snippets have been run.") print("=" * 50) print(message) print("=" * 50) def get_num_params(model): ''' a single entry in cfloat and cdouble count as two parameters see https://github.com/pytorch/pytorch/issues/57518 ''' # model_parameters = filter(lambda p: p.requires_grad, model.parameters()) # num_params = 0 # for p in model_parameters: # # num_params += np.prod(p.size()+(2,) if p.is_complex() else p.size()) # num_params += p.numel() * (1 + p.is_complex()) # return num_params c = 0 for p in list(model.parameters()): c += reduce(operator.mul, list(p.size() + (2,) if p.is_complex() else p.size())) #### there is complex weight return c ### x: list of tensors class MultipleTensors(): def __init__(self, x): self.x = x def to(self, device): self.x = [x_.to(device) for x_ in self.x] return self def __len__(self): return len(self.x) def __getitem__(self, item): return self.x[item] # whether need to transpose def plot_heatmap( x, y, z, path=None, vmin=None, vmax=None,cmap=None, title="", xlabel="x", ylabel="y",show=False ): ''' Plot heat map for a 3-dimension data ''' plt.cla() # plt.figure() xx = np.linspace(np.min(x), np.max(x)) yy = np.linspace(np.min(y), np.max(y)) xx, yy = np.meshgrid(xx, yy) vals = interpolate.griddata(np.array([x, y]).T, np.array(z), (xx, yy), method='cubic') vals_0 = interpolate.griddata(np.array([x, y]).T, np.array(z), (xx, yy), method='nearest') vals[np.isnan(vals)] = vals_0[np.isnan(vals)] if vmin is not None and vmax is not None: fig = plt.imshow(vals, extent=[np.min(x), np.max(x),np.min(y), np.max(y)], aspect="equal", interpolation="bicubic",cmap=cmap, vmin=vmin, vmax=vmax,origin='lower') elif vmin is not None: fig = plt.imshow(vals, extent=[np.min(x), np.max(x),np.min(y), np.max(y)], aspect="equal", interpolation="bicubic",cmap=cmap, vmin=vmin,origin='lower') else: fig = plt.imshow(vals, extent=[np.min(x), np.max(x),np.min(y), np.max(y)],cmap=cmap, aspect="equal", interpolation="bicubic",origin='lower') fig.axes.set_autoscale_on(False) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.colorbar() if path: plt.savefig(path) if show: plt.show() plt.close() import contextlib class Interp1d(torch.autograd.Function): def __call__(self, x, y, xnew, out=None): return self.forward(x, y, xnew, out) def forward(ctx, x, y, xnew, out=None): """ Linear 1D interpolation on the GPU for Pytorch. This function returns interpolated values of a set of 1-D functions at the desired query points `xnew`. This function is working similarly to Matlab™ or scipy functions with the `linear` interpolation mode on, except that it parallelises over any number of desired interpolation problems. The code will run on GPU if all the tensors provided are on a cuda device. Parameters ---------- x : (N, ) or (D, N) Pytorch Tensor A 1-D or 2-D tensor of real values. y : (N,) or (D, N) Pytorch Tensor A 1-D or 2-D tensor of real values. The length of `y` along its last dimension must be the same as that of `x` xnew : (P,) or (D, P) Pytorch Tensor A 1-D or 2-D tensor of real values. `xnew` can only be 1-D if _both_ `x` and `y` are 1-D. Otherwise, its length along the first dimension must be the same as that of whichever `x` and `y` is 2-D. out : Pytorch Tensor, same shape as `xnew` Tensor for the output. If None: allocated automatically. """ # making the vectors at least 2D is_flat = {} require_grad = {} v = {} device = [] eps = torch.finfo(y.dtype).eps for name, vec in {'x': x, 'y': y, 'xnew': xnew}.items(): assert len(vec.shape) <= 2, 'interp1d: all inputs must be '\ 'at most 2-D.' if len(vec.shape) == 1: v[name] = vec[None, :] else: v[name] = vec is_flat[name] = v[name].shape[0] == 1 require_grad[name] = vec.requires_grad device = list(set(device + [str(vec.device)])) assert len(device) == 1, 'All parameters must be on the same device.' device = device[0] # Checking for the dimensions assert (v['x'].shape[1] == v['y'].shape[1] and ( v['x'].shape[0] == v['y'].shape[0] or v['x'].shape[0] == 1 or v['y'].shape[0] == 1 ) ), ("x and y must have the same number of columns, and either " "the same number of row or one of them having only one " "row.") reshaped_xnew = False if ((v['x'].shape[0] == 1) and (v['y'].shape[0] == 1) and (v['xnew'].shape[0] > 1)): # if there is only one row for both x and y, there is no need to # loop over the rows of xnew because they will all have to face the # same interpolation problem. We should just stack them together to # call interp1d and put them back in place afterwards. original_xnew_shape = v['xnew'].shape v['xnew'] = v['xnew'].contiguous().view(1, -1) reshaped_xnew = True # identify the dimensions of output and check if the one provided is ok D = max(v['x'].shape[0], v['xnew'].shape[0]) shape_ynew = (D, v['xnew'].shape[-1]) if out is not None: if out.numel() != shape_ynew[0]*shape_ynew[1]: # The output provided is of incorrect shape. # Going for a new one out = None else: ynew = out.reshape(shape_ynew) if out is None: ynew = torch.zeros(*shape_ynew, device=device) # moving everything to the desired device in case it was not there # already (not handling the case things do not fit entirely, user will # do it if required.) for name in v: v[name] = v[name].to(device) # calling searchsorted on the x values. ind = ynew.long() # expanding xnew to match the number of rows of x in case only one xnew is # provided if v['xnew'].shape[0] == 1: v['xnew'] = v['xnew'].expand(v['x'].shape[0], -1) torch.searchsorted(v['x'].contiguous(), v['xnew'].contiguous(), out=ind) # the `-1` is because searchsorted looks for the index where the values # must be inserted to preserve order. And we want the index of the # preceeding value. ind -= 1 # we clamp the index, because the number of intervals is x.shape-1, # and the left neighbour should hence be at most number of intervals # -1, i.e. number of columns in x -2 ind = torch.clamp(ind, 0, v['x'].shape[1] - 1 - 1) # helper function to select stuff according to the found indices. def sel(name): if is_flat[name]: return v[name].contiguous().view(-1)[ind] return torch.gather(v[name], 1, ind) # activating gradient storing for everything now enable_grad = False saved_inputs = [] for name in ['x', 'y', 'xnew']: if require_grad[name]: enable_grad = True saved_inputs += [v[name]] else: saved_inputs += [None, ] # assuming x are sorted in the dimension 1, computing the slopes for # the segments is_flat['slopes'] = is_flat['x'] # now we have found the indices of the neighbors, we start building the # output. Hence, we start also activating gradient tracking with torch.enable_grad() if enable_grad else contextlib.suppress(): v['slopes'] = ( (v['y'][:, 1:]-v['y'][:, :-1]) / (eps + (v['x'][:, 1:]-v['x'][:, :-1])) ) # now build the linear interpolation ynew = sel('y') + sel('slopes')*( v['xnew'] - sel('x')) if reshaped_xnew: ynew = ynew.view(original_xnew_shape) ctx.save_for_backward(ynew, *saved_inputs) return ynew @staticmethod def backward(ctx, grad_out): inputs = ctx.saved_tensors[1:] gradients = torch.autograd.grad( ctx.saved_tensors[0], [i for i in inputs if i is not None], grad_out, retain_graph=True) result = [None, ] * 5 pos = 0 for index in range(len(inputs)): if inputs[index] is not None: result[index] = gradients[pos] pos += 1 return (*result,) class TorchQuantileTransformer(): ''' QuantileTransformer implemented by PyTorch ''' def __init__( self, output_distribution, references_, quantiles_, device=torch.device('cpu') ) -> None: self.quantiles_ = torch.Tensor(quantiles_).to(device) self.output_distribution = output_distribution self._norm_pdf_C = np.sqrt(2 * np.pi) self.references_ = torch.Tensor(references_).to(device) BOUNDS_THRESHOLD = 1e-7 self.clip_min = self.norm_ppf(torch.Tensor([BOUNDS_THRESHOLD - np.spacing(1)])) self.clip_max = self.norm_ppf(torch.Tensor([1 - (BOUNDS_THRESHOLD - np.spacing(1))])) def norm_pdf(self, x): return torch.exp(-x ** 2 / 2.0) / self._norm_pdf_C @staticmethod def norm_cdf(x): return ts.ndtr(x) @staticmethod def norm_ppf(x): return ts.ndtri(x) def transform_col(self, X_col, quantiles, inverse): BOUNDS_THRESHOLD = 1e-7 output_distribution = self.output_distribution if not inverse: lower_bound_x = quantiles[0] upper_bound_x = quantiles[-1] lower_bound_y = 0 upper_bound_y = 1 else: lower_bound_x = 0 upper_bound_x = 1 lower_bound_y = quantiles[0] upper_bound_y = quantiles[-1] # for inverse transform, match a uniform distribution with np.errstate(invalid="ignore"): # hide NaN comparison warnings if output_distribution == "normal": X_col = self.norm_cdf(X_col) # else output distribution is already a uniform distribution # find index for lower and higher bounds with np.errstate(invalid="ignore"): # hide NaN comparison warnings if output_distribution == "normal": lower_bounds_idx = X_col - BOUNDS_THRESHOLD < lower_bound_x upper_bounds_idx = X_col + BOUNDS_THRESHOLD > upper_bound_x if output_distribution == "uniform": lower_bounds_idx = X_col == lower_bound_x upper_bounds_idx = X_col == upper_bound_x isfinite_mask = ~torch.isnan(X_col) X_col_finite = X_col[isfinite_mask] torch_interp = Interp1d() X_col_out = X_col.clone() if not inverse: # Interpolate in one direction and in the other and take the # mean. This is in case of repeated values in the features # and hence repeated quantiles # # If we don't do this, only one extreme of the duplicated is # used (the upper when we do ascending, and the # lower for descending). We take the mean of these two X_col_out[isfinite_mask] = 0.5 * ( torch_interp(quantiles, self.references_, X_col_finite) - torch_interp(-torch.flip(quantiles, [0]), -torch.flip(self.references_, [0]), -X_col_finite) ) else: X_col_out[isfinite_mask] = torch_interp(self.references_, quantiles, X_col_finite) X_col_out[upper_bounds_idx] = upper_bound_y X_col_out[lower_bounds_idx] = lower_bound_y # for forward transform, match the output distribution if not inverse: with np.errstate(invalid="ignore"): # hide NaN comparison warnings if output_distribution == "normal": X_col_out = self.norm_ppf(X_col_out) # find the value to clip the data to avoid mapping to # infinity. Clip such that the inverse transform will be # consistent X_col_out = torch.clip(X_col_out, self.clip_min, self.clip_max) # else output distribution is uniform and the ppf is the # identity function so we let X_col unchanged return X_col_out def transform(self, X, inverse=True,component='all'): X_out = torch.zeros_like(X, requires_grad=False) for feature_idx in range(X.shape[1]): X_out[:, feature_idx] = self.transform_col( X[:, feature_idx], self.quantiles_[:, feature_idx], inverse ) return X_out def to(self,device): self.quantiles_ = self.quantiles_.to(device) self.references_ = self.references_.to(device) return self ''' Simple normalization layer ''' class UnitTransformer(): def __init__(self, X): self.mean = X.mean(dim=0, keepdim=True) self.std = X.std(dim=0, keepdim=True) + 1e-8 def to(self, device): self.mean = self.mean.to(device) self.std = self.std.to(device) return self def transform(self, X, inverse=True,component='all'): if component == 'all' or 'all-reduce': if inverse: orig_shape = X.shape return (X*(self.std - 1e-8) + self.mean).view(orig_shape) else: return (X-self.mean)/self.std else: if inverse: orig_shape = X.shape return (X*(self.std[:,component] - 1e-8)+ self.mean[:,component]).view(orig_shape) else: return (X - self.mean[:,component])/self.std[:,component] ''' Simple pointwise normalization layer, all data must contain the same length, used only for FNO datasets X: B, N, C ''' class PointWiseUnitTransformer(): def __init__(self, X): self.mean = X.mean(dim=0, keepdim=False) self.std = X.std(dim=0, keepdim=False) + 1e-8 def to(self, device): self.mean = self.mean.to(device) self.std = self.std.to(device) return self def transform(self, X, inverse=True,component='all'): if component == 'all' or 'all-reduce': if inverse: orig_shape = X.shape X = X.view(-1, self.mean.shape[0],self.mean.shape[1]) ### align shape for flat tensor return (X*(self.std - 1e-8) + self.mean).view(orig_shape) else: return (X-self.mean)/self.std else: if inverse: orig_shape = X.shape X = X.view(-1, self.mean.shape[0],self.mean.shape[1]) return (X*(self.std[:,component] - 1e-8)+ self.mean[:,component]).view(orig_shape) else: return (X - self.mean[:,component])/self.std[:,component] ''' x: B, N (not necessary sorted) y: B, N, C (not necessary sorted) xnew: B, N (sorted) ''' def binterp1d(x, y, xnew, eps=1e-9): x_, x_indice = torch.sort(x,dim=-1) y_ = y[torch.arange(x_.shape[0]).unsqueeze(1),x_indice] x_, y_, xnew = x_.contiguous(), y_.contiguous(), xnew.contiguous() ind = torch.searchsorted(x_, xnew) ind -= 1 ind = torch.clamp(ind, 0, x_.shape[1] - 1 - 1) ind = ind.unsqueeze(-1).repeat([1, 1, y_.shape[-1]]) x_ = x_.unsqueeze(-1).repeat([1, 1, y_.shape[-1]]) slopes = ((y_[:, 1:]-y_[:, :-1])/(eps + (x_[:, 1:]-x_[:, :-1]))) y_sel = torch.gather(y_, 1, ind) x_sel = torch.gather(x_,1, ind) slopes_sel = torch.gather(slopes, 1, ind) ynew =y_sel + slopes_sel * (xnew.unsqueeze(-1) - x_sel) return ynew
17,709
34.562249
118
py
GNOT
GNOT-master/visualize_result.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import pickle import torch import numpy as np import torch.nn as nn import dgl import matplotlib.pyplot as plt from dgl.dataloading import GraphDataLoader from torch.utils.data.sampler import SubsetRandomSampler from utils import get_seed, get_num_params from args import get_args from data_utils import get_dataset, get_model, get_loss_func, MIODataLoader from train import validate_epoch from utils import plot_heatmap if __name__ == "__main__": model_path = '[Your model path]' result = torch.load(model_path,map_location='cpu') args = result['args'] model_dict = result['model'] vis_component = 0 if args.component == 'all' else int(args.component) device = torch.device('cpu') kwargs = {'pin_memory': False} if args.gpu else {} get_seed(args.seed, printout=False) train_dataset, test_dataset = get_dataset(args) test_sampler = SubsetRandomSampler(torch.arange(len(test_dataset))) test_loader = MIODataLoader(test_dataset, sampler=test_sampler, batch_size=1, drop_last=False) loss_func = get_loss_func(args.loss_name, args, regularizer=True, normalizer=args.normalizer) metric_func = get_loss_func(args.loss_name, args , regularizer=False, normalizer=args.normalizer) model = get_model(args,) model.load_state_dict(model_dict) model.eval() with torch.no_grad(): #### test single case idx = 0 g, u_p, g_u = list(iter(test_loader))[idx] # u_p = u_p.unsqueeze(0) ### test if necessary out = model(g, u_p, g_u) x, y = g.ndata['x'][:,0].cpu().numpy(), g.ndata['x'][:,1].cpu().numpy() pred = out[:,vis_component].squeeze().cpu().numpy() target =g.ndata['y'][:,vis_component].squeeze().cpu().numpy() err = pred - target print(pred) print(target) print(err) print(np.linalg.norm(err)/np.linalg.norm(target)) #### choose one to visualize cm = plt.cm.get_cmap('rainbow') plot_heatmap(x, y, pred,cmap=cm,show=True) plot_heatmap(x, y, target,cmap=cm,show=True) plt.figure() plt.scatter(x, y, c=pred, cmap=cm,s=2) plt.colorbar() plt.show() plt.figure() plt.scatter(x, y, c=err, cmap=cm,s=2) plt.colorbar() plt.show() plt.scatter(x, y, c=target, s=2,cmap=cm) plt.colorbar() plt.show()
2,452
25.095745
101
py
GNOT
GNOT-master/data_generation/__init__.py
#!/usr/bin/env python #-*- coding:utf-8 _*-
46
14.666667
23
py
GNOT
GNOT-master/models/__init__.py
#!/usr/bin/env python #-*- coding:utf-8 _*-
46
14.666667
23
py
GNOT
GNOT-master/models/cgpt.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import math import numpy as np import torch import torch.nn as nn import dgl from einops import repeat, rearrange from torch.nn import functional as F from torch.nn import GELU, ReLU, Tanh, Sigmoid from torch.nn.utils.rnn import pad_sequence from utils import MultipleTensors from models.mlp import MLP class GPTConfig(): """ base GPT config, params common to all GPT versions """ def __init__(self,attn_type='linear', embd_pdrop=0.0, resid_pdrop=0.0,attn_pdrop=0.0, n_embd=128, n_head=1, n_layer=3, block_size=128, n_inner=512,act='gelu', branch_sizes=1,n_inputs=1): self.attn_type = attn_type self.embd_pdrop = embd_pdrop self.resid_pdrop = resid_pdrop self.attn_pdrop = attn_pdrop self.n_embd = n_embd # 64 self.n_head = n_head self.n_layer = n_layer self.block_size = block_size self.n_inner = 4 * self.n_embd self.act = act self.branch_sizes = branch_sizes self.n_inputs = n_inputs ''' X: N*T*C --> N*(4*n + 3)*C ''' def horizontal_fourier_embedding(X, n=3): freqs = 2**torch.linspace(-n, n, 2*n+1).to(X.device) freqs = freqs[None,None,None,...] X_ = X.unsqueeze(-1).repeat([1,1,1,2*n+1]) X_cos = torch.cos(freqs * X_) X_sin = torch.sin(freqs * X_) X = torch.cat([X.unsqueeze(-1), X_cos, X_sin],dim=-1).view(X.shape[0],X.shape[1],-1) return X class LinearAttention(nn.Module): """ A vanilla multi-head masked self-attention layer with a projection at the end. It is possible to use torch.nn.MultiheadAttention here but I am including an explicit implementation here to show that there is nothing too scary here. """ def __init__(self, config): super(LinearAttention, self).__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads self.key = nn.Linear(config.n_embd, config.n_embd) self.query = nn.Linear(config.n_embd, config.n_embd) self.value = nn.Linear(config.n_embd, config.n_embd) # regularization self.attn_drop = nn.Dropout(config.attn_pdrop) # output projection self.proj = nn.Linear(config.n_embd, config.n_embd) self.n_head = config.n_head self.attn_type = 'l1' ''' Linear Attention and Linear Cross Attention (if y is provided) ''' def forward(self, x, y=None, layer_past=None): y = x if y is None else y B, T1, C = x.size() _, T2, _ = y.size() # calculate query, key, values for all heads in batch and move head forward to be the batch dim q = self.query(x).view(B, T1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) k = self.key(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = self.value(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) if self.attn_type == 'l1': q = q.softmax(dim=-1) k = k.softmax(dim=-1) # k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).sum(dim=-1, keepdim=True) # normalized elif self.attn_type == "galerkin": q = q.softmax(dim=-1) k = k.softmax(dim=-1) # D_inv = 1. / T2 # galerkin elif self.attn_type == "l2": # still use l1 normalization q = q / q.norm(dim=-1,keepdim=True, p=1) k = k / k.norm(dim=-1,keepdim=True, p=1) k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).abs().sum(dim=-1, keepdim=True) # normalized else: raise NotImplementedError context = k.transpose(-2, -1) @ v y = self.attn_drop((q @ context) * D_inv + q) # output projection y = rearrange(y, 'b h n d -> b n (h d)') y = self.proj(y) return y class LinearCrossAttention(nn.Module): """ A vanilla multi-head masked self-attention layer with a projection at the end. It is possible to use torch.nn.MultiheadAttention here but I am including an explicit implementation here to show that there is nothing too scary here. """ def __init__(self, config): super(LinearCrossAttention, self).__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads self.query = nn.Linear(config.n_embd, config.n_embd) self.keys = nn.ModuleList([nn.Linear(config.n_embd, config.n_embd) for _ in range(config.n_inputs)]) self.values = nn.ModuleList([nn.Linear(config.n_embd, config.n_embd) for _ in range(config.n_inputs)]) # regularization self.attn_drop = nn.Dropout(config.attn_pdrop) # output projection self.proj = nn.Linear(config.n_embd, config.n_embd) self.n_head = config.n_head self.n_inputs = config.n_inputs self.attn_type = 'l1' ''' Linear Attention and Linear Cross Attention (if y is provided) ''' def forward(self, x, y=None, layer_past=None): y = x if y is None else y B, T1, C = x.size() # calculate query, key, values for all heads in batch and move head forward to be the batch dim q = self.query(x).view(B, T1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) q = q.softmax(dim=-1) out = q for i in range(self.n_inputs): _, T2, _ = y[i].size() k = self.keys[i](y[i]).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = self.values[i](y[i]).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) k = k.softmax(dim=-1) # k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).sum(dim=-1, keepdim=True) # normalized out = out + 1 * (q @ (k.transpose(-2, -1) @ v)) * D_inv # output projection out = rearrange(out, 'b h n d -> b n (h d)') out = self.proj(out) return out ''' Self and Cross Attention block for CGPT, contains a cross attention block and a self attention block ''' class CrossAttentionBlock(nn.Module): def __init__(self, config): super(CrossAttentionBlock, self).__init__() self.ln1 = nn.LayerNorm(config.n_embd) self.ln2_branch = nn.ModuleList([nn.LayerNorm(config.n_embd) for _ in range(config.n_inputs)]) self.n_inputs = config.n_inputs self.ln3 = nn.LayerNorm(config.n_embd) self.ln4 = nn.LayerNorm(config.n_embd) self.ln5 = nn.LayerNorm(config.n_embd) # self.ln6 = nn.LayerNorm(config.n_embd) ## for ab study if config.attn_type == 'linear': print('Using Linear Attention') self.selfattn = LinearAttention(config) self.crossattn = LinearCrossAttention(config) # self.selfattn_branch = LinearAttention(config) else: raise NotImplementedError if config.act == 'gelu': self.act = GELU elif config.act == "tanh": self.act = Tanh elif config.act == 'relu': self.act = ReLU elif config.act == 'sigmoid': self.act = Sigmoid self.resid_drop1 = nn.Dropout(config.resid_pdrop) self.resid_drop2 = nn.Dropout(config.resid_pdrop) self.mlp1 = nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) self.mlp2 = nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) def ln_branchs(self, y): return MultipleTensors([self.ln2_branch[i](y[i]) for i in range(self.n_inputs)]) def forward(self, x, y): x = x + self.resid_drop1(self.crossattn(self.ln1(x), self.ln_branchs(y))) x = x + self.mlp1(self.ln3(x)) x = x + self.resid_drop2(self.selfattn(self.ln4(x))) x = x + self.mlp2(self.ln5(x)) return x ''' Cross Attention GPT neural operator Trunck Net: geom''' class CGPTNO(nn.Module): def __init__(self, trunk_size=2, branch_sizes=None, output_size=3, n_layers=2, n_hidden=64, n_head=1, n_inner=4, mlp_layers=2, attn_type='linear', act = 'gelu', ffn_dropout=0.0, attn_dropout=0.0, horiz_fourier_dim = 0, ): super(CGPTNO, self).__init__() self.horiz_fourier_dim = horiz_fourier_dim self.trunk_size = trunk_size * (4*horiz_fourier_dim + 3) if horiz_fourier_dim>0 else trunk_size # self.branch_sizes = [bsize * (4*horiz_fourier_dim + 3) for bsize in branch_sizes] if horiz_fourier_dim > 0 else branch_sizes self.branch_sizes = branch_sizes self.output_size = output_size self.trunk_mlp = MLP(self.trunk_size, n_hidden, n_hidden, n_layers=mlp_layers,act=act) if branch_sizes: self.n_inputs = len(branch_sizes) self.branch_mlps = nn.ModuleList([MLP(bsize, n_hidden, n_hidden, n_layers=mlp_layers, act=act) for bsize in self.branch_sizes]) else: self.n_inputs = 0 self.gpt_config = GPTConfig(attn_type=attn_type, embd_pdrop=ffn_dropout, resid_pdrop=ffn_dropout, attn_pdrop=attn_dropout, n_embd=n_hidden, n_head=n_head, n_layer=n_layers, block_size=128, act=act, branch_sizes=branch_sizes, n_inputs=self.n_inputs, n_inner=n_inner) self.blocks = nn.Sequential(*[CrossAttentionBlock(self.gpt_config) for _ in range(self.gpt_config.n_layer)]) self.out_mlp = MLP(n_hidden, n_hidden, output_size, n_layers=mlp_layers) # self.apply(self._init_weights) self.__name__ = 'CGPT' def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=0.0002) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def configure_optimizers(self, lr=1e-3, betas=(0.9,0.999), weight_decay=0.00001, no_decay_extras=[]): """ This long function is unfortunately doing something very simple and is being very defensive: We are separating out all parameters of the model into two buckets: those that will experience weight decay for regularization and those that won't (biases, and layernorm/embedding weights). We are then returning the PyTorch optimizer object. """ # separate out all parameters to those that will and won't experience regularizing weight decay decay = set() no_decay = set() # whitelist_weight_modules = (torch.nn.Linear, ) whitelist_weight_modules = (torch.nn.Linear, torch.nn.Conv2d) blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding) for mn, m in self.named_modules(): for pn, p in m.named_parameters(): fpn = '%s.%s' % (mn, pn) if mn else pn # full param name if pn.endswith('bias'): # all biases will not be decayed no_decay.add(fpn) elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules): # weights of whitelist modules will be weight decayed decay.add(fpn) elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules): # weights of blacklist modules will NOT be weight decayed no_decay.add(fpn) # special case the position embedding parameter in the root GPT module as not decayed for nd in no_decay_extras: no_decay.add(nd) # validate that we considered every parameter param_dict = {pn: p for pn, p in self.named_parameters()} inter_params = decay & no_decay union_params = decay | no_decay assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) assert len( param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \ % (str(param_dict.keys() - union_params),) # create the pytorch optimizer object optim_groups = [ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": weight_decay}, {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, ] optimizer = torch.optim.AdamW(optim_groups, lr=lr, betas=betas) return optimizer def forward(self, g, u_p, inputs): gs = dgl.unbatch(g) x = pad_sequence([_g.ndata['x'] for _g in gs]).permute(1, 0, 2) # B, T1, F x = torch.cat([x, u_p.unsqueeze(1).repeat([1, x.shape[1], 1])], dim=-1) if self.horiz_fourier_dim > 0: x = horizontal_fourier_embedding(x, self.horiz_fourier_dim) # z = horizontal_fourier_embedding(z, self.horiz_fourier_dim) x = self.trunk_mlp(x) if self.n_inputs: z = MultipleTensors([self.branch_mlps[i](inputs[i]) for i in range(self.n_inputs)]) else: z = MultipleTensors([x]) for block in self.blocks: x = block(x, z) x = self.out_mlp(x) x_out = torch.cat([x[i, :num] for i, num in enumerate(g.batch_num_nodes())],dim=0) return x_out class CGPT(nn.Module): def __init__(self, trunk_size=2, branch_sizes=None, space_dim=2, output_size=3, n_layers=2, n_hidden=64, n_head=1, n_experts = 2, n_inner = 4, mlp_layers=2, attn_type='linear', act = 'gelu', ffn_dropout=0.0, attn_dropout=0.0, horiz_fourier_dim = 0, ): super(CGPT, self).__init__() self.horiz_fourier_dim = horiz_fourier_dim self.trunk_size = trunk_size * (4*horiz_fourier_dim + 3) if horiz_fourier_dim>0 else trunk_size self.branch_sizes = [bsize * (4*horiz_fourier_dim + 3) for bsize in branch_sizes] if horiz_fourier_dim > 0 else branch_sizes self.n_inputs = len(self.branch_sizes) self.output_size = output_size self.space_dim = space_dim self.gpt_config = GPTConfig(attn_type=attn_type,embd_pdrop=ffn_dropout, resid_pdrop=ffn_dropout, attn_pdrop=attn_dropout,n_embd=n_hidden, n_head=n_head, n_layer=n_layers, block_size=128,act=act, branch_sizes=branch_sizes,n_inputs=len(branch_sizes),n_inner=n_inner) self.trunk_mlp = MLP(self.trunk_size, n_hidden, n_hidden, n_layers=mlp_layers,act=act) self.branch_mlps = nn.ModuleList([MLP(bsize, n_hidden, n_hidden, n_layers=mlp_layers,act=act) for bsize in self.branch_sizes]) self.blocks = nn.Sequential(*[CrossAttentionBlock(self.gpt_config) for _ in range(self.gpt_config.n_layer)]) self.out_mlp = MLP(n_hidden, n_hidden, output_size, n_layers=mlp_layers) # self.apply(self._init_weights) self.__name__ = 'MIOEGPT' def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=0.0002) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def forward(self, g, u_p, inputs): gs = dgl.unbatch(g) x = pad_sequence([_g.ndata['x'] for _g in gs]).permute(1, 0, 2) # B, T1, F x = torch.cat([x, u_p.unsqueeze(1).repeat([1, x.shape[1], 1])], dim=-1) # if self.horiz_fourier_dim > 0: # x = horizontal_fourier_embedding(x, self.horiz_fourier_dim) # z = horizontal_fourier_embedding(z, self.horiz_fourier_dim) x = self.trunk_mlp(x) z = MultipleTensors([self.branch_mlps[i](inputs[i]) for i in range(self.n_inputs)]) for block in self.blocks: x = block(x, z) x = self.out_mlp(x) x_out = torch.cat([x[i, :num] for i, num in enumerate(g.batch_num_nodes())],dim=0) return x_out
17,097
37.770975
190
py
GNOT
GNOT-master/models/mgpt.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import math import numpy as np import torch import torch.nn as nn import dgl from einops import repeat, rearrange from torch.nn import functional as F from torch.nn import GELU, ReLU, Tanh, Sigmoid from torch.nn.utils.rnn import pad_sequence from models.mlp import MLP class MoEGPTConfig(): """ base GPT config, params common to all GPT versions """ def __init__(self,attn_type='linear', embd_pdrop=0.0, resid_pdrop=0.0,attn_pdrop=0.0, n_embd=128, n_head=1, n_layer=3, block_size=128, n_inner=512,act='gelu',n_experts=2,space_dim=1): self.attn_type = attn_type self.embd_pdrop = embd_pdrop self.resid_pdrop = resid_pdrop self.attn_pdrop = attn_pdrop self.n_embd = n_embd # 64 self.n_head = n_head self.n_layer = n_layer self.block_size = block_size self.n_inner = 4 * self.n_embd self.act = act self.n_experts = n_experts self.space_dim = space_dim class LinearAttention(nn.Module): """ A vanilla multi-head masked self-attention layer with a projection at the end. It is possible to use torch.nn.MultiheadAttention here but I am including an explicit implementation here to show that there is nothing too scary here. """ def __init__(self, config): super(LinearAttention, self).__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads self.key = nn.Linear(config.n_embd, config.n_embd) self.query = nn.Linear(config.n_embd, config.n_embd) self.value = nn.Linear(config.n_embd, config.n_embd) # regularization self.attn_drop = nn.Dropout(config.attn_pdrop) # output projection self.proj = nn.Linear(config.n_embd, config.n_embd) self.n_head = config.n_head self.attn_type = 'l1' ''' Linear Attention and Linear Cross Attention (if y is provided) ''' def forward(self, x, y=None, layer_past=None): y = x if y is None else y B, T1, C = x.size() _, T2, _ = y.size() # calculate query, key, values for all heads in batch and move head forward to be the batch dim q = self.query(x).view(B, T1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) k = self.key(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = self.value(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) if self.attn_type == 'l1': q = q.softmax(dim=-1) k = k.softmax(dim=-1) # k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).sum(dim=-1, keepdim=True) # normalized elif self.attn_type == "galerkin": q = q.softmax(dim=-1) k = k.softmax(dim=-1) # D_inv = 1. / T2 # galerkin elif self.attn_type == "l2": # still use l1 normalization q = q / q.norm(dim=-1,keepdim=True, p=1) k = k / k.norm(dim=-1,keepdim=True, p=1) k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).abs().sum(dim=-1, keepdim=True) # normalized else: raise NotImplementedError context = k.transpose(-2, -1) @ v y = self.attn_drop((q @ context) * D_inv + q) # output projection y = rearrange(y, 'b h n d -> b n (h d)') y = self.proj(y) return y def generalized_kernel(data, *, projection_matrix, kernel_fn = nn.ReLU(), kernel_epsilon = 0.001, normalize_data = True, device = None): b, h, *_ = data.shape data_normalizer = (data.shape[-1] ** -0.25) if normalize_data else 1. if projection_matrix is None: return kernel_fn(data_normalizer * data) + kernel_epsilon projection = repeat(projection_matrix, 'j d -> b h j d', b = b, h = h) projection = projection.type_as(data) data_dash = torch.einsum('...id,...jd->...ij', (data_normalizer * data), projection) data_prime = kernel_fn(data_dash) + kernel_epsilon return data_prime.type_as(data) def orthogonal_matrix_chunk(cols, device = None): from distutils.version import LooseVersion TORCH_GE_1_8_0 = LooseVersion(torch.__version__) >= LooseVersion('1.8.0') unstructured_block = torch.randn((cols, cols), device = device) if TORCH_GE_1_8_0: q, r = torch.linalg.qr(unstructured_block.cpu(), mode = 'reduced') else: q, r = torch.qr(unstructured_block.cpu(), some = True) q, r = map(lambda t: t.to(device), (q, r)) return q.t() ''' X: N*T*C --> N*(4*n + 3)*C ''' def horizontal_fourier_embedding(X, n=3): freqs = 2**torch.linspace(-n, n, 2*n+1).to(X.device) freqs = freqs[None,None,None,...] X_ = X.unsqueeze(-1).repeat([1,1,1,2*n+1]) X_cos = torch.cos(freqs * X_) X_sin = torch.sin(freqs * X_) X = torch.cat([X.unsqueeze(-1), X_cos, X_sin],dim=-1).view(X.shape[0],X.shape[1],-1) return X ''' Self and Cross Attention block for CGPT, contains a cross attention block and a self attention block ''' class MoECrossAttentionBlock(nn.Module): def __init__(self, config): super(MoECrossAttentionBlock, self).__init__() self.ln1 = nn.LayerNorm(config.n_embd) self.ln2 = nn.LayerNorm(config.n_embd) self.ln3 = nn.LayerNorm(config.n_embd) self.ln4 = nn.LayerNorm(config.n_embd) self.ln5 = nn.LayerNorm(config.n_embd) if config.attn_type == 'linear': print('Using Linear Attention') self.selfattn = LinearAttention(config) self.crossattn = LinearAttention(config) # self.selfattn_branch = LinearAttention(config) else: raise NotImplementedError if config.act == 'gelu': self.act = GELU elif config.act == "tanh": self.act = Tanh elif config.act == 'relu': self.act = ReLU elif config.act == 'sigmoid': self.act = Sigmoid self.resid_drop1 = nn.Dropout(config.resid_pdrop) self.resid_drop2 = nn.Dropout(config.resid_pdrop) self.n_experts = config.n_experts self.moe_mlp1 = nn.ModuleList([nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) for _ in range(self.n_experts)]) self.moe_mlp2 = nn.ModuleList([nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) for _ in range(self.n_experts)]) self.gatenet = nn.Sequential( nn.Linear(config.space_dim, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_inner), self.act(), nn.Linear(config.n_inner, self.n_experts) ) ''' x: [B, T1, C], y:[B, T2, C], pos:[B, T1, n] ''' def forward(self, x, y, pos): gate_score = F.softmax(self.gatenet(pos),dim=-1).unsqueeze(2) # B, T1, 1, m x = x + self.resid_drop1(self.crossattn(self.ln1(x), self.ln2(y))) x_moe1 = torch.stack([self.moe_mlp1[i](x) for i in range(self.n_experts)],dim=-1) # B, T1, C, m x_moe1 = (gate_score*x_moe1).sum(dim=-1,keepdim=False) x = x + self.ln3(x_moe1) x = x + self.resid_drop2(self.selfattn(self.ln4(x))) x_moe2 = torch.stack([self.moe_mlp1[i](x) for i in range(self.n_experts)],dim=-1) # B, T1, C, m x_moe2 = (gate_score*x_moe2).sum(dim=-1,keepdim=False) x = x + self.ln5(x_moe2) return x #### No layernorm # def forward(self, x, y): # # y = self.selfattn_branch(self.ln5(y)) # x = x + self.resid_drop1(self.crossattn(x, y)) # x = x + self.mlp1(x) # x = x + self.resid_drop2(self.selfattn(x)) # x = x + self.mlp2(x) # # return x ''' Cross Attention GPT neural operator Trunck Net: geom ''' class MoEGPTNO(nn.Module): def __init__(self, trunk_size=2, branch_size=2, space_dim=2, output_size=3, n_layers=2, n_hidden=64, n_head=1, n_experts = 2, mlp_layers=2, attn_type='linear', act = 'gelu', ffn_dropout=0.0, attn_dropout=0.0, horiz_fourier_dim = 0, ): super(MoEGPTNO, self).__init__() self.horiz_fourier_dim = horiz_fourier_dim self.trunk_size = trunk_size * (4*horiz_fourier_dim + 3) if horiz_fourier_dim>0 else trunk_size self.branch_size = branch_size * (4*horiz_fourier_dim + 3) if horiz_fourier_dim > 0 else branch_size self.output_size = output_size self.space_dim = space_dim self.gpt_config = MoEGPTConfig(attn_type=attn_type,embd_pdrop=ffn_dropout, resid_pdrop=ffn_dropout, attn_pdrop=attn_dropout,n_embd=n_hidden, n_head=n_head, n_layer=n_layers, block_size=128,act=act, n_experts=n_experts,space_dim=space_dim) self.trunk_mlp = MLP(self.trunk_size, n_hidden, n_hidden, n_layers=mlp_layers,act=act) self.branch_mlp = MLP(self.branch_size, n_hidden, n_hidden, n_layers=mlp_layers,act=act) self.blocks = nn.Sequential(*[MoECrossAttentionBlock(self.gpt_config) for _ in range(self.gpt_config.n_layer)]) self.out_mlp = MLP(n_hidden, n_hidden, output_size, n_layers=mlp_layers) # self.apply(self._init_weights) self.__name__ = 'MoEGPT' def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=0.0002) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def configure_optimizers(self, lr=1e-3, betas=(0.9,0.999), weight_decay=0.00001, no_decay_extras=[]): """ This long function is unfortunately doing something very simple and is being very defensive: We are separating out all parameters of the model into two buckets: those that will experience weight decay for regularization and those that won't (biases, and layernorm/embedding weights). We are then returning the PyTorch optimizer object. """ # separate out all parameters to those that will and won't experience regularizing weight decay decay = set() no_decay = set() # whitelist_weight_modules = (torch.nn.Linear, ) whitelist_weight_modules = (torch.nn.Linear, torch.nn.Conv2d) blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding) for mn, m in self.named_modules(): for pn, p in m.named_parameters(): fpn = '%s.%s' % (mn, pn) if mn else pn # full param name if pn.endswith('bias'): # all biases will not be decayed no_decay.add(fpn) elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules): # weights of whitelist modules will be weight decayed decay.add(fpn) elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules): # weights of blacklist modules will NOT be weight decayed no_decay.add(fpn) # special case the position embedding parameter in the root GPT module as not decayed for nd in no_decay_extras: no_decay.add(nd) # validate that we considered every parameter param_dict = {pn: p for pn, p in self.named_parameters()} inter_params = decay & no_decay union_params = decay | no_decay assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params),) assert len( param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \ % (str(param_dict.keys() - union_params),) # create the pytorch optimizer object optim_groups = [ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": weight_decay}, {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, ] optimizer = torch.optim.AdamW(optim_groups, lr=lr, betas=betas) return optimizer def forward(self, g, u_p, g_u): gs = dgl.unbatch(g) g_us = dgl.unbatch(g_u) x = pad_sequence([_g.ndata['x'] for _g in gs]).permute(1, 0, 2) # B, T1, F pos = x[:,:,0:self.space_dim] z = pad_sequence([_g.ndata['x'] for _g in g_us]).permute(1, 0, 2) # B, T2, F x = torch.cat([x, u_p.unsqueeze(1).repeat([1, x.shape[1], 1])], dim=-1) if self.horiz_fourier_dim > 0: x = horizontal_fourier_embedding(x, self.horiz_fourier_dim) z = horizontal_fourier_embedding(z, self.horiz_fourier_dim) x = self.trunk_mlp(x) z = self.branch_mlp(z) for block in self.blocks: x = block(x, z, pos) x = self.out_mlp(x) x_out = torch.cat([x[i, :num] for i, num in enumerate(g.batch_num_nodes())],dim=0) return x_out
13,659
37.696884
246
py
GNOT
GNOT-master/models/mlp.py
import torch.nn as nn import torch.nn.functional as F import dgl ACTIVATION = {'gelu':nn.GELU(),'tanh':nn.Tanh(),'sigmoid':nn.Sigmoid(),'relu':nn.ReLU(),'leaky_relu':nn.LeakyReLU(0.1),'softplus':nn.Softplus(),'ELU':nn.ELU()} ''' A simple MLP class, includes at least 2 layers and n hidden layers ''' class MLP(nn.Module): def __init__(self, n_input, n_hidden, n_output, n_layers=1, act='gelu'): super(MLP, self).__init__() if act in ACTIVATION.keys(): self.act = ACTIVATION[act] else: raise NotImplementedError self.n_input = n_input self.n_hidden = n_hidden self.n_output = n_output self.n_layers = n_layers self.linear_pre = nn.Linear(n_input, n_hidden) self.linear_post = nn.Linear(n_hidden, n_output) self.linears = nn.ModuleList([nn.Linear(n_hidden, n_hidden) for _ in range(n_layers)]) # self.bns = nn.ModuleList([nn.BatchNorm1d(n_hidden) for _ in range(n_layers)]) def forward(self, x): x = self.act(self.linear_pre(x)) for i in range(self.n_layers): x = self.act(self.linears[i](x)) + x # x = self.act(self.bns[i](self.linears[i](x))) + x x = self.linear_post(x) return x
1,270
30.775
159
py
GNOT
GNOT-master/models/mmgpt.py
#!/usr/bin/env python #-*- coding:utf-8 _*- import math import numpy as np import torch import torch.nn as nn import dgl from einops import repeat, rearrange from torch.nn import functional as F from torch.nn import GELU, ReLU, Tanh, Sigmoid from torch.nn.utils.rnn import pad_sequence from utils import MultipleTensors from models.mlp import MLP class MoEGPTConfig(): """ base GPT config, params common to all GPT versions """ def __init__(self,attn_type='linear', embd_pdrop=0.0, resid_pdrop=0.0,attn_pdrop=0.0, n_embd=128, n_head=1, n_layer=3, block_size=128, n_inner=4,act='gelu',n_experts=2,space_dim=1,branch_sizes=None,n_inputs=1): self.attn_type = attn_type self.embd_pdrop = embd_pdrop self.resid_pdrop = resid_pdrop self.attn_pdrop = attn_pdrop self.n_embd = n_embd # 64 self.n_head = n_head self.n_layer = n_layer self.block_size = block_size self.n_inner = n_inner * self.n_embd self.act = act self.n_experts = n_experts self.space_dim = space_dim self.branch_sizes = branch_sizes self.n_inputs = n_inputs class LinearAttention(nn.Module): """ A vanilla multi-head masked self-attention layer with a projection at the end. It is possible to use torch.nn.MultiheadAttention here but I am including an explicit implementation here to show that there is nothing too scary here. """ def __init__(self, config): super(LinearAttention, self).__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads self.key = nn.Linear(config.n_embd, config.n_embd) self.query = nn.Linear(config.n_embd, config.n_embd) self.value = nn.Linear(config.n_embd, config.n_embd) # regularization self.attn_drop = nn.Dropout(config.attn_pdrop) # output projection self.proj = nn.Linear(config.n_embd, config.n_embd) self.n_head = config.n_head self.attn_type = 'l1' ''' Linear Attention and Linear Cross Attention (if y is provided) ''' def forward(self, x, y=None, layer_past=None): y = x if y is None else y B, T1, C = x.size() _, T2, _ = y.size() # calculate query, key, values for all heads in batch and move head forward to be the batch dim q = self.query(x).view(B, T1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) k = self.key(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = self.value(y).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) if self.attn_type == 'l1': q = q.softmax(dim=-1) k = k.softmax(dim=-1) # k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).sum(dim=-1, keepdim=True) # normalized elif self.attn_type == "galerkin": q = q.softmax(dim=-1) k = k.softmax(dim=-1) # D_inv = 1. / T2 # galerkin elif self.attn_type == "l2": # still use l1 normalization q = q / q.norm(dim=-1,keepdim=True, p=1) k = k / k.norm(dim=-1,keepdim=True, p=1) k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).abs().sum(dim=-1, keepdim=True) # normalized else: raise NotImplementedError context = k.transpose(-2, -1) @ v y = self.attn_drop((q @ context) * D_inv + q) # output projection y = rearrange(y, 'b h n d -> b n (h d)') y = self.proj(y) return y class LinearCrossAttention(nn.Module): """ A vanilla multi-head masked self-attention layer with a projection at the end. It is possible to use torch.nn.MultiheadAttention here but I am including an explicit implementation here to show that there is nothing too scary here. """ def __init__(self, config): super(LinearCrossAttention, self).__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads self.query = nn.Linear(config.n_embd, config.n_embd) self.keys = nn.ModuleList([nn.Linear(config.n_embd, config.n_embd) for _ in range(config.n_inputs)]) self.values = nn.ModuleList([nn.Linear(config.n_embd, config.n_embd) for _ in range(config.n_inputs)]) # regularization self.attn_drop = nn.Dropout(config.attn_pdrop) # output projection self.proj = nn.Linear(config.n_embd, config.n_embd) self.n_head = config.n_head self.n_inputs = config.n_inputs self.attn_type = 'l1' ''' Linear Attention and Linear Cross Attention (if y is provided) ''' def forward(self, x, y=None, layer_past=None): y = x if y is None else y B, T1, C = x.size() # calculate query, key, values for all heads in batch and move head forward to be the batch dim q = self.query(x).view(B, T1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) q = q.softmax(dim=-1) out = q for i in range(self.n_inputs): _, T2, _ = y[i].size() k = self.keys[i](y[i]).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = self.values[i](y[i]).view(B, T2, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) k = k.softmax(dim=-1) # k_cumsum = k.sum(dim=-2, keepdim=True) D_inv = 1. / (q * k_cumsum).sum(dim=-1, keepdim=True) # normalized out = out + 1 * (q @ (k.transpose(-2, -1) @ v)) * D_inv # output projection out = rearrange(out, 'b h n d -> b n (h d)') out = self.proj(out) return out ''' X: N*T*C --> N*(4*n + 3)*C ''' def horizontal_fourier_embedding(X, n=3): freqs = 2**torch.linspace(-n, n, 2*n+1).to(X.device) freqs = freqs[None,None,None,...] X_ = X.unsqueeze(-1).repeat([1,1,1,2*n+1]) X_cos = torch.cos(freqs * X_) X_sin = torch.sin(freqs * X_) X = torch.cat([X.unsqueeze(-1), X_cos, X_sin],dim=-1).view(X.shape[0],X.shape[1],-1) return X ''' Self and Cross Attention block for CGPT, contains a cross attention block and a self attention block ''' class MIOECrossAttentionBlock(nn.Module): def __init__(self, config): super(MIOECrossAttentionBlock, self).__init__() self.ln1 = nn.LayerNorm(config.n_embd) self.ln2_branch = nn.ModuleList([nn.LayerNorm(config.n_embd) for _ in range(config.n_inputs)]) self.ln3 = nn.LayerNorm(config.n_embd) self.ln4 = nn.LayerNorm(config.n_embd) self.ln5 = nn.LayerNorm(config.n_embd) if config.attn_type == 'linear': print('Using Linear Attention') self.selfattn = LinearAttention(config) self.crossattn = LinearCrossAttention(config) else: raise NotImplementedError if config.act == 'gelu': self.act = GELU elif config.act == "tanh": self.act = Tanh elif config.act == 'relu': self.act = ReLU elif config.act == 'sigmoid': self.act = Sigmoid self.resid_drop1 = nn.Dropout(config.resid_pdrop) self.resid_drop2 = nn.Dropout(config.resid_pdrop) self.n_experts = config.n_experts self.n_inputs = config.n_inputs self.moe_mlp1 = nn.ModuleList([nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) for _ in range(self.n_experts)]) self.moe_mlp2 = nn.ModuleList([nn.Sequential( nn.Linear(config.n_embd, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_embd), ) for _ in range(self.n_experts)]) self.gatenet = nn.Sequential( nn.Linear(config.space_dim, config.n_inner), self.act(), nn.Linear(config.n_inner, config.n_inner), self.act(), nn.Linear(config.n_inner, self.n_experts) ) def ln_branchs(self, y): return MultipleTensors([self.ln2_branch[i](y[i]) for i in range(self.n_inputs)]) ''' x: [B, T1, C], y:[B, T2, C], pos:[B, T1, n] ''' def forward(self, x, y, pos): gate_score = F.softmax(self.gatenet(pos),dim=-1).unsqueeze(2) # B, T1, 1, m x = x + self.resid_drop1(self.crossattn(self.ln1(x), self.ln_branchs(y))) x_moe1 = torch.stack([self.moe_mlp1[i](x) for i in range(self.n_experts)],dim=-1) # B, T1, C, m x_moe1 = (gate_score*x_moe1).sum(dim=-1,keepdim=False) x = x + self.ln3(x_moe1) x = x + self.resid_drop2(self.selfattn(self.ln4(x))) x_moe2 = torch.stack([self.moe_mlp2[i](x) for i in range(self.n_experts)],dim=-1) # B, T1, C, m x_moe2 = (gate_score*x_moe2).sum(dim=-1,keepdim=False) x = x + self.ln5(x_moe2) return x #### No layernorm # def forward(self, x, y): # # y = self.selfattn_branch(self.ln5(y)) # x = x + self.resid_drop1(self.crossattn(x, y)) # x = x + self.mlp1(x) # x = x + self.resid_drop2(self.selfattn(x)) # x = x + self.mlp2(x) # # return x ''' Cross Attention GPT neural operator Trunck Net: geom ''' class GNOT(nn.Module): def __init__(self, trunk_size=2, branch_sizes=None, space_dim=2, output_size=3, n_layers=2, n_hidden=64, n_head=1, n_experts = 2, n_inner = 4, mlp_layers=2, attn_type='linear', act = 'gelu', ffn_dropout=0.0, attn_dropout=0.0, horiz_fourier_dim = 0, ): super(GNOT, self).__init__() self.horiz_fourier_dim = horiz_fourier_dim self.trunk_size = trunk_size * (4*horiz_fourier_dim + 3) if horiz_fourier_dim>0 else trunk_size self.branch_sizes = [bsize * (4*horiz_fourier_dim + 3) for bsize in branch_sizes] if horiz_fourier_dim > 0 else branch_sizes self.n_inputs = len(self.branch_sizes) self.output_size = output_size self.space_dim = space_dim self.gpt_config = MoEGPTConfig(attn_type=attn_type,embd_pdrop=ffn_dropout, resid_pdrop=ffn_dropout, attn_pdrop=attn_dropout,n_embd=n_hidden, n_head=n_head, n_layer=n_layers, block_size=128,act=act, n_experts=n_experts,space_dim=space_dim, branch_sizes=branch_sizes,n_inputs=len(branch_sizes),n_inner=n_inner) self.trunk_mlp = MLP(self.trunk_size, n_hidden, n_hidden, n_layers=mlp_layers,act=act) self.branch_mlps = nn.ModuleList([MLP(bsize, n_hidden, n_hidden, n_layers=mlp_layers,act=act) for bsize in self.branch_sizes]) self.blocks = nn.Sequential(*[MIOECrossAttentionBlock(self.gpt_config) for _ in range(self.gpt_config.n_layer)]) self.out_mlp = MLP(n_hidden, n_hidden, output_size, n_layers=mlp_layers) # self.apply(self._init_weights) self.__name__ = 'MIOEGPT' def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=0.0002) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def forward(self, g, u_p, inputs): gs = dgl.unbatch(g) x = pad_sequence([_g.ndata['x'] for _g in gs]).permute(1, 0, 2) # B, T1, F pos = x[:,:,0:self.space_dim] x = torch.cat([x, u_p.unsqueeze(1).repeat([1, x.shape[1], 1])], dim=-1) # if self.horiz_fourier_dim > 0: # x = horizontal_fourier_embedding(x, self.horiz_fourier_dim) # z = horizontal_fourier_embedding(z, self.horiz_fourier_dim) x = self.trunk_mlp(x) z = MultipleTensors([self.branch_mlps[i](inputs[i]) for i in range(self.n_inputs)]) for block in self.blocks: x = block(x, z, pos) x = self.out_mlp(x) x_out = torch.cat([x[i, :num] for i, num in enumerate(g.batch_num_nodes())],dim=0) return x_out
12,578
36.4375
214
py
GNOT
GNOT-master/models/optimizer.py
import math import torch from torch import Tensor from typing import List, Optional from torch.optim.optimizer import Optimizer def adam(params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_avg_sqs: List[Tensor], max_exp_avg_sqs: List[Tensor], state_steps: List[int], *, amsgrad: bool, beta1: float, beta2: float, lr: float, weight_decay: float, eps: float): r"""Functional API that performs Adam algorithm computation. See :class:`~torch.optim.Adam` for details. """ for i, param in enumerate(params): grad = grads[i] exp_avg = exp_avgs[i] exp_avg_sq = exp_avg_sqs[i] step = state_steps[i] bias_correction1 = 1 - beta1 ** step bias_correction2 = 1 - beta2 ** step if weight_decay != 0: grad = grad.add(param, alpha=weight_decay) # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) exp_avg_sq.mul_(beta2).addcmul_(grad, grad.conj(), value=1 - beta2) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.maximum(max_exp_avg_sqs[i], exp_avg_sq, out=max_exp_avg_sqs[i]) # Use the max. for normalizing running avg. of gradient denom = (max_exp_avg_sqs[i].sqrt() / math.sqrt(bias_correction2)).add_(eps) else: denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps) step_size = lr / bias_correction1 param.addcdiv_(exp_avg, denom, value=-step_size) class Adam(Optimizer): r"""Implements Adam algorithm. It has been proposed in `Adam: A Method for Stochastic Optimization`_. The implementation of the L2 penalty follows changes proposed in `Decoupled Weight Decay Regularization`_. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _Decoupled Weight Decay Regularization: https://arxiv.org/abs/1711.05101 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(Adam, self).__init__(params, defaults) def __setstate__(self, state): super(Adam, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] grads = [] exp_avgs = [] exp_avg_sqs = [] max_exp_avg_sqs = [] state_steps = [] beta1, beta2 = group['betas'] for p in group['params']: if p.grad is not None: params_with_grad.append(p) if p.grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') grads.append(p.grad) state = self.state[p] # Lazy state initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) if group['amsgrad']: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avgs.append(state['exp_avg']) exp_avg_sqs.append(state['exp_avg_sq']) if group['amsgrad']: max_exp_avg_sqs.append(state['max_exp_avg_sq']) # update the steps for each param group update state['step'] += 1 # record the step after step update state_steps.append(state['step']) adam(params_with_grad, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, amsgrad=group['amsgrad'], beta1=beta1, beta2=beta2, lr=group['lr'], weight_decay=group['weight_decay'], eps=group['eps']) return loss def adamw(params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_avg_sqs: List[Tensor], max_exp_avg_sqs: List[Tensor], state_steps: List[int], *, amsgrad: bool, beta1: float, beta2: float, lr: float, weight_decay: float, eps: float): r"""Functional API that performs AdamW algorithm computation. See :class:`~torch.optim.AdamW` for details. """ for i, param in enumerate(params): grad = grads[i] exp_avg = exp_avgs[i] exp_avg_sq = exp_avg_sqs[i] step = state_steps[i] # Perform stepweight decay param.mul_(1 - lr * weight_decay) bias_correction1 = 1 - beta1 ** step bias_correction2 = 1 - beta2 ** step # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) exp_avg_sq.mul_(beta2).addcmul_(grad, grad.conj(), value=1 - beta2) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.maximum(max_exp_avg_sqs[i], exp_avg_sq, out=max_exp_avg_sqs[i]) # Use the max. for normalizing running avg. of gradient denom = (max_exp_avg_sqs[i].sqrt() / math.sqrt(bias_correction2)).add_(eps) else: denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps) step_size = lr / bias_correction1 param.addcdiv_(exp_avg, denom, value=-step_size) class AdamW(Optimizer): r"""Implements AdamW algorithm. The original Adam algorithm was proposed in `Adam: A Method for Stochastic Optimization`_. The AdamW variant was proposed in `Decoupled Weight Decay Regularization`_. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay coefficient (default: 1e-2) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _Decoupled Weight Decay Regularization: https://arxiv.org/abs/1711.05101 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-2, amsgrad=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(AdamW, self).__init__(params, defaults) def __setstate__(self, state): super(AdamW, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] grads = [] exp_avgs = [] exp_avg_sqs = [] state_sums = [] max_exp_avg_sqs = [] state_steps = [] amsgrad = group['amsgrad'] beta1, beta2 = group['betas'] for p in group['params']: if p.grad is None: continue params_with_grad.append(p) if p.grad.is_sparse: raise RuntimeError('AdamW does not support sparse gradients') grads.append(p.grad) state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avgs.append(state['exp_avg']) exp_avg_sqs.append(state['exp_avg_sq']) if amsgrad: max_exp_avg_sqs.append(state['max_exp_avg_sq']) # update the steps for each param group update state['step'] += 1 # record the step after step update state_steps.append(state['step']) adamw(params_with_grad, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, amsgrad=amsgrad, beta1=beta1, beta2=beta2, lr=group['lr'], weight_decay=group['weight_decay'], eps=group['eps']) return loss
12,976
37.853293
120
py
GNOT
GNOT-master/resources/__init__.py
#!/usr/bin/env python #-*- coding:utf-8 _*-
46
14.666667
23
py
F3Net
F3Net-master/README.md
## [F3Net: Fusion, Feedback and Focus for Salient Object Detection](https://arxiv.org/pdf/1911.11445.pdf) by Jun Wei, Shuhui Wang, Qingming Huang ## Introduction ![framework](./fig/framework.png)Most of existing salient object detection models have achieved great progress by aggregating multi-level features extracted from convolutional neural networks. However, because of the different receptive fields of different convolutional layers, there exists big differences between features generated by these layers. Common feature fusion strategies (addition or concatenation) ignore these differences and may cause suboptimal solutions. In this paper, we propose the F3Net to solve above problem, which mainly consists of cross feature module (CFM) and cascaded feedback decoder (CFD) trained by minimizing a new pixel position aware loss (PPA). Specifically, CFM aims to selectively aggregate multi-level features. Different from addition and concatenation, CFM adaptively selects complementary components from input features before fusion, which can effectively avoid introducing too much redundant information that may destroy the original features. Besides, CFD adopts a multi-stage feedback mechanism, where features closed to supervision will be introduced to the output of previous layers to supplement them and eliminate the differences between features. These refined features will go through multiple similar iterations before generating the final saliency maps. Furthermore, different from binary cross entropy, the proposed PPA loss doesn’t treat pixels equally, which can synthesize the local structure information of a pixel to guide the network to focus more on local details. Hard pixels from boundaries or error-prone parts will be given more attention to emphasize their importance. F3Net is able to segment salient object regions accurately and provide clear local details. Comprehensive experiments on five benchmark datasets demonstrate that F3Net outperforms state-of-the-art approaches on six evaluation metrics. ## Prerequisites - [Python 3.5](https://www.python.org/) - [Pytorch 1.3](http://pytorch.org/) - [OpenCV 4.0](https://opencv.org/) - [Numpy 1.15](https://numpy.org/) - [TensorboardX](https://github.com/lanpa/tensorboardX) - [Apex](https://github.com/NVIDIA/apex) ## Clone repository ```shell git clone [email protected]:weijun88/F3Net.git cd F3Net/ ``` ## Download dataset Download the following datasets and unzip them into `data` folder - [PASCAL-S](http://cbi.gatech.edu/salobj/) - [ECSSD](http://www.cse.cuhk.edu.hk/leojia/projects/hsaliency/dataset.html) - [HKU-IS](https://i.cs.hku.hk/~gbli/deep_saliency.html) - [DUT-OMRON](http://saliencydetection.net/dut-omron/) - [DUTS](http://saliencydetection.net/duts/) ## Download model - If you want to test the performance of F3Net, please download the [model](https://drive.google.com/file/d/1jcsmxZHL6DGwDplLp93H4VeN2ZjqBsOF/view?usp=sharing) into `out` folder - If you want to train your own model, please download the [pretrained model](https://download.pytorch.org/models/resnet50-19c8e357.pth) into `res` folder ## Training ```shell cd src/ python3 train.py ``` - `ResNet-50` is used as the backbone of F3Net and `DUTS-TR` is used to train the model - `batch=32`, `lr=0.05`, `momen=0.9`, `decay=5e-4`, `epoch=32` - Warm-up and linear decay strategies are used to change the learning rate `lr` - After training, the result models will be saved in `out` folder ## Testing ```shell cd src python3 test.py ``` - After testing, saliency maps of `PASCAL-S`, `ECSSD`, `HKU-IS`, `DUT-OMRON`, `DUTS-TE` will be saved in `eval/F3Net/` folder. ## Saliency maps & Trained model - saliency maps: [Baidu](https://pan.baidu.com/s/1ZIfZ90FoqlrSdoD31Lul5g) [Google](https://drive.google.com/file/d/1FfZtzfSX6-hlwar4yJYLuGogGbLW9sYe/view?usp=sharing) - trained model: [Baidu](https://pan.baidu.com/s/1qlqiCG0d9o2wH8ddeVJsSQ) [Google](https://drive.google.com/file/d/1jcsmxZHL6DGwDplLp93H4VeN2ZjqBsOF/view?usp=sharing) ## Evaluation - To evaluate the performace of F3Net, please use MATLAB to run `main.m` ```shell cd eval matlab main ``` - Quantitative comparisons ![performace](./fig/table.png) - Qualitative comparisons ![sample](./fig/case.png) ## Citation - If you find this work is helpful, please cite our paper ``` @inproceedings{F3Net, title = {F3Net: Fusion, Feedback and Focus for Salient Object Detection}, author = {Jun Wei, Shuhui Wang, Qingming Huang}, booktitle = {AAAI Conference on Artificial Intelligence (AAAI)}, year = {2020} } ```
4,590
53.011765
1,872
md
F3Net
F3Net-master/eval/Emeasure.m
function [score]= Emeasure(FM,GT) % Emeasure Compute the Enhanced Alignment measure (as proposed in "Enhanced-alignment % Measure for Binary Foreground Map Evaluation" [Deng-Ping Fan et. al - IJCAI'18 oral paper]) % Usage: % score = Emeasure(FM,GT) % Input: % FM - Binary foreground map. Type: double. % GT - Binary ground truth. Type: double. % Output: % score - The Enhanced alignment score %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Important Note:%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %The code is for academic purposes only. Please cite this paper if you make use of it: %@conference{Fan2018Enhanced, title={Enhanced-alignment Measure for Binary Foreground Map Evaluation}, % author={Fan, Deng-Ping and Gong, Cheng and Cao, Yang and Ren, Bo and Cheng, Ming-Ming and Borji, Ali}, % year = {2018}, % booktitle = {IJCAI} % } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FM = mat2gray(FM); thd = 2 * mean(FM(:)); FM = FM > thd; % if thd>1: % thd=1; % end FM = logical(FM); GT = logical(GT); %Use double for computations. dFM = double(FM); dGT = double(GT); %Special case: if (sum(dGT(:))==0)% if the GT is completely black enhanced_matrix = 1.0 - dFM; %only calculate the black area of intersection elseif(sum(~dGT(:))==0)%if the GT is completely white enhanced_matrix = dFM; %only calcualte the white area of intersection else %Normal case: %1.compute alignment matrix align_matrix = AlignmentTerm(dFM,dGT); %2.compute enhanced alignment matrix enhanced_matrix = EnhancedAlignmentTerm(align_matrix); end %3.Emeasure score [w,h] = size(GT); score = sum(enhanced_matrix(:))./(w*h - 1 + eps); end % Alignment Term function [align_Matrix] = AlignmentTerm(dFM,dGT) %compute global mean mu_FM = mean2(dFM); mu_GT = mean2(dGT); %compute the bias matrix align_FM = dFM - mu_FM; align_GT = dGT - mu_GT; %compute alignment matrix align_Matrix = 2.*(align_GT.*align_FM)./(align_GT.*align_GT + align_FM.*align_FM + eps); end % Enhanced Alignment Term function. f(x) = 1/4*(1 + x)^2) function enhanced = EnhancedAlignmentTerm(align_Matrix) enhanced = ((align_Matrix + 1).^2)/4; end
2,267
29.24
118
m
F3Net
F3Net-master/eval/Fmeasure.m
%% function [PreFtem, RecallFtem, FmeasureF] = Fmeasure(sMap, gtMap, gtsize) sumLabel = 2* mean(sMap(:)); if (sumLabel > 1) sumLabel = 1; end Label3 = zeros( gtsize ); Label3(sMap>=sumLabel ) = 1; NumRec = length( find( Label3==1 ) ); LabelAnd = Label3 & gtMap; NumAnd = length( find ( LabelAnd==1 ) ); num_obj = sum(sum(gtMap)); if NumAnd == 0 PreFtem = 0; RecallFtem = 0; FmeasureF = 0; else PreFtem = NumAnd/NumRec; RecallFtem = NumAnd/num_obj; FmeasureF = ((1.3*PreFtem*RecallFtem)/(0.3*PreFtem+RecallFtem)); end
564
19.178571
73
m
F3Net
F3Net-master/eval/MAE.m
function mae = MAE(smap, gtImg) % Code Author: Wangjiang Zhu % Email: [email protected] % Date: 3/24/2014 if size(smap, 1) ~= size(gtImg, 1) || size(smap, 2) ~= size(gtImg, 2) error('Saliency map and gt Image have different sizes!\n'); end if ~islogical(gtImg) gtImg = gtImg(:,:,1) > 128; end fgPixels = smap(gtImg); fgErrSum = length(fgPixels) - sum(fgPixels); bgErrSum = sum(smap(~gtImg)); mae = (fgErrSum + bgErrSum) / numel(gtImg);
457
27.625
69
m
F3Net
F3Net-master/eval/PRCurve.m
function [precision, recall] = PRCurve(smapImg, gtImg) % Code Author: Wangjiang Zhu % Email: [email protected] % Date: 3/24/2014 if ~islogical(gtImg) gtImg = gtImg(:,:,1) > 128; end if any(size(smapImg) ~= size(gtImg)) error('saliency map and ground truth mask have different size'); end gtPxlNum = sum(gtImg(:)); if 0 == gtPxlNum error('no foreground region is labeled'); end targetHist = histc(smapImg(gtImg), 0:255); nontargetHist = histc(smapImg(~gtImg), 0:255); targetHist = flipud(targetHist); nontargetHist = flipud(nontargetHist); targetHist = cumsum( targetHist ); nontargetHist = cumsum( nontargetHist ); precision = targetHist ./ (targetHist + nontargetHist + eps); if any(isnan(precision)) warning('there exists NAN in precision, this is because your saliency map do not range from 0 to 255\n'); end recall = targetHist / gtPxlNum;
874
26.34375
110
m
F3Net
F3Net-master/eval/S_object.m
function Q = S_object(prediction,GT) % S_object Computes the object similarity between foreground maps and ground % truth(as proposed in "Structure-measure:A new way to evaluate foreground % maps" [Deng-Ping Fan et. al - ICCV 2017]) % Usage: % Q = S_object(prediction,GT) % Input: % prediction - Binary/Non binary foreground map with values in the range % [0 1]. Type: double. % GT - Binary ground truth. Type: logical. % Output: % Q - The object similarity score %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the similarity of the foreground in the object level prediction_fg = prediction; prediction_fg(~GT)=0; O_FG = Object(prediction_fg,GT); % compute the similarity of the background prediction_bg = 1.0 - prediction; prediction_bg(GT) = 0; O_BG = Object(prediction_bg,~GT); % combine the foreground measure and background measure together u = mean2(GT); Q = u * O_FG + (1 - u) * O_BG; end function score = Object(prediction,GT) % check the input if isempty(prediction) score = 0; return; end if isinteger(prediction) prediction = double(prediction); end if (~isa( prediction, 'double' )) error('prediction should be of type: double'); end if ((max(prediction(:))>1) || min(prediction(:))<0) error('prediction should be in the range of [0 1]'); end if(~islogical(GT)) error('GT should be of type: logical'); end % compute the mean of the foreground or background in prediction x = mean2(prediction(GT)); % compute the standard deviations of the foreground or background in prediction sigma_x = std(prediction(GT)); score = 2.0 * x./(x^2 + 1.0 + sigma_x + eps); end
1,667
27.758621
79
m
F3Net
F3Net-master/eval/S_region.m
function Q = S_region(prediction,GT) % S_region computes the region similarity between the foreground map and % ground truth(as proposed in "Structure-measure:A new way to evaluate % foreground maps" [Deng-Ping Fan et. al - ICCV 2017]) % Usage: % Q = S_region(prediction,GT) % Input: % prediction - Binary/Non binary foreground map with values in the range % [0 1]. Type: double. % GT - Binary ground truth. Type: logical. % Output: % Q - The region similarity score %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the centroid of the GT [X,Y] = centroid(GT); % divide GT into 4 regions [GT_1,GT_2,GT_3,GT_4,w1,w2,w3,w4] = divideGT(GT,X,Y); %Divede prediction into 4 regions [prediction_1,prediction_2,prediction_3,prediction_4] = Divideprediction(prediction,X,Y); %Compute the ssim score for each regions Q1 = ssim(prediction_1,GT_1); Q2 = ssim(prediction_2,GT_2); Q3 = ssim(prediction_3,GT_3); Q4 = ssim(prediction_4,GT_4); %Sum the 4 scores Q = w1 * Q1 + w2 * Q2 + w3 * Q3 + w4 * Q4; end function [X,Y] = centroid(GT) % Centroid Compute the centroid of the GT % Usage: % [X,Y] = Centroid(GT) % Input: % GT - Binary ground truth. Type: logical. % Output: % [X,Y] - The coordinates of centroid. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [rows,cols] = size(GT); if(sum(GT(:))==0) X = round(cols/2); Y = round(rows/2); else dGT = double(GT); x = ones(rows,1)*(1:cols); y = (1:rows)'*ones(1,cols); area = sum(dGT(:)); X = round(sum(sum(dGT.*x))/area); Y = round(sum(sum(dGT.*y))/area); end end % divide the GT into 4 regions according to the centroid of the GT and return the weights function [LT,RT,LB,RB,w1,w2,w3,w4] = divideGT(GT,X,Y) % LT - left top; % RT - right top; % LB - left bottom; % RB - right bottom; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %width and height of the GT [hei,wid] = size(GT); area = wid * hei; %copy the 4 regions LT = GT(1:Y,1:X); RT = GT(1:Y,X+1:wid); LB = GT(Y+1:hei,1:X); RB = GT(Y+1:hei,X+1:wid); %The different weight (each block proportional to the GT foreground region). w1 = (X*Y)./area; w2 = ((wid-X)*Y)./area; w3 = (X*(hei-Y))./area; w4 = 1.0 - w1 - w2 - w3; end %Divide the prediction into 4 regions according to the centroid of the GT function [LT,RT,LB,RB] = Divideprediction(prediction,X,Y) %width and height of the prediction [hei,wid] = size(prediction); %copy the 4 regions LT = prediction(1:Y,1:X); RT = prediction(1:Y,X+1:wid); LB = prediction(Y+1:hei,1:X); RB = prediction(Y+1:hei,X+1:wid); end function Q = ssim(prediction,GT) % ssim computes the region similarity between foreground maps and ground % truth(as proposed in "Structure-measure: A new way to evaluate foreground % maps" [Deng-Ping Fan et. al - ICCV 2017]) % Usage: % Q = ssim(prediction,GT) % Input: % prediction - Binary/Non binary foreground map with values in the range % [0 1]. Type: double. % GT - Binary ground truth. Type: logical. % Output: % Q - The region similarity score %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dGT = double(GT); [hei,wid] = size(prediction); N = wid*hei; %Compute the mean of SM,GT x = mean2(prediction); y = mean2(dGT); %Compute the variance of SM,GT sigma_x2 = sum(sum((prediction - x).^2))./(N - 1 + eps); sigma_y2 = sum(sum((dGT - y).^2))./(N - 1 + eps); %Compute the covariance between SM and GT sigma_xy = sum(sum((prediction - x).*(dGT - y)))./(N - 1 + eps); alpha = 4 * x * y * sigma_xy; beta = (x.^2 + y.^2).*(sigma_x2 + sigma_y2); if(alpha ~= 0) Q = alpha./(beta + eps); elseif(alpha == 0 && beta == 0) Q = 1.0; else Q = 0; end end
3,681
24.929577
89
m
F3Net
F3Net-master/eval/Smeasure.m
function Q = Smeasure(prediction,GT) % Smeasure computes the similarity between the foreground map and % ground truth(as proposed in "Structure-measure: A new way to evaluate % foreground maps" [Deng-Ping Fan et. al - ICCV 2017]) % Usage: % Q = Smeasure(prediction,GT) % Input: % prediction - Binary/Non binary foreground map with values in the range % [0 1]. Type: double. % GT - Binary ground truth. Type: logical. % Output: % Q - The computed similarity score %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check input if (~isa(prediction,'double')) error('The prediction should be double type...'); end if ((max(prediction(:))>1) || min(prediction(:))<0) error('The prediction should be in the range of [0 1]...'); end if (~islogical(GT)) error('GT should be logical type...'); end y = mean2(GT); if (y==0)% if the GT is completely black x = mean2(prediction); Q = 1.0 - x; %only calculate the area of intersection elseif(y==1)%if the GT is completely white x = mean2(prediction); Q = x; %only calcualte the area of intersection else alpha = 0.5; Q = alpha*S_object(prediction,GT)+(1-alpha)*S_region(prediction,GT); end end
1,222
30.358974
75
m
F3Net
F3Net-master/eval/main.m
algorithms = { %'C2SNet'; %'BMPM'; %'DGRL'; %'R3Net'; %'RAS'; %'PiCA-R'; %'PAGE'; %'TDBU'; %'BASNet'; %'CPD-R'; %'PoolNet'; %'AFNet'; 'F3Net' }; datasets = { 'ECSSD'; 'PASCAL-S'; 'DUTS'; 'HKU-IS'; 'DUT-OMRON'; %'THUR15K'; }; for i = 1:numel(algorithms) alg = algorithms{i}; fprintf('The method is %s\n', alg); for j = 1:numel(datasets) dataset = datasets{j}; predpath = ['./maps/' alg '/' dataset '/']; maskpath = ['../data/' dataset '/mask/']; if ~exist(predpath, 'dir'), continue; end names = dir(['./maps/' alg '/' dataset '/*.png']); names = {names.name}'; wfm = 0; mae = 0; sm = 0; fm = 0; prec = 0; rec = 0; em = 0; score1 = 0; score2 = 0; score3 = 0; score4 = 0; score5 = 0; score6 = 0; score7 = 0; results = cell(numel(names), 6); ALLPRECISION = zeros(numel(names), 256); ALLRECALL = zeros(numel(names), 256); file_num = false(numel(names), 1); for k = 1:numel(names) name = names{k,1}; results{k, 1} = name; file_num(k) = true; fgpath = [predpath name]; fg = imread(fgpath); if strcmp(alg, 'PoolNet') gtpath = [maskpath strrep(name, '_sal_fuse.', '.')]; elseif strcmp(alg, 'C2SNet') gtpath = [maskpath strrep(name, '_10k.', '.')]; else gtpath = [maskpath name]; end gt = imread(gtpath); if length(size(fg)) == 3, fg = fg(:,:,1); end if length(size(gt)) == 3, gt = gt(:,:,1); end fg = imresize(fg, size(gt)); fg = mat2gray(fg); gt = mat2gray(gt); if max(fg(:)) == 0 || max(gt(:)) == 0, continue; end gt(gt>=0.5) = 1; gt(gt<0.5) = 0; gt = logical(gt); score1 = MAE(fg, gt); [score2, score3, score4] = Fmeasure(fg, gt, size(gt)); score5 = wFmeasure(fg, gt); score6 = Smeasure(fg, gt); score7 = Emeasure(fg, gt); mae = mae + score1; prec = prec + score2; rec = rec + score3; fm = fm + score4; wfm = wfm + score5; sm = sm + score6; em = em + score7; results{k, 2} = score1; results{k, 3} = score4; results{k, 4} = score5; results{k, 5} = score6; results{k, 6} = score7; [precision, recall] = PRCurve(fg*255, gt); ALLPRECISION(k, :) = precision; ALLRECALL(k, :) = recall; end prec = mean(ALLPRECISION(file_num,:), 1); rec = mean(ALLRECALL(file_num,:), 1); maxF = max(1.3*prec.*rec./(0.3*prec+rec+eps)); file_num = double(file_num); fm = fm / sum(file_num); mae = mae / sum(file_num); wfm = wfm / sum(file_num); sm = sm / sum(file_num); em = em / sum(file_num); fprintf('%s: %6.3f, %6.3f, %6.3f, %6.3f, %6.3f, %6.3f\n', dataset, maxF, fm, mae, wfm, sm, em) save_path = ['./result' filesep alg filesep dataset filesep]; if ~exist(save_path, 'dir'), mkdir(save_path); end save([save_path 'results.mat'], 'results'); save([save_path 'prec.mat'], 'prec'); save([save_path 'rec.mat'], 'rec'); end end
3,979
35.851852
102
m
F3Net
F3Net-master/eval/wFmeasure.m
function [Q]= wFmeasure(FG,GT) % wFmeasure Compute the Weighted F-beta measure (as proposed in "How to Evaluate Foreground Maps?" [Margolin et. al - CVPR'14]) % Usage: % Q = FbW(FG,GT) % Input: % FG - Binary/Non binary foreground map with values in the range [0 1]. Type: double. % GT - Binary ground truth. Type: logical. % Output: % Q - The Weighted F-beta score %Check input if (~isa( FG, 'double' )) error('FG should be of type: double'); end if ((max(FG(:))>1) || min(FG(:))<0) error('FG should be in the range of [0 1]'); end if (~islogical(GT)) error('GT should be of type: logical'); end % GT(GT>=0.5) = 1; GT(GT<0.5) = 0; GT = logical(GT); dGT = double(GT); %Use double for computations. if max(dGT(:)) == 0 Q = 0; return end E = abs(FG-dGT); % [Ef, Et, Er] = deal(abs(FG-GT)); [Dst,IDXT] = bwdist(dGT); %Pixel dependency K = fspecial('gaussian',7,5); Et = E; Et(~GT)=Et(IDXT(~GT)); %To deal correctly with the edges of the foreground region EA = imfilter(Et,K); MIN_E_EA = E; MIN_E_EA(GT & EA<E) = EA(GT & EA<E); %Pixel importance B = ones(size(GT)); B(~GT) = 2-1*exp(log(1-0.5)/5.*Dst(~GT)); Ew = MIN_E_EA.*B; TPw = sum(dGT(:)) - sum(sum(Ew(GT))); FPw = sum(sum(Ew(~GT))); R = 1- mean2(Ew(GT)); %Weighed Recall P = TPw./(eps+TPw+FPw); %Weighted Precision % Q = 1.3*(R*P)./(eps+R+0.3*P); %Beta=1; Q = (2)*(R*P)./(eps+R+P); %Beta=1; % Q = (1+Beta^2)*(R*P)./(eps+R+(Beta.*P)); end
1,423
25.37037
127
m
F3Net
F3Net-master/src/dataset.py
#!/usr/bin/python3 #coding=utf-8 import os import cv2 import torch import numpy as np from torch.utils.data import Dataset ########################### Data Augmentation ########################### class Normalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, image, mask): image = (image - self.mean)/self.std mask /= 255 return image, mask class RandomCrop(object): def __call__(self, image, mask): H,W,_ = image.shape randw = np.random.randint(W/8) randh = np.random.randint(H/8) offseth = 0 if randh == 0 else np.random.randint(randh) offsetw = 0 if randw == 0 else np.random.randint(randw) p0, p1, p2, p3 = offseth, H+offseth-randh, offsetw, W+offsetw-randw return image[p0:p1,p2:p3, :], mask[p0:p1,p2:p3] class RandomFlip(object): def __call__(self, image, mask): if np.random.randint(2)==0: return image[:,::-1,:], mask[:, ::-1] else: return image, mask class Resize(object): def __init__(self, H, W): self.H = H self.W = W def __call__(self, image, mask): image = cv2.resize(image, dsize=(self.W, self.H), interpolation=cv2.INTER_LINEAR) mask = cv2.resize( mask, dsize=(self.W, self.H), interpolation=cv2.INTER_LINEAR) return image, mask class ToTensor(object): def __call__(self, image, mask): image = torch.from_numpy(image) image = image.permute(2, 0, 1) mask = torch.from_numpy(mask) return image, mask ########################### Config File ########################### class Config(object): def __init__(self, **kwargs): self.kwargs = kwargs self.mean = np.array([[[124.55, 118.90, 102.94]]]) self.std = np.array([[[ 56.77, 55.97, 57.50]]]) print('\nParameters...') for k, v in self.kwargs.items(): print('%-10s: %s'%(k, v)) def __getattr__(self, name): if name in self.kwargs: return self.kwargs[name] else: return None ########################### Dataset Class ########################### class Data(Dataset): def __init__(self, cfg): self.cfg = cfg self.normalize = Normalize(mean=cfg.mean, std=cfg.std) self.randomcrop = RandomCrop() self.randomflip = RandomFlip() self.resize = Resize(352, 352) self.totensor = ToTensor() with open(cfg.datapath+'/'+cfg.mode+'.txt', 'r') as lines: self.samples = [] for line in lines: self.samples.append(line.strip()) def __getitem__(self, idx): name = self.samples[idx] image = cv2.imread(self.cfg.datapath+'/image/'+name+'.jpg')[:,:,::-1].astype(np.float32) mask = cv2.imread(self.cfg.datapath+'/mask/' +name+'.png', 0).astype(np.float32) shape = mask.shape if self.cfg.mode=='train': image, mask = self.normalize(image, mask) image, mask = self.randomcrop(image, mask) image, mask = self.randomflip(image, mask) return image, mask else: image, mask = self.normalize(image, mask) image, mask = self.resize(image, mask) image, mask = self.totensor(image, mask) return image, mask, shape, name def collate(self, batch): size = [224, 256, 288, 320, 352][np.random.randint(0, 5)] image, mask = [list(item) for item in zip(*batch)] for i in range(len(batch)): image[i] = cv2.resize(image[i], dsize=(size, size), interpolation=cv2.INTER_LINEAR) mask[i] = cv2.resize(mask[i], dsize=(size, size), interpolation=cv2.INTER_LINEAR) image = torch.from_numpy(np.stack(image, axis=0)).permute(0,3,1,2) mask = torch.from_numpy(np.stack(mask, axis=0)).unsqueeze(1) return image, mask def __len__(self): return len(self.samples) ########################### Testing Script ########################### if __name__=='__main__': import matplotlib.pyplot as plt plt.ion() cfg = Config(mode='train', datapath='../data/DUTS') data = Data(cfg) for i in range(1000): image, mask = data[i] image = image*cfg.std + cfg.mean plt.subplot(121) plt.imshow(np.uint8(image)) plt.subplot(122) plt.imshow(mask) input()
4,497
32.819549
96
py
F3Net
F3Net-master/src/net.py
#!/usr/bin/python3 #coding=utf-8 import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F def weight_init(module): for n, m in module.named_children(): print('initialize: '+n) if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu') if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d)): nn.init.ones_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu') if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Sequential): weight_init(m) elif isinstance(m, nn.ReLU): pass else: m.initialize() class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=(3*dilation-1)//2, bias=False, dilation=dilation) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes*4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes*4) self.downsample = downsample def forward(self, x): out = F.relu(self.bn1(self.conv1(x)), inplace=True) out = F.relu(self.bn2(self.conv2(out)), inplace=True) out = self.bn3(self.conv3(out)) if self.downsample is not None: x = self.downsample(x) return F.relu(out+x, inplace=True) class ResNet(nn.Module): def __init__(self): super(ResNet, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self.make_layer( 64, 3, stride=1, dilation=1) self.layer2 = self.make_layer(128, 4, stride=2, dilation=1) self.layer3 = self.make_layer(256, 6, stride=2, dilation=1) self.layer4 = self.make_layer(512, 3, stride=2, dilation=1) def make_layer(self, planes, blocks, stride, dilation): downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes*4, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes*4)) layers = [Bottleneck(self.inplanes, planes, stride, downsample, dilation=dilation)] self.inplanes = planes*4 for _ in range(1, blocks): layers.append(Bottleneck(self.inplanes, planes, dilation=dilation)) return nn.Sequential(*layers) def forward(self, x): out1 = F.relu(self.bn1(self.conv1(x)), inplace=True) out1 = F.max_pool2d(out1, kernel_size=3, stride=2, padding=1) out2 = self.layer1(out1) out3 = self.layer2(out2) out4 = self.layer3(out3) out5 = self.layer4(out4) return out2, out3, out4, out5 def initialize(self): self.load_state_dict(torch.load('../res/resnet50-19c8e357.pth'), strict=False) class CFM(nn.Module): def __init__(self): super(CFM, self).__init__() self.conv1h = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn1h = nn.BatchNorm2d(64) self.conv2h = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn2h = nn.BatchNorm2d(64) self.conv3h = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn3h = nn.BatchNorm2d(64) self.conv4h = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn4h = nn.BatchNorm2d(64) self.conv1v = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn1v = nn.BatchNorm2d(64) self.conv2v = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn2v = nn.BatchNorm2d(64) self.conv3v = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn3v = nn.BatchNorm2d(64) self.conv4v = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.bn4v = nn.BatchNorm2d(64) def forward(self, left, down): if down.size()[2:] != left.size()[2:]: down = F.interpolate(down, size=left.size()[2:], mode='bilinear') out1h = F.relu(self.bn1h(self.conv1h(left )), inplace=True) out2h = F.relu(self.bn2h(self.conv2h(out1h)), inplace=True) out1v = F.relu(self.bn1v(self.conv1v(down )), inplace=True) out2v = F.relu(self.bn2v(self.conv2v(out1v)), inplace=True) fuse = out2h*out2v out3h = F.relu(self.bn3h(self.conv3h(fuse )), inplace=True)+out1h out4h = F.relu(self.bn4h(self.conv4h(out3h)), inplace=True) out3v = F.relu(self.bn3v(self.conv3v(fuse )), inplace=True)+out1v out4v = F.relu(self.bn4v(self.conv4v(out3v)), inplace=True) return out4h, out4v def initialize(self): weight_init(self) class Decoder(nn.Module): def __init__(self): super(Decoder, self).__init__() self.cfm45 = CFM() self.cfm34 = CFM() self.cfm23 = CFM() def forward(self, out2h, out3h, out4h, out5v, fback=None): if fback is not None: refine5 = F.interpolate(fback, size=out5v.size()[2:], mode='bilinear') refine4 = F.interpolate(fback, size=out4h.size()[2:], mode='bilinear') refine3 = F.interpolate(fback, size=out3h.size()[2:], mode='bilinear') refine2 = F.interpolate(fback, size=out2h.size()[2:], mode='bilinear') out5v = out5v+refine5 out4h, out4v = self.cfm45(out4h+refine4, out5v) out3h, out3v = self.cfm34(out3h+refine3, out4v) out2h, pred = self.cfm23(out2h+refine2, out3v) else: out4h, out4v = self.cfm45(out4h, out5v) out3h, out3v = self.cfm34(out3h, out4v) out2h, pred = self.cfm23(out2h, out3v) return out2h, out3h, out4h, out5v, pred def initialize(self): weight_init(self) class F3Net(nn.Module): def __init__(self, cfg): super(F3Net, self).__init__() self.cfg = cfg self.bkbone = ResNet() self.squeeze5 = nn.Sequential(nn.Conv2d(2048, 64, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.squeeze4 = nn.Sequential(nn.Conv2d(1024, 64, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.squeeze3 = nn.Sequential(nn.Conv2d( 512, 64, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.squeeze2 = nn.Sequential(nn.Conv2d( 256, 64, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.decoder1 = Decoder() self.decoder2 = Decoder() self.linearp1 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.linearp2 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.linearr2 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.linearr3 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.linearr4 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.linearr5 = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1) self.initialize() def forward(self, x, shape=None): out2h, out3h, out4h, out5v = self.bkbone(x) out2h, out3h, out4h, out5v = self.squeeze2(out2h), self.squeeze3(out3h), self.squeeze4(out4h), self.squeeze5(out5v) out2h, out3h, out4h, out5v, pred1 = self.decoder1(out2h, out3h, out4h, out5v) out2h, out3h, out4h, out5v, pred2 = self.decoder2(out2h, out3h, out4h, out5v, pred1) shape = x.size()[2:] if shape is None else shape pred1 = F.interpolate(self.linearp1(pred1), size=shape, mode='bilinear') pred2 = F.interpolate(self.linearp2(pred2), size=shape, mode='bilinear') out2h = F.interpolate(self.linearr2(out2h), size=shape, mode='bilinear') out3h = F.interpolate(self.linearr3(out3h), size=shape, mode='bilinear') out4h = F.interpolate(self.linearr4(out4h), size=shape, mode='bilinear') out5h = F.interpolate(self.linearr5(out5v), size=shape, mode='bilinear') return pred1, pred2, out2h, out3h, out4h, out5h def initialize(self): if self.cfg.snapshot: self.load_state_dict(torch.load(self.cfg.snapshot)) else: weight_init(self)
8,656
43.623711
141
py
F3Net
F3Net-master/src/test.py
#!/usr/bin/python3 #coding=utf-8 import os import sys sys.path.insert(0, '../') sys.dont_write_bytecode = True import cv2 import numpy as np import matplotlib.pyplot as plt plt.ion() import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from tensorboardX import SummaryWriter import dataset from net import F3Net class Test(object): def __init__(self, Dataset, Network, path): ## dataset self.cfg = Dataset.Config(datapath=path, snapshot='./out/model-32', mode='test') self.data = Dataset.Data(self.cfg) self.loader = DataLoader(self.data, batch_size=1, shuffle=False, num_workers=8) ## network self.net = Network(self.cfg) self.net.train(False) self.net.cuda() def show(self): with torch.no_grad(): for image, mask, shape, name in self.loader: image, mask = image.cuda().float(), mask.cuda().float() out1u, out2u, out2r, out3r, out4r, out5r = self.net(image) out = out2u plt.subplot(221) plt.imshow(np.uint8(image[0].permute(1,2,0).cpu().numpy()*self.cfg.std + self.cfg.mean)) plt.subplot(222) plt.imshow(mask[0].cpu().numpy()) plt.subplot(223) plt.imshow(out[0, 0].cpu().numpy()) plt.subplot(224) plt.imshow(torch.sigmoid(out[0, 0]).cpu().numpy()) plt.show() input() def save(self): with torch.no_grad(): for image, mask, shape, name in self.loader: image = image.cuda().float() out1u, out2u, out2r, out3r, out4r, out5r = self.net(image, shape) out = out2u pred = (torch.sigmoid(out[0,0])*255).cpu().numpy() head = '../eval/maps/F3Net/'+ self.cfg.datapath.split('/')[-1] if not os.path.exists(head): os.makedirs(head) cv2.imwrite(head+'/'+name[0]+'.png', np.round(pred)) if __name__=='__main__': for path in ['../data/ECSSD', '../data/PASCAL-S', '../data/DUTS', '../data/HKU-IS', '../data/DUT-OMRON']: t = Test(dataset, F3Net, path) t.save() # t.show()
2,319
32.142857
109
py
F3Net
F3Net-master/src/train.py
#!/usr/bin/python3 #coding=utf-8 import sys import datetime sys.path.insert(0, '../') sys.dont_write_bytecode = True import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from tensorboardX import SummaryWriter import dataset from net import F3Net from apex import amp def structure_loss(pred, mask): weit = 1+5*torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15)-mask) wbce = F.binary_cross_entropy_with_logits(pred, mask, reduce='none') wbce = (weit*wbce).sum(dim=(2,3))/weit.sum(dim=(2,3)) pred = torch.sigmoid(pred) inter = ((pred*mask)*weit).sum(dim=(2,3)) union = ((pred+mask)*weit).sum(dim=(2,3)) wiou = 1-(inter+1)/(union-inter+1) return (wbce+wiou).mean() def train(Dataset, Network): ## dataset cfg = Dataset.Config(datapath='../data/DUTS', savepath='./out', mode='train', batch=32, lr=0.05, momen=0.9, decay=5e-4, epoch=32) data = Dataset.Data(cfg) loader = DataLoader(data, collate_fn=data.collate, batch_size=cfg.batch, shuffle=True, num_workers=8) ## network net = Network(cfg) net.train(True) net.cuda() ## parameter base, head = [], [] for name, param in net.named_parameters(): if 'bkbone.conv1' in name or 'bkbone.bn1' in name: print(name) elif 'bkbone' in name: base.append(param) else: head.append(param) optimizer = torch.optim.SGD([{'params':base}, {'params':head}], lr=cfg.lr, momentum=cfg.momen, weight_decay=cfg.decay, nesterov=True) net, optimizer = amp.initialize(net, optimizer, opt_level='O2') sw = SummaryWriter(cfg.savepath) global_step = 0 for epoch in range(cfg.epoch): optimizer.param_groups[0]['lr'] = (1-abs((epoch+1)/(cfg.epoch+1)*2-1))*cfg.lr*0.1 optimizer.param_groups[1]['lr'] = (1-abs((epoch+1)/(cfg.epoch+1)*2-1))*cfg.lr for step, (image, mask) in enumerate(loader): image, mask = image.cuda().float(), mask.cuda().float() out1u, out2u, out2r, out3r, out4r, out5r = net(image) loss1u = structure_loss(out1u, mask) loss2u = structure_loss(out2u, mask) loss2r = structure_loss(out2r, mask) loss3r = structure_loss(out3r, mask) loss4r = structure_loss(out4r, mask) loss5r = structure_loss(out5r, mask) loss = (loss1u+loss2u)/2+loss2r/2+loss3r/4+loss4r/8+loss5r/16 optimizer.zero_grad() with amp.scale_loss(loss, optimizer) as scale_loss: scale_loss.backward() optimizer.step() ## log global_step += 1 sw.add_scalar('lr' , optimizer.param_groups[0]['lr'], global_step=global_step) sw.add_scalars('loss', {'loss1u':loss1u.item(), 'loss2u':loss2u.item(), 'loss2r':loss2r.item(), 'loss3r':loss3r.item(), 'loss4r':loss4r.item(), 'loss5r':loss5r.item()}, global_step=global_step) if step%10 == 0: print('%s | step:%d/%d/%d | lr=%.6f | loss=%.6f'%(datetime.datetime.now(), global_step, epoch+1, cfg.epoch, optimizer.param_groups[0]['lr'], loss.item())) if epoch>cfg.epoch/3*2: torch.save(net.state_dict(), cfg.savepath+'/model-'+str(epoch+1)) if __name__=='__main__': train(dataset, F3Net)
3,380
38.313953
205
py
null
coax-main/.readthedocs.yml
version: 2 build: image: latest python: version: 3.8 install: - method: pip path: . extra_requirements: - doc system_packages: true sphinx: builder: html configuration: doc/conf.py
210
10.722222
28
yml
null
coax-main/STATUS.md
# Development Status In this file we list the current status of the tests written (and passed). | | docs | unit tests | FrozenLake | CartPole | Pong | Pendulum | LunarLander | Ant | |-----------------|:----:|:----------:|:----------:|:--------:|:----:|:--------:|:-----------:|:---:| | ValueTD | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | Sarsa | ✔ | ✔ | ✔ | ✔ | | | | | | QLearning | ✔ | ✔ | ✔ | | ✔ | | | | | QLearningMode | ✔ | ✔ | ✔ | | ✔ | | | | | DoubleQLearning | ✔ | ✔ | ✔ | | | | | | | ExpectedSarsa | ✔ | ✔ | ✔ | | | | | | | VanillaPG | ✔ | ✔ | ✔ | ✔ | | | | | | DeterministicPG | ✔ | ✔ | ✔ | | | ✔ | | | | PPOClip | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | CrossEntropy | | | | | | | | |
1,324
68.736842
101
md
null
coax-main/setup.py
#!/usr/bin/env python3 import re import os import setuptools from collections import namedtuple PROJECTDIR = os.path.dirname(__file__) RE_VERSION = re.compile( r'^__version__ \= \'(?P<version>(?P<majorminor>\d+\.\d+)\.\d+(?:\w+\d+)?)\'$', re.MULTILINE) DEV_STATUS = { '0.1': 'Development Status :: 1 - Planning', # v0.1 - skeleton '0.2': 'Development Status :: 2 - Pre-Alpha', # v0.2 - some basic functionality '0.3': 'Development Status :: 3 - Alpha', # v0.3 - most functionality '0.4': 'Development Status :: 4 - Beta', # v0.4 - most functionality + doc '1.0': 'Development Status :: 5 - Production/Stable', # v1.0 - most functionality + doc + test '2.0': 'Development Status :: 6 - Mature', # v2.0 - new functionality? } VersionSpec = namedtuple('VersionSpec', 'version majorminor') def get_install_requires(requirements_txt): install_requires = [] with open(os.path.join(PROJECTDIR, requirements_txt)) as f: for line in f: line = line.strip() if line and not line.startswith('#'): install_requires.append(line) return install_requires def get_version_spec(): with open(os.path.join(PROJECTDIR, 'coax', '__init__.py')) as f: version_match = re.search(RE_VERSION, f.read()) assert version_match is not None, "can't parse __version__ from __init__.py" version_spec = VersionSpec(**version_match.groupdict()) return version_spec def get_long_description(): with open(os.path.join(PROJECTDIR, 'README.rst')) as f: return f.read() version_spec = get_version_spec() # main setup kw args setup_kwargs = { 'name': 'coax', 'version': version_spec.version, 'description': "Plug-n-play reinforcement learning with Gymnasium and JAX", 'long_description': get_long_description(), 'author': 'Kristian Holsheimer', 'author_email': '[email protected]', 'url': 'https://coax.readthedocs.io', 'license': 'MIT', 'python_requires': '~=3.6', 'install_requires': get_install_requires('requirements.txt'), 'extras_require': { 'dev': get_install_requires('requirements.dev.txt'), 'doc': get_install_requires('requirements.doc.txt'), 'ray': ['ray>1.9.0'], }, 'classifiers': [ DEV_STATUS[version_spec.majorminor], 'Environment :: GPU :: NVIDIA CUDA', 'Framework :: Flake8', 'Framework :: IPython', 'Framework :: Jupyter', 'Framework :: Pytest', 'Framework :: Sphinx', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], 'zip_safe': True, 'packages': setuptools.find_packages(), } if __name__ == '__main__': setuptools.setup(**setup_kwargs)
3,174
34.277778
99
py
null
coax-main/upgrade_requirements.py
""" To update the requirements files, first do a pip freeze in google colab and then past the output in requirements.colab.txt After that, just run this script from the project root (where this script is located). """ import re from sys import stderr from packaging.version import parse as _parse import pandas as pd kwargs = { 'sep': r'(?:==|>=|\s@\s)', 'names': ['name', 'version'], 'index_col': 'name', 'comment': '#', 'engine': 'python', } def parse(row): version_str = '' if row.version is None else str(row.version) if version_str.startswith('http'): m = re.search(row.name + r'\-([\d\.]+)\+', row.version) version_str = '' if m is None else m.group(1) return _parse(version_str) def upgrade_requirements(filename): reqs_colab = pd.read_csv('requirements.colab.txt', **kwargs) reqs_colab['version'] = reqs_colab.apply(parse, axis=1) reqs = pd.read_csv(filename, **kwargs) reqs['version'] = reqs.apply(parse, axis=1) overlap = pd.merge(reqs, reqs_colab, left_index=True, right_index=True, suffixes=('', '_colab')) need_updating = overlap[overlap['version'] < overlap['version_colab']] with open(filename) as f: lines = f.readlines() for i, line in enumerate(lines): for name, row in need_updating.iterrows(): if line.startswith(name): new_version = row['version_colab'].base_version line_new = line.replace(str(row['version']), new_version) lines[i] = line_new print(f"updating {filename}: {line.rstrip()} --> {line_new.rstrip()}", file=stderr) with open(filename, 'w') as f: f.writelines(lines) if __name__ == '__main__': upgrade_requirements('requirements.txt') upgrade_requirements('requirements.dev.txt') upgrade_requirements('requirements.doc.txt')
1,870
30.183333
100
py
null
coax-main/.azure/docs.yml
# https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - main pool: vmImage: 'ubuntu-latest' variables: python.version: '3.8' TF_CPP_MIN_LOG_LEVEL: 3 # tell XLA to be quiet JAX_PLATFORM_NAME: cpu steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(python.version)' displayName: 'Use Python $(python.version)' - script: | sudo apt install -y swig python -m pip install --upgrade pip wheel pip install -r requirements.txt pip install -r requirements.dev.txt pip install pytest-azurepipelines displayName: 'Install requirements' - script: python -m flake8 coax displayName: 'Run flake8' - script: python -m pytest coax -v displayName: 'Run pytest' - script: | sudo apt install -y pandoc pip install -r requirements.doc.txt python setup.py build_sphinx displayName: 'Build docs' - task: FtpUpload@2 displayName: 'Deploy docs' inputs: credentialsOption: 'inputs' serverUrl: $(FTP_DEPLOY_SERVERURL) username: $(FTP_DEPLOY_USERNAME) password: $(FTP_DEPLOY_PASSWORD) rootDirectory: 'build/sphinx/html/' filePatterns: '**' remoteDirectory: '/site/wwwroot' clean: false cleanContents: true preservePaths: true trustSSL: false
1,259
22.333333
68
yml
null
coax-main/.azure/tests.yml
# https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - main pool: vmImage: 'ubuntu-latest' variables: TF_CPP_MIN_LOG_LEVEL: 3 # tell XLA to be quiet strategy: matrix: Python37_cpu: python.version: '3.7' JAX_PLATFORM_NAME: cpu Python38_cpu: python.version: '3.8' JAX_PLATFORM_NAME: cpu Python36_cpu: python.version: '3.9' JAX_PLATFORM_NAME: cpu # Python36_gpu: # Python37_gpu: # python.version: '3.7' # JAX_PLATFORM_NAME: gpu # XLA_PYTHON_CLIENT_MEM_FRACTION: 0.1 # don't use all of GPU memory # Python38_gpu: # python.version: '3.8' # JAX_PLATFORM_NAME: gpu # XLA_PYTHON_CLIENT_MEM_FRACTION: 0.1 # don't use all of GPU memory # python.version: '3.9' # JAX_PLATFORM_NAME: gpu # XLA_PYTHON_CLIENT_MEM_FRACTION: 0.1 # don't use all of GPU memory steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(python.version)' displayName: 'Use Python $(python.version)' - script: | sudo apt install -y swig python -m pip install --upgrade pip wheel pip install -r requirements.txt pip install -r requirements.dev.txt pip install pytest-azurepipelines displayName: 'Install requirements' - script: python -m flake8 coax displayName: 'Run flake8' - script: python -m pytest --cov=coax --cov-report=xml --cov-report=html coax -v displayName: 'Run pytest' - script: | sudo apt install -y pandoc pip install -r requirements.doc.txt python setup.py build_sphinx displayName: 'Build docs'
1,583
25.4
80
yml
null
coax-main/.github/ISSUE_TEMPLATE/bug_report.md
--- name: Bug report about: Create a report to help us improve title: '' labels: 'triage' assignees: '' --- **Describe the bug** <!-- A clear and concise description of what the bug is. --> **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **To Reproduce** Colab notebook to repro the bug: - https://colab.research.google.com/... *Runtime used for this colab notebook: ... (e.g. CPU/GPU/TPU)* **If you can't reproduce the bug in colab, please tell us some more about your runtime environment:** - OS: <!-- e.g. ubuntu 20.04, macos 10.14, ... --> - Python version: <!-- e.g. 3.8.2 --> - CUDA version (if applicable): <!-- e.g. nocuda, cuda102, cuda110, ... --> - `jax` version: <!-- e.g. 0.1.72 --> - `jaxlib` version: <!-- e.g. 0.1.51 --> - `coax` version: <!-- e.g. 0.1.2 --> - (any other version numbers that may be relevant) **Additional context** Add any other context about the problem here.
958
26.4
101
md
null
coax-main/.github/ISSUE_TEMPLATE/feature_request.md
--- name: Feature request about: Suggest an idea for this project title: '' labels: 'enhancement' assignees: '' --- **Is your feature request related to a problem? Please describe.** <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] --> **Describe the solution you'd like** <!-- A clear and concise description of what you want to happen. --> **Describe alternatives you've considered** <!-- A clear and concise description of any alternative solutions or features you've considered. --> **Additional context** <!-- Add any other context or screenshots about the feature request here. -->
642
29.619048
101
md
null
coax-main/.github/ISSUE_TEMPLATE/question.md
--- name: Question about: Ask a question about this project title: '' labels: 'question' assignees: '' --- **What's your question?** <!-- Please explain the context of your question. -->
191
12.714286
53
md
null
coax-main/.github/workflows/release.yml
name: release on: push: tags: - 'v*' jobs: test: name: Run tests runs-on: ${{ matrix.runs-on }} strategy: matrix: runs-on: [ubuntu-latest, macos-latest] python-version: ["3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install system packages (macos-latest) if: matrix.runs-on == 'macos-latest' run: brew install swig - name: Install system packages (ubuntu-latest) if: matrix.runs-on == 'ubuntu-latest' run: sudo apt-get install swig - name: Install python packages run: | python -m pip install --upgrade pip wheel python -m pip install -r requirements.txt python -m pip install -r requirements.dev.txt python -m pip install . - name: Lint with flake8 run: | python -m pip install flake8 # stop the build if there are Python syntax errors or undefined names python -m flake8 coax --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. python -m flake8 coax --count --exit-zero --max-complexity=10 --statistics - name: Test with pytest run: | python -m pip install pytest python -m pytest -v coax build-and-deploy: name: Build and deploy needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v1 with: python-version: 3.8 - name: Build run: | python -m pip install wheel python setup.py sdist python setup.py bdist_wheel - name: Upload to pypi run: | python -m pip install twine python -m twine upload --skip-existing --non-interactive --verbose dist/* env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.TWINE_TOKEN }} create-release: name: Create release needs: test runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Create release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref }} release_name: ${{ github.ref }} body: "Release notes: https://coax.readthedocs.io/release_notes.html" draft: false prerelease: ${{ contains(github.ref, 'rc') }}
2,603
28.931034
87
yml
null
coax-main/.github/workflows/tests.yml
name: tests on: push: branches: - main pull_request: branches: - main jobs: test: name: Run tests runs-on: ${{ matrix.runs-on }} strategy: matrix: runs-on: [ubuntu-latest, macos-latest] python-version: ["3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install system packages (macos-latest) if: matrix.runs-on == 'macos-latest' run: brew install swig - name: Install system packages (ubuntu-latest) if: matrix.runs-on == 'ubuntu-latest' run: sudo apt-get install swig - name: Install python packages run: | python -m pip install --upgrade pip wheel python -m pip install -r requirements.txt python -m pip install -r requirements.dev.txt python -m pip install . - name: Lint with flake8 run: | python -m pip install flake8 # stop the build if there are Python syntax errors or undefined names python -m flake8 coax --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. python -m flake8 coax --count --exit-zero --max-complexity=10 --statistics - name: Test with pytest run: | python -m pip install pytest pytest-cov python -m pytest --cov=coax --cov-report=xml coax -v
1,510
30.479167
87
yml
null
coax-main/coax/__init__.py
__version__ = '0.1.13' # fall back to legacy gym if gymnasium is unavailable try: import gymnasium as _gymnasium except ImportError: import sys import warnings warnings.warn("Cannot import 'gymnasium'; attempting to fall back to legacy 'gym'.") import gym as _gymnasium # Don't catch ImportError here; we need gymnasium or gym. sys.modules['gymnasium'] = _gymnasium del sys, warnings # Keep namespace clean. # expose specific classes and functions from ._core.v import V from ._core.q import Q from ._core.policy import Policy from ._core.worker import Worker from ._core.reward_function import RewardFunction from ._core.transition_model import TransitionModel from ._core.stochastic_v import StochasticV from ._core.stochastic_q import StochasticQ from ._core.stochastic_transition_model import StochasticTransitionModel from ._core.stochastic_reward_function import StochasticRewardFunction from ._core.value_based_policy import EpsilonGreedy, BoltzmannPolicy from ._core.random_policy import RandomPolicy from ._core.successor_state_q import SuccessorStateQ from .utils import safe_sample, render_episode, unvectorize # pre-load submodules from . import experience_replay from . import model_updaters from . import policy_objectives from . import proba_dists from . import regularizers from . import reward_tracing from . import td_learning from . import typing from . import utils from . import value_losses from . import wrappers __all__ = ( # classes and functions 'V', 'Q', 'Policy', 'Worker', 'RewardFunction', 'TransitionModel', 'StochasticV', 'StochasticQ', 'StochasticRewardFunction', 'StochasticTransitionModel', 'EpsilonGreedy', 'BoltzmannPolicy', 'RandomPolicy', 'SuccessorStateQ', 'safe_sample', 'render_episode', 'unvectorize', # modules 'experience_replay', 'model_updaters', 'policy_objectives', 'proba_dists', 'regularizers', 'reward_tracing', 'td_learning', 'typing', 'utils', 'value_losses', 'wrappers', ) # ----------------------------------------------------------------------------- # register envs # ----------------------------------------------------------------------------- if 'ConnectFour-v0' in _gymnasium.envs.registry: del _gymnasium.envs.registry['ConnectFour-v0'] _gymnasium.envs.register( id='ConnectFour-v0', entry_point='coax.envs:ConnectFourEnv', ) if 'FrozenLakeNonSlippery-v0' in _gymnasium.envs.registry: del _gymnasium.envs.registry['FrozenLakeNonSlippery-v0'] _gymnasium.envs.register( id='FrozenLakeNonSlippery-v0', entry_point='gymnasium.envs.toy_text:FrozenLakeEnv', kwargs={'map_name': '4x4', 'is_slippery': False}, max_episode_steps=20, reward_threshold=0.99, ) del _gymnasium # Keep namespace clean.
2,853
26.180952
88
py
null
coax-main/coax/typing.py
from typing import TypeVar, Union, Sequence, Callable, Tuple __all__ = ( 'Batch', 'SpaceElement', 'Observation', 'Action' ) Batch = Sequence # annotate batched quantities Observation = TypeVar('Observation') # a state observation Action = TypeVar('Action') # an action SpaceElement = Union[Observation, Action] # element of a gymnasium-style space LogPropensity = TypeVar('LogPropensity') # an action Policy = Callable[ [Observation, bool], Union[Action, Tuple[Action, LogPropensity]] ]
573
23.956522
80
py
null
coax-main/coax/_base/__init__.py
0
0
0
py
null
coax-main/coax/_base/errors.py
class CoaxError(Exception): pass class SpaceError(CoaxError): pass class ActionSpaceError(SpaceError): pass class DistributionError(CoaxError): pass class EpisodeDoneError(CoaxError): pass class InconsistentCacheInputError(CoaxError): pass class InsufficientCacheError(CoaxError): pass class LeafNodeError(CoaxError): pass class MissingAdversaryError(CoaxError): pass class MissingModelError(CoaxError): pass class NotLeafNodeError(CoaxError): pass class NumpyArrayCheckError(CoaxError): pass class TensorCheckError(CoaxError): pass class UnavailableActionError(CoaxError): pass
662
10.839286
45
py
null
coax-main/coax/_base/test_case.py
import gc import unittest from collections import namedtuple from contextlib import AbstractContextManager from resource import getrusage, RUSAGE_SELF from functools import partial import gymnasium import jax import jax.numpy as jnp import numpy as onp import haiku as hk __all__ = ( 'DiscreteEnv', 'BoxEnv', 'TestCase', 'MemoryProfiler', ) MockEnv = namedtuple('MockEnv', ( 'observation_space', 'action_space', 'reward_range', 'metadata', 'reset', 'step', 'close', 'random_seed', 'spec')) def DiscreteEnv(random_seed): action_space = gymnasium.spaces.Discrete(3) action_space.seed(13 * random_seed) observation_space = gymnasium.spaces.Box( low=onp.float32(0), high=onp.float32(1), shape=(17, 19)) observation_space.seed(11 * random_seed) reward_range = (-1., 1.) metadata = None spec = None def reset(): return observation_space.sample() def step(a): s = observation_space.sample() return s, 0.5, False, {} def close(): pass return MockEnv(observation_space, action_space, reward_range, metadata, reset, step, close, random_seed, spec) def BoxEnv(random_seed): env = DiscreteEnv(random_seed)._asdict() env['action_space'] = gymnasium.spaces.Box( low=onp.float32(0), high=onp.float32(1), shape=(3, 5)) env['action_space'].seed(7 * random_seed) return MockEnv(**env) class MemoryProfiler(AbstractContextManager): def __enter__(self): gc.collect() self._mem_used = None self._mem_start = self._get_mem() return self def __exit__(self, exc_type, exc_val, exc_tb): gc.collect() self._mem_used = self._get_mem() - self._mem_start @property def memory_used(self): gc.collect() if self._mem_used is not None: return self._mem_used # only available after __exit__ else: return self._get_mem() - self._mem_start @staticmethod def _get_mem(): return getrusage(RUSAGE_SELF).ru_maxrss class TestCase(unittest.TestCase): r""" adds some common properties to unittest.TestCase """ seed = 42 margin = 0.01 # for robust comparison (x > 0) --> (x > margin) decimal = 6 # sets the absolute tolerance @property def env_discrete(self): return DiscreteEnv(self.seed) @property def env_boxspace(self): return BoxEnv(self.seed) @property def transitions_discrete(self): from ..utils import safe_sample from ..reward_tracing import TransitionBatch return TransitionBatch( S=onp.stack([ safe_sample(self.env_discrete.observation_space, seed=(self.seed * i * 1)) for i in range(1, 12)], axis=0), A=onp.stack([ safe_sample(self.env_discrete.action_space, seed=(self.seed * i * 2)) for i in range(1, 12)], axis=0), logP=onp.log(onp.random.RandomState(3).rand(11)), Rn=onp.random.RandomState(5).randn(11), In=onp.random.RandomState(7).randint(2, size=11) * 0.95, S_next=onp.stack([ safe_sample(self.env_discrete.observation_space, seed=(self.seed * i * 11)) for i in range(1, 12)], axis=0), A_next=onp.stack([ safe_sample(self.env_discrete.action_space, seed=(self.seed * i * 13)) for i in range(1, 12)], axis=0), logP_next=onp.log(onp.random.RandomState(17).rand(11)), extra_info=None ) @property def transitions_boxspace(self): from ..utils import safe_sample from ..reward_tracing import TransitionBatch return TransitionBatch( S=onp.stack([ safe_sample(self.env_boxspace.observation_space, seed=(self.seed * i * 1)) for i in range(1, 12)], axis=0), A=onp.stack([ safe_sample(self.env_boxspace.action_space, seed=(self.seed * i * 2)) for i in range(1, 12)], axis=0), logP=onp.log(onp.random.RandomState(3).rand(11)), Rn=onp.random.RandomState(5).randn(11), In=onp.random.RandomState(7).randint(2, size=11) * 0.95, S_next=onp.stack([ safe_sample(self.env_boxspace.observation_space, seed=(self.seed * i * 11)) for i in range(1, 12)], axis=0), A_next=onp.stack([ safe_sample(self.env_boxspace.action_space, seed=(self.seed * i * 13)) for i in range(1, 12)], axis=0), logP_next=onp.log(onp.random.RandomState(17).rand(11)), extra_info=None ) @property def func_pi_discrete(self): def func(S, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(self.env_discrete.action_space.n), )) return {'logits': seq(flatten(S))} return func @property def func_pi_boxspace(self): def func(S, is_training): flatten = hk.Flatten() batch_norm_m = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_v = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_m = partial(batch_norm_m, is_training=is_training) batch_norm_v = partial(batch_norm_v, is_training=is_training) mu = hk.Sequential(( hk.Linear(7), batch_norm_m, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(self.env_boxspace.action_space.shape)), hk.Reshape(self.env_boxspace.action_space.shape), )) logvar = hk.Sequential(( hk.Linear(7), batch_norm_v, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(self.env_boxspace.action_space.shape)), hk.Reshape(self.env_boxspace.action_space.shape), )) return {'mu': mu(flatten(S)), 'logvar': logvar(flatten(S))} return func @property def func_q_type1(self): def func(S, A, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(1), jnp.ravel, )) X = jnp.concatenate((flatten(S), flatten(A)), axis=-1) return seq(X) return func @property def func_q_type2(self): def func(S, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(self.env_discrete.action_space.n), )) return seq(flatten(S)) return func @property def func_q_stochastic_type1(self): def func(S, A, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(51), )) print(S.shape, A.shape) X = jnp.concatenate((flatten(S), flatten(A)), axis=-1) return {'logits': seq(X)} return func @property def func_q_stochastic_type2(self): def func(S, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(self.env_discrete.action_space.n * 51), hk.Reshape((self.env_discrete.action_space.n, 51)) )) return {'logits': seq(flatten(S))} return func @property def func_v(self): def func(S, is_training): flatten = hk.Flatten() batch_norm = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm = partial(batch_norm, is_training=is_training) seq = hk.Sequential(( hk.Linear(7), batch_norm, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(1), jnp.ravel )) return seq(flatten(S)) return func @property def func_p_type1(self): def func(S, A, is_training): output_shape = self.env_discrete.observation_space.shape flatten = hk.Flatten() batch_norm_m = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_v = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_m = partial(batch_norm_m, is_training=is_training) batch_norm_v = partial(batch_norm_v, is_training=is_training) mu = hk.Sequential(( hk.Linear(7), batch_norm_m, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(output_shape)), hk.Reshape(output_shape), )) logvar = hk.Sequential(( hk.Linear(7), batch_norm_v, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(output_shape)), hk.Reshape(output_shape), )) X = jnp.concatenate((flatten(S), flatten(A)), axis=-1) return {'mu': mu(X), 'logvar': logvar(X)} return func @property def func_p_type2(self): def func(S, is_training): env = self.env_discrete output_shape = (env.action_space.n, *env.observation_space.shape) flatten = hk.Flatten() batch_norm_m = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_v = hk.BatchNorm(create_scale=True, create_offset=True, decay_rate=0.95) batch_norm_m = partial(batch_norm_m, is_training=is_training) batch_norm_v = partial(batch_norm_v, is_training=is_training) mu = hk.Sequential(( hk.Linear(7), batch_norm_m, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(output_shape)), hk.Reshape(output_shape), )) logvar = hk.Sequential(( hk.Linear(7), batch_norm_v, jnp.tanh, hk.Linear(3), jnp.tanh, hk.Linear(onp.prod(output_shape)), hk.Reshape(output_shape), )) X = flatten(S) return {'mu': mu(X), 'logvar': logvar(X)} return func def assertArrayAlmostEqual(self, x, y, decimal=None): decimal = decimal or self.decimal x = onp.asanyarray(x) y = onp.asanyarray(y) x = (x - x.min()) / (x.max() - x.min() + 1e-16) y = (y - y.min()) / (y.max() - y.min() + 1e-16) onp.testing.assert_array_almost_equal(x, y, decimal=decimal) def assertArrayNotEqual(self, x, y, margin=margin): reldiff = jnp.abs(2 * (x - y) / (x + y + 1e-16)) maxdiff = jnp.max(reldiff) assert float(maxdiff) > self.margin def assertPytreeAlmostEqual(self, x, y, decimal=None): decimal = decimal or self.decimal jax.tree_map( lambda x, y: onp.testing.assert_array_almost_equal( x, y, decimal=decimal), x, y) def assertPytreeNotEqual(self, x, y, margin=None): margin = margin or self.margin reldiff = jax.tree_map( lambda a, b: abs(2 * (a - b) / (a + b + 1e-16)), x, y) maxdiff = max(jnp.max(d) for d in jax.tree_util.tree_leaves(reldiff)) assert float(maxdiff) > margin def assertArraySubdtypeFloat(self, arr): self.assertTrue(jnp.issubdtype(arr.dtype, jnp.floating)) def assertArraySubdtypeInt(self, arr): self.assertTrue(jnp.issubdtype(arr.dtype, jnp.integer)) def assertArrayShape(self, arr, shape): self.assertEqual(arr.shape, shape) def assertAlmostEqual(self, x, y, decimal=None): decimal = decimal or self.decimal super().assertAlmostEqual(x, y, places=decimal)
13,055
36.517241
95
py
null
coax-main/coax/_base/mixins/__init__.py
from ._add_orig_to_info import AddOrigToInfoDictMixin from ._copy import CopyMixin from ._logger import LoggerMixin from ._random_state import RandomStateMixin __all__ = ( 'AddOrigToInfoDictMixin', 'CopyMixin', 'LoggerMixin', 'RandomStateMixin', )
266
19.538462
53
py
null
coax-main/coax/_base/mixins/_add_orig_to_info.py
from typing import Mapping class AddOrigToInfoDictMixin: def _add_s_orig_to_info_dict(self, info): if not isinstance(info, Mapping): assert info is None, "unexpected type for 'info' Mapping" info = {} if 's_orig' in info: info['s_orig'].append(self._s_orig) else: info['s_orig'] = [self._s_orig] if 's_next_orig' in info: info['s_next_orig'].append(self._s_next_orig) else: info['s_next_orig'] = [self._s_next_orig] self._s_orig = self._s_next_orig def _add_a_orig_to_info_dict(self, info): if not isinstance(info, Mapping): assert info is None, "unexpected type for 'info' Mapping" info = {} if 'a_orig' in info: info['a_orig'].append(self._a_orig) else: info['a_orig'] = [self._a_orig]
895
27.903226
69
py
null
coax-main/coax/_base/mixins/_copy.py
from copy import deepcopy, copy class CopyMixin: def copy(self, deep=False): r""" Create a copy of the current instance. Parameters ---------- deep : bool, optional Whether the copy should be a deep copy. Returns ------- copy A deep copy of the current instance. """ return deepcopy(self) if deep else copy(self)
429
16.916667
53
py
null
coax-main/coax/_base/mixins/_logger.py
import logging class LoggerMixin: @property def logger(self): return logging.getLogger(self.__class__.__name__)
130
15.375
57
py
null
coax-main/coax/_base/mixins/_random_state.py
import numpy as onp import jax class RandomStateMixin: @property def random_seed(self): return self._random_seed @random_seed.setter def random_seed(self, new_random_seed): if new_random_seed is None: new_random_seed = onp.random.randint(2147483647) self._random_seed = new_random_seed self._random_key = jax.random.PRNGKey(self._random_seed) @property def rng(self): self._random_key, key = jax.random.split(self._random_key) return key
526
24.095238
66
py
null
coax-main/coax/_core/__init__.py
0
0
0
py
null
coax-main/coax/_core/base_func.py
from abc import ABC, abstractmethod from typing import Any, Tuple, NamedTuple import jax import haiku as hk from gymnasium.spaces import Space from ..typing import Batch, Observation, Action from ..utils import pretty_repr, jit from .._base.mixins import RandomStateMixin, CopyMixin class Inputs(NamedTuple): args: Any static_argnums: Tuple[int, ...] def __repr__(self): return pretty_repr(self) class ExampleData(NamedTuple): inputs: Inputs output: Any def __repr__(self): return pretty_repr(self) class ArgsType1(NamedTuple): S: Batch[Observation] A: Batch[Action] is_training: bool def __repr__(self): return pretty_repr(self) class ArgsType2(NamedTuple): S: Batch[Observation] is_training: bool def __repr__(self): return pretty_repr(self) class ModelTypes(NamedTuple): type1: ArgsType1 type2: ArgsType2 def __repr__(self): return pretty_repr(self) class BaseFunc(ABC, RandomStateMixin, CopyMixin): """ Abstract base class for function approximators: coax.V, coax.Q, coax.Policy """ def __init__(self, func, observation_space, action_space=None, random_seed=None): if not isinstance(observation_space, Space): raise TypeError( "observation_space must be derived from gymnasium.Space, " f"got: {type(observation_space)}") self.observation_space = observation_space if action_space is not None: if not isinstance(action_space, Space): raise TypeError( f"action_space must be derived from gymnasium.Space, got: {type(action_space)}") self.action_space = action_space self.random_seed = random_seed # also initializes self.rng via RandomStateMixin self._jitted_funcs = {} # Haiku-transform the provided func example_data = self._check_signature(func) static_argnums = tuple(i + 3 for i in example_data.inputs.static_argnums) transformed = hk.transform_with_state(func) self._function = jit(transformed.apply, static_argnums=static_argnums) # init function params and state self._params, self._function_state = transformed.init(self.rng, *example_data.inputs.args) # check if output has the expected shape etc. output, _ = \ self._function(self.params, self.function_state, self.rng, *example_data.inputs.args) self._check_output(output, example_data.output) def soft_update_func(old, new, tau): return jax.tree_map(lambda a, b: (1 - tau) * a + tau * b, old, new) self._soft_update_func = jit(soft_update_func) def soft_update(self, other, tau): r""" Synchronize the current instance with ``other`` through exponential smoothing: .. math:: \theta\ \leftarrow\ \theta + \tau\, (\theta_\text{new} - \theta) Parameters ---------- other A seperate copy of the current object. This object will hold the new parameters :math:`\theta_\text{new}`. tau : float between 0 and 1, optional If we set :math:`\tau=1` we do a hard update. If we pick a smaller value, we do a smooth update. """ if not isinstance(other, self.__class__): raise TypeError("'self' and 'other' must be of the same type") self.params = self._soft_update_func(self.params, other.params, tau) self.function_state = self._soft_update_func(self.function_state, other.function_state, tau) @property def params(self): """ The parameters (weights) of the function approximator. """ return self._params @params.setter def params(self, new_params): if jax.tree_util.tree_structure(new_params) != jax.tree_util.tree_structure(self._params): raise TypeError("new params must have the same structure as old params") self._params = new_params @property def function(self): r""" The function approximator itself, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output, function_state = obj.function(obj.params, obj.function_state, obj.rng, *inputs) """ return self._function @property def function_state(self): """ The state of the function approximator, see :func:`haiku.transform_with_state`. """ return self._function_state @function_state.setter def function_state(self, new_function_state): new_tree_structure = jax.tree_util.tree_structure(new_function_state) tree_structure = jax.tree_util.tree_structure(self._function_state) if new_tree_structure != tree_structure: raise TypeError("new function_state must have the same structure as old function_state") self._function_state = new_function_state @abstractmethod def _check_signature(self, func): """ Check if func has expected input signature; returns example_data; raises TypeError """ @abstractmethod def _check_output(self, actual, expected): """ Check if func has expected output signature; raises TypeError """ @abstractmethod def example_data(self, env, **kwargs): r""" A small utility function that generates example input and output data. These may be useful for writing and debugging your own custom function approximators. """
5,555
31.115607
100
py
null
coax-main/coax/_core/base_stochastic_func_type1.py
from inspect import signature from collections import namedtuple import jax import jax.numpy as jnp import numpy as onp import haiku as hk from gymnasium.spaces import Space, Discrete from ..utils import safe_sample, batch_to_single, jit from .base_func import BaseFunc, ExampleData, Inputs, ArgsType1, ArgsType2, ModelTypes __all__ = ( 'BaseStochasticFuncType1', ) class BaseStochasticFuncType1(BaseFunc): r""" An abstract base class for stochastic functions that take *state-action pairs* as input: * StochasticQ * StochasticTransitionModel * StochasticRewardFunction """ def __init__( self, func, observation_space, action_space, observation_preprocessor, action_preprocessor, proba_dist, random_seed): self.observation_preprocessor = observation_preprocessor self.action_preprocessor = action_preprocessor self.proba_dist = proba_dist # note: self._modeltype is set in super().__init__ via self._check_signature super().__init__( func=func, observation_space=observation_space, action_space=action_space, random_seed=random_seed) def __call__(self, s, a=None, return_logp=False): S = self.observation_preprocessor(self.rng, s) if a is None: X, logP = self.sample_func_type2(self.params, self.function_state, self.rng, S) X, logP = batch_to_single((X, logP)) # (batch, num_actions, *) -> (num_actions, *) n = self.action_space.n x = [self.proba_dist.postprocess_variate(self.rng, X, index=i) for i in range(n)] logp = list(logP) else: A = self.action_preprocessor(self.rng, a) X, logP = self.sample_func_type1(self.params, self.function_state, self.rng, S, A) x = self.proba_dist.postprocess_variate(self.rng, X) logp = batch_to_single(logP) return (x, logp) if return_logp else x def mean(self, s, a=None): S = self.observation_preprocessor(self.rng, s) if a is None: X = self.mean_func_type2(self.params, self.function_state, self.rng, S) X = batch_to_single(X) # (batch, num_actions, *) -> (num_actions, *) n = self.action_space.n x = [self.proba_dist.postprocess_variate(self.rng, X, index=i) for i in range(n)] else: A = self.action_preprocessor(self.rng, a) X = self.mean_func_type1(self.params, self.function_state, self.rng, S, A) x = self.proba_dist.postprocess_variate(self.rng, X) return x def mode(self, s, a=None): S = self.observation_preprocessor(self.rng, s) if a is None: X = self.mode_func_type2(self.params, self.function_state, self.rng, S) X = batch_to_single(X) # (batch, num_actions, *) -> (num_actions, *) n = self.action_space.n x = [self.proba_dist.postprocess_variate(self.rng, X, index=i) for i in range(n)] else: A = self.action_preprocessor(self.rng, a) X = self.mode_func_type1(self.params, self.function_state, self.rng, S, A) x = self.proba_dist.postprocess_variate(self.rng, X) return x def dist_params(self, s, a=None): S = self.observation_preprocessor(self.rng, s) if a is None: # batch_to_single() projects: (batch, num_actions, *shape) -> (num_actions, *shape) dist_params = batch_to_single( self.function_type2(self.params, self.function_state, self.rng, S, False)[0]) dist_params = [ batch_to_single(dist_params, index=i) for i in range(self.action_space.n)] else: A = self.action_preprocessor(self.rng, a) dist_params, _ = self.function_type1( self.params, self.function_state, self.rng, S, A, False) dist_params = batch_to_single(dist_params) return dist_params @property def function_type1(self): r""" Same as :attr:`function`, except that it ensures a type-1 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 1: return self.function assert isinstance(self.action_space, Discrete) def project(A): assert A.ndim == 2, f"bad shape: {A.shape}" assert A.shape[1] == self.action_space.n, f"bad shape: {A.shape}" def func(leaf): # noqa: E306 assert isinstance(leaf, jnp.ndarray), f"leaf must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 2, f"bad shape: {leaf.shape}" assert leaf.shape[0] == A.shape[0], \ f"batch_size (axis=0) mismatch: leaf.shape: {leaf.shape}, A.shape: {A.shape}" assert leaf.shape[1] == A.shape[1], \ f"num_actions (axis=1) mismatch: leaf.shape: {leaf.shape}, A.shape: {A.shape}" return jax.vmap(jnp.dot)(jnp.moveaxis(leaf, 1, -1), A) return func def type1_func(type2_params, type2_state, rng, S, A, is_training): dist_params, state_new = self.function(type2_params, type2_state, rng, S, is_training) dist_params = jax.tree_map(project(A), dist_params) return dist_params, state_new return type1_func @property def function_type2(self): r""" Same as :attr:`function`, except that it ensures a type-2 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 2: return self.function if not isinstance(self.action_space, Discrete): raise ValueError( "input 'A' is required for type-1 dynamics model when action space is non-Discrete") n = self.action_space.n def reshape(leaf): # reshape from (batch * num_actions, *shape) -> (batch, *shape, num_actions) assert isinstance(leaf, jnp.ndarray), f"all leaves must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 1, f"bad shape: {leaf.shape}" assert leaf.shape[0] % n == 0, \ f"first axis size must be a multiple of num_actions, got shape: {leaf.shape}" leaf = jnp.reshape(leaf, (-1, n, *leaf.shape[1:])) # (batch, num_actions, *shape) return leaf def type2_func(type1_params, type1_state, rng, S, is_training): rngs = hk.PRNGSequence(rng) batch_size = jax.tree_util.tree_leaves(S)[0].shape[0] # example: let S = [7, 2, 5, 8] and num_actions = 3, then # S_rep = [7, 7, 7, 2, 2, 2, 5, 5, 5, 8, 8, 8] # repeated # A_rep = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] # tiled S_rep = jax.tree_map(lambda x: jnp.repeat(x, n, axis=0), S) A_rep = jnp.tile(jnp.arange(n), batch_size) A_rep = self.action_preprocessor(next(rngs), A_rep) # one-hot encoding # evaluate on replicas => output shape: (batch * num_actions, *shape) dist_params_rep, state_new = self.function( type1_params, type1_state, next(rngs), S_rep, A_rep, is_training) dist_params = jax.tree_map(reshape, dist_params_rep) return dist_params, state_new return type2_func @property def modeltype(self): r""" Specifier for how the dynamics model is implemented, i.e. .. math:: (s,a) &\mapsto p(s'|s,a) &\qquad (\text{modeltype} &= 1) \\ s &\mapsto p(s'|s,.) &\qquad (\text{modeltype} &= 2) Note that modeltype=2 is only well-defined if the action space is :class:`Discrete <gymnasium.spaces.Discrete>`. Namely, :math:`n` is the number of discrete actions. """ return self._modeltype @classmethod def example_data( cls, env, observation_preprocessor, action_preprocessor, proba_dist, batch_size=1, random_seed=None): if not isinstance(env.observation_space, Space): raise TypeError( "env.observation_space must be derived from gymnasium.Space, " f"got: {type(env.observation_space)}") if not isinstance(env.action_space, Space): raise TypeError( "env.action_space must be derived from gymnasium.Space, " f"got: {type(env.action_space)}") rnd = onp.random.RandomState(random_seed) rngs = hk.PRNGSequence(rnd.randint(jnp.iinfo('int32').max)) # these must be provided assert observation_preprocessor is not None assert action_preprocessor is not None assert proba_dist is not None # input: state observations S = [safe_sample(env.observation_space, rnd) for _ in range(batch_size)] S = [observation_preprocessor(next(rngs), s) for s in S] S = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *S) # input: actions A = [safe_sample(env.action_space, rnd) for _ in range(batch_size)] A = [action_preprocessor(next(rngs), a) for a in A] A = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *A) # output: type1 dist_params_type1 = jax.tree_map( lambda x: jnp.asarray(rnd.randn(batch_size, *x.shape[1:])), proba_dist.default_priors) data_type1 = ExampleData( inputs=Inputs(args=ArgsType1(S=S, A=A, is_training=True), static_argnums=(2,)), output=dist_params_type1) if not isinstance(env.action_space, Discrete): return ModelTypes(type1=data_type1, type2=None) # output: type2 (if actions are discrete) dist_params_type2 = jax.tree_map( lambda x: jnp.asarray(rnd.randn(batch_size, env.action_space.n, *x.shape[1:])), proba_dist.default_priors) data_type2 = ExampleData( inputs=Inputs(args=ArgsType2(S=S, is_training=True), static_argnums=(1,)), output=dist_params_type2) return ModelTypes(type1=data_type1, type2=data_type2) @property def sample_func_type1(self): r""" The function that is used for generating *random samples*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.sample_func_type1(obj.params, obj.function_state, obj.rng, S) """ if not hasattr(self, '_sample_func_type1'): def sample_func_type1(params, state, rng, S, A): rngs = hk.PRNGSequence(rng) dist_params, _ = self.function_type1(params, state, next(rngs), S, A, False) S_next = self.proba_dist.sample(dist_params, next(rngs)) logP = self.proba_dist.log_proba(dist_params, S_next) return S_next, logP self._sample_func_type1 = jit(sample_func_type1) return self._sample_func_type1 @property def sample_func_type2(self): r""" The function that is used for generating *random samples*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.sample_func_type2(obj.params, obj.function_state, obj.rng, S, A) """ if not hasattr(self, '_sample_func_type2'): def sample_func_type2(params, state, rng, S): rngs = hk.PRNGSequence(rng) dist_params, _ = self.function_type2(params, state, next(rngs), S, False) dist_params = jax.tree_map(self._reshape_to_replicas, dist_params) X = self.proba_dist.sample(dist_params, next(rngs)) # (batch x n, *shape) logP = self.proba_dist.log_proba(dist_params, X) # (batch x n) X = jax.tree_map(self._reshape_from_replicas, X) # (batch, n, *shape) logP = self._reshape_from_replicas(logP) # (batch, n) return X, logP self._sample_func_type2 = jit(sample_func_type2) return self._sample_func_type2 @property def mode_func_type1(self): r""" The function that is used for computing the *mode*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mode_func_type1(obj.params, obj.function_state, obj.rng, S, A) """ if not hasattr(self, '_mode_func_type1'): def mode_func_type1(params, state, rng, S, A): dist_params, _ = self.function_type1(params, state, rng, S, A, False) X = self.proba_dist.mode(dist_params) return X self._mode_func_type1 = jit(mode_func_type1) return self._mode_func_type1 @property def mode_func_type2(self): r""" The function that is used for computing the *mode*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mode_func_type2(obj.params, obj.function_state, obj.rng, S) """ if not hasattr(self, '_mode_func_type2'): def mode_func_type2(params, state, rng, S): dist_params, _ = self.function_type2(params, state, rng, S, False) dist_params = jax.tree_map(self._reshape_to_replicas, dist_params) X = self.proba_dist.mode(dist_params) # (batch x n, *shape) X = jax.tree_map(self._reshape_from_replicas, X) # (batch, n, *shape) return X self._mode_func_type2 = jit(mode_func_type2) return self._mode_func_type2 @property def mean_func_type1(self): r""" The function that is used for computing the *mean*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mean_func_type1(obj.params, obj.function_state, obj.rng, S, A) """ if not hasattr(self, '_mean_func_type1'): def mean_func_type1(params, state, rng, S, A): dist_params, _ = self.function_type1(params, state, rng, S, A, False) X = self.proba_dist.mean(dist_params) return X self._mean_func_type1 = jit(mean_func_type1) return self._mean_func_type1 @property def mean_func_type2(self): r""" The function that is used for computing the *mean*, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mean_func_type2(obj.params, obj.function_state, obj.rng, S) """ if not hasattr(self, '_mean_func_type2'): def mean_func_type2(params, state, rng, S): dist_params, _ = self.function_type2(params, state, rng, S, False) dist_params = jax.tree_map(self._reshape_to_replicas, dist_params) X = self.proba_dist.mean(dist_params) # (batch x n, *shape) X = jax.tree_map(self._reshape_from_replicas, X) # (batch, n, *shape) return X self._mean_func_type2 = jit(mean_func_type2) return self._mean_func_type2 def _check_signature(self, func): sig_type1 = ('S', 'A', 'is_training') sig_type2 = ('S', 'is_training') sig = tuple(signature(func).parameters) if sig not in (sig_type1, sig_type2): sig = ', '.join(sig) alt = ' or func(S, is_training)' if isinstance(self.action_space, Discrete) else '' raise TypeError( f"func has bad signature; expected: func(S, A, is_training){alt}, got: func({sig})") if sig == sig_type2 and not isinstance(self.action_space, Discrete): raise TypeError( "type-2 models are only well-defined for Discrete action spaces") Env = namedtuple('Env', ('observation_space', 'action_space')) example_data_per_modeltype = BaseStochasticFuncType1.example_data( env=Env(self.observation_space, self.action_space), observation_preprocessor=self.observation_preprocessor, action_preprocessor=self.action_preprocessor, proba_dist=self.proba_dist, batch_size=1, random_seed=self.random_seed) if sig == sig_type1: self._modeltype = 1 example_data = example_data_per_modeltype.type1 else: self._modeltype = 2 example_data = example_data_per_modeltype.type2 return example_data def _check_output(self, actual, expected): expected_leaves, expected_structure = jax.tree_util.tree_flatten(expected) actual_leaves, actual_structure = jax.tree_util.tree_flatten(actual) assert all(isinstance(x, jnp.ndarray) for x in expected_leaves), "bad example_data" if actual_structure != expected_structure: raise TypeError( f"func has bad return tree_structure, expected: {expected_structure}, " f"got: {actual_structure}") if not all(isinstance(x, jnp.ndarray) for x in actual_leaves): bad_types = tuple(type(x) for x in actual_leaves if not isinstance(x, jnp.ndarray)) raise TypeError( "all leaves of dist_params must be of type: jax.numpy.ndarray, " f"found leaves of type: {bad_types}") if not all(a.shape == b.shape for a, b in zip(actual_leaves, expected_leaves)): shapes_tree = jax.tree_map( lambda a, b: f"{a.shape} {'!=' if a.shape != b.shape else '=='} {b.shape}", actual, expected) raise TypeError(f"found leaves with unexpected shapes: {shapes_tree}") def _reshape_from_replicas(self, leaf): """ reshape from (batch x num_actions, *) to (batch, num_actions, *) """ assert isinstance(self.action_space, Discrete), "action_space is non-discrete" assert isinstance(leaf, jnp.ndarray), f"leaf must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 1, f"bad shape: {leaf.shape}" assert leaf.shape[0] % self.action_space.n == 0, \ f"first axis size must be a multiple of num_actions, got shape: {leaf.shape}" return jnp.reshape(leaf, (-1, self.action_space.n, *leaf.shape[1:])) return leaf def _reshape_to_replicas(self, leaf): """ reshape from (batch, num_actions, *) to (batch x num_actions, *) """ assert isinstance(self.action_space, Discrete), "action_space is non-discrete" assert isinstance(leaf, jnp.ndarray), f"leaf must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 2, f"bad shape: {leaf.shape}" assert leaf.shape[1] == self.action_space.n, \ f"axis=1 size must be num_actions, got shape: {leaf.shape}" return jnp.reshape(leaf, (-1, *leaf.shape[2:])) # (batch x num_actions, *shape)
19,163
41.39823
100
py
null
coax-main/coax/_core/base_stochastic_func_type2.py
from inspect import signature from collections import namedtuple import jax import jax.numpy as jnp import numpy as onp import haiku as hk from gymnasium.spaces import Space from ..utils import safe_sample, batch_to_single, jit from .base_func import BaseFunc, ExampleData, Inputs, ArgsType2 __all__ = ( 'BaseStochasticFuncType2', 'StochasticFuncType2Mixin', ) class StochasticFuncType2Mixin: r""" An mix-in class for stochastic functions that take *only states* as input: * Policy * StochasticV * StateDensity """ def __call__(self, s, return_logp=False): S = self.observation_preprocessor(self.rng, s) X, logP = self.sample_func(self.params, self.function_state, self.rng, S) x = self.proba_dist.postprocess_variate(self.rng, X) return (x, batch_to_single(logP)) if return_logp else x def mean(self, s): S = self.observation_preprocessor(self.rng, s) X = self.mean_func(self.params, self.function_state, self.rng, S) x = self.proba_dist.postprocess_variate(self.rng, X) return x def mode(self, s): S = self.observation_preprocessor(self.rng, s) X = self.mode_func(self.params, self.function_state, self.rng, S) x = self.proba_dist.postprocess_variate(self.rng, X) return x def dist_params(self, s): S = self.observation_preprocessor(self.rng, s) dist_params, _ = self.function(self.params, self.function_state, self.rng, S, False) return batch_to_single(dist_params) @property def sample_func(self): r""" The function that is used for sampling *random* from the underlying :attr:`proba_dist`, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.sample_func(obj.params, obj.function_state, obj.rng, *inputs) """ if not hasattr(self, '_sample_func'): def sample_func(params, state, rng, S): rngs = hk.PRNGSequence(rng) dist_params, _ = self.function(params, state, next(rngs), S, False) X = self.proba_dist.sample(dist_params, next(rngs)) logP = self.proba_dist.log_proba(dist_params, X) return X, logP self._sample_func = jit(sample_func) return self._sample_func @property def mean_func(self): r""" The function that is used for getting the mean of the distribution, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mean_func(obj.params, obj.function_state, obj.rng, *inputs) """ if not hasattr(self, '_mean_func'): def mean_func(params, state, rng, S): dist_params, _ = self.function(params, state, rng, S, False) return self.proba_dist.mean(dist_params) self._mean_func = jit(mean_func) return self._mean_func @property def mode_func(self): r""" The function that is used for getting the mode of the distribution, defined as a JIT-compiled pure function. This function may be called directly as: .. code:: python output = obj.mode_func(obj.params, obj.function_state, obj.rng, *inputs) """ if not hasattr(self, '_mode_func'): def mode_func(params, state, rng, S): dist_params, _ = self.function(params, state, rng, S, False) return self.proba_dist.mode(dist_params) self._mode_func = jit(mode_func) return self._mode_func class BaseStochasticFuncType2(BaseFunc, StochasticFuncType2Mixin): r""" An abstract base class for stochastic function that take *only states* as input: * Policy * StochasticV * StateDensity """ def __init__( self, func, observation_space, action_space, observation_preprocessor, proba_dist, random_seed): self.observation_preprocessor = observation_preprocessor self.proba_dist = proba_dist # note: self._modeltype is set in super().__init__ via self._check_signature super().__init__( func=func, observation_space=observation_space, action_space=action_space, random_seed=random_seed) @classmethod def example_data( cls, env, observation_preprocessor=None, proba_dist=None, batch_size=1, random_seed=None): if not isinstance(env.observation_space, Space): raise TypeError( "env.observation_space must be derived from gymnasium.Space, " f"got: {type(env.observation_space)}") if not isinstance(env.action_space, Space): raise TypeError( "env.action_space must be derived from gymnasium.Space, " f"got: {type(env.action_space)}") # these must be provided assert observation_preprocessor is not None assert proba_dist is not None rnd = onp.random.RandomState(random_seed) rngs = hk.PRNGSequence(rnd.randint(jnp.iinfo('int32').max)) # input: state observations S = [safe_sample(env.observation_space, rnd) for _ in range(batch_size)] S = [observation_preprocessor(next(rngs), s) for s in S] S = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *S) # output dist_params = jax.tree_map( lambda x: jnp.asarray(rnd.randn(batch_size, *x.shape[1:])), proba_dist.default_priors) return ExampleData( inputs=Inputs(args=ArgsType2(S=S, is_training=True), static_argnums=(1,)), output=dist_params, ) def _check_signature(self, func): if tuple(signature(func).parameters) != ('S', 'is_training'): sig = ', '.join(signature(func).parameters) raise TypeError( f"func has bad signature; expected: func(S, is_training), got: func({sig})") Env = namedtuple('Env', ('observation_space', 'action_space')) return BaseStochasticFuncType2.example_data( env=Env(self.observation_space, self.action_space), observation_preprocessor=self.observation_preprocessor, proba_dist=self.proba_dist, batch_size=1, random_seed=self.random_seed, ) def _check_output(self, actual, expected): expected_leaves, expected_structure = jax.tree_util.tree_flatten(expected) actual_leaves, actual_structure = jax.tree_util.tree_flatten(actual) assert all(isinstance(x, jnp.ndarray) for x in expected_leaves), "bad example_data" if actual_structure != expected_structure: raise TypeError( f"func has bad return tree_structure, expected: {expected_structure}, " f"got: {actual_structure}") if not all(isinstance(x, jnp.ndarray) for x in actual_leaves): bad_types = tuple(type(x) for x in actual_leaves if not isinstance(x, jnp.ndarray)) raise TypeError( "all leaves of dist_params must be of type: jax.numpy.ndarray, " f"found leaves of type: {bad_types}") if not all(a.shape == b.shape for a, b in zip(actual_leaves, expected_leaves)): shapes_tree = jax.tree_map( lambda a, b: f"{a.shape} {'!=' if a.shape != b.shape else '=='} {b.shape}", actual, expected) raise TypeError(f"found leaves with unexpected shapes: {shapes_tree}")
7,645
35.583732
98
py
null
coax-main/coax/_core/policy.py
from ..utils import default_preprocessor from ..proba_dists import ProbaDist from .base_stochastic_func_type2 import BaseStochasticFuncType2 class Policy(BaseStochasticFuncType2): r""" A parametrized policy :math:`\pi_\theta(a|s)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. proba_dist : ProbaDist, optional A probability distribution that is used to interpret the output of :code:`func <coax.Policy.func>`. Check out the :mod:`coax.proba_dists` module for available options. If left unspecified, this defaults to: .. code:: python proba_dist = coax.proba_dists.ProbaDist(action_space) random_seed : int, optional Seed for pseudo-random number generators. """ def __init__(self, func, env, observation_preprocessor=None, proba_dist=None, random_seed=None): # defaults if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if proba_dist is None: proba_dist = ProbaDist(env.action_space) super().__init__( func=func, observation_space=env.observation_space, action_space=env.action_space, observation_preprocessor=observation_preprocessor, proba_dist=proba_dist, random_seed=random_seed) def __call__(self, s, return_logp=False): r""" Sample an action :math:`a\sim\pi_\theta(.|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. return_logp : bool, optional Whether to return the log-propensity :math:`\log\pi(a|s)`. Returns ------- a : action A single action :math:`a`. logp : float, optional The log-propensity :math:`\log\pi_\theta(a|s)`. This is only returned if we set ``return_logp=True``. """ return super().__call__(s, return_logp=return_logp) def mean(self, s): r""" Get the mean of the distribution :math:`\pi_\theta(.|s)`. Note that if the actions are discrete, this returns the :attr:`mode` instead. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- a : action A single action :math:`a`. """ return super().mean(s) def mode(self, s): r""" Sample a greedy action :math:`a=\arg\max_a\pi_\theta(a|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- a : action A single action :math:`a`. """ return super().mode(s) def dist_params(self, s): r""" Get the conditional distribution parameters of :math:`\pi_\theta(.|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- dist_params : Params The distribution parameters of :math:`\pi_\theta(.|s)`. """ return super().dist_params(s) @classmethod def example_data( cls, env, observation_preprocessor=None, proba_dist=None, batch_size=1, random_seed=None): # defaults if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if proba_dist is None: proba_dist = ProbaDist(env.action_space) return super().example_data( env=env, observation_preprocessor=observation_preprocessor, proba_dist=proba_dist, batch_size=batch_size, random_seed=random_seed)
4,373
25.509091
100
py
null
coax-main/coax/_core/policy_test.py
from functools import partial from collections import namedtuple import gymnasium import jax import jax.numpy as jnp import numpy as onp import haiku as hk from .._base.test_case import TestCase from ..utils import safe_sample from .policy import Policy discrete = gymnasium.spaces.Discrete(7) boxspace = gymnasium.spaces.Box(low=0, high=1, shape=(3, 5)) Env = namedtuple('Env', ('observation_space', 'action_space')) def func_discrete(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n), )) return {'logits': seq(S)} def func_boxspace(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) mu = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape)), hk.Reshape(boxspace.shape), )) logvar = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape)), hk.Reshape(boxspace.shape), )) return {'mu': mu(S), 'logvar': logvar(S)} class TestPolicy(TestCase): def test_init(self): msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logvar': \*, 'mu': \*}\), " r"got: PyTreeDef\({'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): Policy(func_discrete, Env(boxspace, boxspace)) msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'logvar': \*, 'mu': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): Policy(func_boxspace, Env(boxspace, discrete)) # these should all be fine Policy(func_discrete, Env(boxspace, discrete)) Policy(func_boxspace, Env(boxspace, boxspace)) def test_call_discrete(self): env = Env(boxspace, discrete) s = safe_sample(boxspace, seed=17) pi = Policy(func_discrete, env, random_seed=19) a = pi(s) print(a, discrete) self.assertTrue(discrete.contains(a)) self.assertEqual(a, 3) def test_call_box(self): env = Env(boxspace, boxspace) s = safe_sample(boxspace, seed=17) pi = Policy(func_boxspace, env, random_seed=19) a = pi(s) print(type(a), a.shape, a.dtype) print(a) self.assertTrue(boxspace.contains(a)) self.assertArrayShape(a, (3, 5)) self.assertArraySubdtypeFloat(a) def test_greedy_discrete(self): env = Env(boxspace, discrete) s = safe_sample(boxspace, seed=17) pi = Policy(func_discrete, env, random_seed=19) a = pi.mode(s) self.assertTrue(discrete.contains(a)) def test_greedy_box(self): env = Env(boxspace, boxspace) s = safe_sample(boxspace, seed=17) pi = Policy(func_boxspace, env, random_seed=19) a = pi.mode(s) print(type(a), a.shape, a.dtype) print(a) self.assertTrue(boxspace.contains(a)) self.assertArrayShape(a, (3, 5)) self.assertArraySubdtypeFloat(a) def test_function_state(self): env = Env(boxspace, discrete) pi = Policy(func_discrete, env, random_seed=19) print(pi.function_state) batch_norm_avg = pi.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, is_training\), got: func\(S, is_training, x\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) Policy(badfunc, env, random_seed=13) def test_bad_output_structure(self): def badfunc(S, is_training): dist_params = func_discrete(S, is_training) dist_params['foo'] = jnp.zeros(1) return dist_params msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'foo': \*, 'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) Policy(badfunc, env, random_seed=13)
5,038
31.934641
80
py
null
coax-main/coax/_core/q.py
from inspect import signature from collections import namedtuple import jax import jax.numpy as jnp import numpy as onp import haiku as hk from gymnasium.spaces import Space, Discrete from ..utils import safe_sample, default_preprocessor from ..value_transforms import ValueTransform from .base_func import BaseFunc, ExampleData, Inputs, ArgsType1, ArgsType2, ModelTypes __all__ = ( 'Q', ) class Q(BaseFunc): r""" A state-action value function :math:`q_\theta(s,a)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. The function signature must be the same as the example below. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed such that: .. math:: \tilde{q}_\theta(S_t, A_t)\ \approx\ f(G_t) This means that calling the function involves undoing this transformation: .. math:: q(s, a)\ =\ f^{-1}(\tilde{q}_\theta(s, a)) Here, :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, observation_preprocessor=None, action_preprocessor=None, value_transform=None, random_seed=None): self.observation_preprocessor = observation_preprocessor self.action_preprocessor = action_preprocessor self.value_transform = value_transform # defaults if self.observation_preprocessor is None: self.observation_preprocessor = default_preprocessor(env.observation_space) if self.action_preprocessor is None: self.action_preprocessor = default_preprocessor(env.action_space) if self.value_transform is None: self.value_transform = ValueTransform(lambda x: x, lambda x: x) if not isinstance(self.value_transform, ValueTransform): self.value_transform = ValueTransform(*value_transform) super().__init__( func, observation_space=env.observation_space, action_space=env.action_space, random_seed=random_seed) def __call__(self, s, a=None): r""" Evaluate the state-action function on a state observation :math:`s` or on a state-action pair :math:`(s, a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action A single action :math:`a`. Returns ------- q_sa or q_s : ndarray Depending on whether :code:`a` is provided, this either returns a scalar representing :math:`q(s,a)\in\mathbb{R}` or a vector representing :math:`q(s,.)\in\mathbb{R}^n`, where :math:`n` is the number of discrete actions. Naturally, this only applies for discrete action spaces. """ S = self.observation_preprocessor(self.rng, s) if a is None: Q, _ = self.function_type2(self.params, self.function_state, self.rng, S, False) else: A = self.action_preprocessor(self.rng, a) Q, _ = self.function_type1(self.params, self.function_state, self.rng, S, A, False) Q = self.value_transform.inverse_func(Q) return onp.asarray(Q[0]) @property def function_type1(self): r""" Same as :attr:`function`, except that it ensures a type-1 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 1: return self.function assert isinstance(self.action_space, Discrete) def q1_func(q2_params, q2_state, rng, S, A, is_training): assert A.ndim == 2 assert A.shape[1] == self.action_space.n Q_s, state_new = self.function(q2_params, q2_state, rng, S, is_training) Q_sa = jax.vmap(jnp.dot)(A, Q_s) return Q_sa, state_new return q1_func @property def function_type2(self): r""" Same as :attr:`function`, except that it ensures a type-2 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 2: return self.function if not isinstance(self.action_space, Discrete): raise ValueError( "input 'A' is required for type-1 q-function when action space is non-Discrete") n = self.action_space.n def q2_func(q1_params, q1_state, rng, S, is_training): rngs = hk.PRNGSequence(rng) batch_size = jax.tree_util.tree_leaves(S)[0].shape[0] # example: let S = [7, 2, 5, 8] and num_actions = 3, then # S_rep = [7, 7, 7, 2, 2, 2, 5, 5, 5, 8, 8, 8] # repeated # A_rep = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] # tiled S_rep = jax.tree_map(lambda x: jnp.repeat(x, n, axis=0), S) A_rep = jnp.tile(jnp.arange(n), batch_size) A_rep = self.action_preprocessor(next(rngs), A_rep) # one-hot encoding # evaluate on replicas => output shape: (batch * num_actions, 1) Q_sa_rep, state_new = \ self.function(q1_params, q1_state, next(rngs), S_rep, A_rep, is_training) Q_s = Q_sa_rep.reshape(-1, n) # shape: (batch, num_actions) return Q_s, state_new return q2_func @property def modeltype(self): r""" Specifier for how the q-function is modeled, i.e. .. math:: (s,a) &\mapsto q(s,a)\in\mathbb{R} &\qquad (\text{modeltype} &= 1) \\ s &\mapsto q(s,.)\in\mathbb{R}^n &\qquad (\text{modeltype} &= 2) Note that modeltype=2 is only well-defined if the action space is :class:`Discrete <gymnasium.spaces.Discrete>`. Namely, :math:`n` is the number of discrete actions. """ return self._modeltype @classmethod def example_data( cls, env, observation_preprocessor=None, action_preprocessor=None, batch_size=1, random_seed=None): if not isinstance(env.observation_space, Space): raise TypeError( "env.observation_space must be derived from gymnasium.Space, " f"got: {type(env.observation_space)}") if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) rnd = onp.random.RandomState(random_seed) rngs = hk.PRNGSequence(rnd.randint(jnp.iinfo('int32').max)) # input: state observations S = [safe_sample(env.observation_space, rnd) for _ in range(batch_size)] S = [observation_preprocessor(next(rngs), s) for s in S] S = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *S) # input: actions A = [safe_sample(env.action_space, rnd) for _ in range(batch_size)] A = [action_preprocessor(next(rngs), a) for a in A] A = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *A) # output: type1 q1_data = ExampleData( inputs=Inputs(args=ArgsType1(S=S, A=A, is_training=True), static_argnums=(2,)), output=jnp.asarray(rnd.randn(batch_size)), ) if not isinstance(env.action_space, Discrete): return ModelTypes(type1=q1_data, type2=None) # output: type2 (if actions are discrete) q2_data = ExampleData( inputs=Inputs(args=ArgsType2(S=S, is_training=True), static_argnums=(1,)), output=jnp.asarray(rnd.randn(batch_size, env.action_space.n)), ) return ModelTypes(type1=q1_data, type2=q2_data) def _check_signature(self, func): sig_type1 = ('S', 'A', 'is_training') sig_type2 = ('S', 'is_training') sig = tuple(signature(func).parameters) if sig not in (sig_type1, sig_type2): sig = ', '.join(sig) alt = ' or func(S, is_training)' if isinstance(self.action_space, Discrete) else '' raise TypeError( f"func has bad signature; expected: func(S, A, is_training){alt}, got: func({sig})") if sig == sig_type2 and not isinstance(self.action_space, Discrete): raise TypeError("type-2 q-functions are only well-defined for Discrete action spaces") Env = namedtuple('Env', ('observation_space', 'action_space')) example_data_per_modeltype = self.example_data( env=Env(self.observation_space, self.action_space), action_preprocessor=self.action_preprocessor, batch_size=1, random_seed=self.random_seed) if sig == sig_type1: self._modeltype = 1 example_data = example_data_per_modeltype.type1 else: self._modeltype = 2 example_data = example_data_per_modeltype.type2 return example_data def _check_output(self, actual, expected): if not isinstance(actual, jnp.ndarray): class_name = actual.__class__.__name__ raise TypeError(f"func has bad return type; expected jnp.ndarray, got {class_name}") if not jnp.issubdtype(actual.dtype, jnp.floating): raise TypeError( "func has bad return dtype; expected a subdtype of jnp.floating, " f"got dtype={actual.dtype}") if actual.shape != expected.shape: raise TypeError( f"func has bad return shape, expected: {expected.shape}, got: {actual.shape}")
10,806
35.265101
100
py
null
coax-main/coax/_core/q_test.py
from functools import partial import jax import jax.numpy as jnp import numpy as onp import haiku as hk from .._base.test_case import TestCase, DiscreteEnv, BoxEnv from ..utils import safe_sample from .q import Q env_discrete = DiscreteEnv(random_seed=13) env_boxspace = BoxEnv(random_seed=17) def func_type1(S, A, is_training): seq = hk.Sequential(( hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(hk.BatchNorm(False, False, 0.99), is_training=is_training), hk.Linear(8), jax.nn.relu, hk.Linear(1), jnp.ravel, )) S = hk.Flatten()(S) A = hk.Flatten()(A) X = jnp.concatenate((S, A), axis=-1) return seq(X) def func_type2(S, is_training): seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(hk.BatchNorm(False, False, 0.99), is_training=is_training), hk.Linear(8), jax.nn.relu, hk.Linear(env_discrete.action_space.n), )) return seq(S) class TestQ(TestCase): decimal = 5 def test_init(self): # cannot define a type-2 q-function on a non-discrete action space msg = r"type-2 q-functions are only well-defined for Discrete action spaces" with self.assertRaisesRegex(TypeError, msg): Q(func_type2, env_boxspace) # these should all be fine Q(func_type1, env_boxspace) Q(func_type1, env_discrete) Q(func_type2, env_discrete) def test_call_type1_discrete(self): env = env_discrete func = func_type1 s = safe_sample(env.observation_space, seed=19) a = safe_sample(env.action_space, seed=19) q = Q(func, env, random_seed=42) # without a q_s = q(s) self.assertArrayShape(q_s, (env.action_space.n,)) self.assertArraySubdtypeFloat(q_s) # with a q_sa = q(s, a) self.assertArrayShape(q_sa, ()) self.assertArraySubdtypeFloat(q_s) self.assertArrayAlmostEqual(q_sa, q_s[a]) def test_call_type2_discrete(self): env = env_discrete func = func_type2 s = safe_sample(env.observation_space, seed=19) a = safe_sample(env.action_space, seed=19) q = Q(func, env, random_seed=42) # without a q_s = q(s) self.assertArrayShape(q_s, (env.action_space.n,)) self.assertArraySubdtypeFloat(q_s) # with a q_sa = q(s, a) self.assertArrayShape(q_sa, ()) self.assertArraySubdtypeFloat(q_s) self.assertArrayAlmostEqual(q_sa, q_s[a]) def test_call_type1_box(self): env = env_boxspace func = func_type1 s = safe_sample(env.observation_space, seed=19) a = safe_sample(env.action_space, seed=19) q = Q(func, env, random_seed=42) # type-1 requires a if actions space is non-discrete msg = r"input 'A' is required for type-1 q-function when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): q(s) # with a q_sa = q(s, a) self.assertArrayShape(q_sa, ()) self.assertArraySubdtypeFloat(q_sa) def test_apply_q1_as_q2(self): env = env_discrete func = func_type1 q = Q(func, env, random_seed=42) n = env.action_space.n # num_actions def q1_func(params, state, rng, S, A, is_training): A = jnp.argmax(A, axis=1) return jnp.array([encode(s, a) for s, a in zip(S, A)]), state def encode(s, a): return 2 ** a + 2 ** (s + n) def decode(i): b = onp.array(list(bin(i)))[::-1] a = onp.argwhere(b[:n] == '1').item() s = onp.argwhere(b[n:] == '1').item() return s, a q._function = q1_func rng = jax.random.PRNGKey(0) params = () state = () is_training = True S = jnp.array([5, 7, 11, 13, 17, 19, 23]) encoded_rows, _ = q.function_type2(params, state, rng, S, is_training) for s, encoded_row in zip(S, encoded_rows): for a, x in enumerate(encoded_row): s_, a_ = decode(x) self.assertEqual(s_, s) self.assertEqual(a_, a) def test_apply_q2_as_q1(self): env = env_discrete func = func_type2 q = Q(func, env, random_seed=42) n = env.action_space.n # num_actions def q2_func(params, state, rng, S, is_training): batch_size = jax.tree_util.tree_leaves(S)[0].shape[0] return jnp.tile(jnp.arange(n), reps=(batch_size, 1)), state q._function = q2_func rng = jax.random.PRNGKey(0) params = () state = () is_training = True S = jnp.array([5, 7, 11, 13, 17, 19, 23]) A = jnp.array([2, 0, 1, 1, 0, 1, 2]) A_onehot = q.action_preprocessor(q.rng, A) Q_sa, _ = q.function_type1(params, state, rng, S, A_onehot, is_training) self.assertArrayAlmostEqual(Q_sa, A) def test_soft_update(self): tau = 0.13 env = env_discrete func = func_type1 q = Q(func, env, random_seed=42) q_targ = q.copy() q.params = jax.tree_map(jnp.ones_like, q.params) q_targ.params = jax.tree_map(jnp.zeros_like, q.params) expected = jax.tree_map(lambda a: jnp.full_like(a, tau), q.params) q_targ.soft_update(q, tau=tau) self.assertPytreeAlmostEqual(q_targ.params, expected) def test_function_state(self): env = env_discrete func = func_type1 q = Q(func, env, random_seed=42) print(q.function_state) batch_norm_avg = q.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) def test_bad_input_signature(self): env = env_discrete def badfunc(S, A, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, A, is_training\) or func\(S, is_training\), " r"got: func\(S, A, is_training, x\)") with self.assertRaisesRegex(TypeError, msg): Q(badfunc, env) def test_bad_output_type(self): env = env_discrete def badfunc(S, A, is_training): return 'garbage' msg = r"(?:is not a valid JAX type|func has bad return type)" with self.assertRaisesRegex(TypeError, msg): Q(badfunc, env) def test_bad_output_shape_type1(self): env = env_discrete def badfunc(S, A, is_training): Q = func_type1(S, A, is_training) return jnp.expand_dims(Q, axis=-1) msg = r"func has bad return shape, expected: \(1,\), got: \(1, 1\)" with self.assertRaisesRegex(TypeError, msg): Q(badfunc, env) def test_bad_output_shape_type2(self): env = env_discrete def badfunc(S, is_training): Q = func_type2(S, is_training) return Q[:, :2] msg = r"func has bad return shape, expected: \(1, 3\), got: \(1, 2\)" with self.assertRaisesRegex(TypeError, msg): Q(badfunc, env) def test_bad_output_dtype(self): env = env_discrete def badfunc(S, A, is_training): Q = func_type1(S, A, is_training) return Q.astype('int32') msg = r"func has bad return dtype; expected a subdtype of jnp\.floating, got dtype=int32" with self.assertRaisesRegex(TypeError, msg): Q(badfunc, env)
7,736
31.783898
97
py
null
coax-main/coax/_core/random_policy.py
import gymnasium import jax.numpy as jnp import numpy as onp from ..utils import docstring from .policy import Policy __all__ = ( 'RandomPolicy', ) class RandomPolicy: r""" A simple random policy. Parameters ---------- env : gymnasium.Env The gymnasium-style environment. This is only used to get the :code:`env.action_space`. random_seed : int, optional Sets the random state to get reproducible results. """ def __init__(self, env, random_seed=None): if not isinstance(env.action_space, gymnasium.Space): raise TypeError( f"env.action_space must be a gymnasium.Space, got: {type(env.action_space)}") self.action_space = env.action_space self.action_space.seed(random_seed) self.random_seed = random_seed @docstring(Policy.__call__) def __call__(self, s, return_logp=False): a = self.action_space.sample() if not return_logp: return a if isinstance(self.action_space, gymnasium.spaces.Discrete): logp = -onp.log(self.num_actions) return a, logp if isinstance(self.action_space, gymnasium.spaces.Box): sizes = self.action_space.high - self.action_space.low logp = -onp.sum(onp.log(sizes)) # log(prod(1/sizes)) return a, logp raise NotImplementedError( "the log-propensity of a 'uniform' distribution over a " f"{self.action_space.__class__.__name__} space is not yet implemented; " "please submit a feature request") @docstring(Policy.mode) def mode(self, s): return self(s, return_logp=False) @docstring(Policy.dist_params) def dist_params(self, s): if isinstance(self.action_space, gymnasium.spaces.Discrete): return {'logits': jnp.zeros(self.action_space.n)} if isinstance(self.action_space, gymnasium.spaces.Box): return { 'mu': jnp.zeros(self.action_space.shape), 'logvar': 15 * jnp.ones(self.action_space.shape)} raise NotImplementedError( "the dist_params of a 'uniform' distribution over a " f"{self.action_space.__class__.__name__} space is not yet implemented; " "please submit a feature request")
2,336
29.75
95
py
null
coax-main/coax/_core/random_policy_test.py
from functools import partial import gymnasium import jax import haiku as hk import numpy as onp from .._base.test_case import TestCase from .random_policy import RandomPolicy env = gymnasium.make('FrozenLakeNonSlippery-v0') def func_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jax.nn.relu, hk.Linear(env.action_space.n), )) return seq(S) class TestRandomPolicy(TestCase): def setUp(self): self.env = gymnasium.make('FrozenLakeNonSlippery-v0') def tearDown(self): del self.env def test_call(self): pi = RandomPolicy(self.env) s = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_greedy(self): pi = RandomPolicy(self.env) s = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi.mode(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_dist_params(self): pi = RandomPolicy(self.env) s = self.env.observation_space.sample() dist_params = pi.dist_params(s) print(onp.exp(dist_params['logits'])) self.assertEqual(dist_params['logits'].shape, (self.env.action_space.n,))
1,627
26.59322
81
py
null
coax-main/coax/_core/reward_function.py
from .q import Q __all__ = ( 'RewardFunction', ) class RewardFunction(Q): r""" A deterministic reward function :math:`r_\theta(s,a)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. The function signature must be the same as the example below. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed such that: .. math:: \tilde{q}_\theta(S_t, A_t)\ \approx\ f(G_t) This means that calling the function involves undoing this transformation: .. math:: q(s, a)\ =\ f^{-1}(\tilde{q}_\theta(s, a)) Here, :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """
1,889
29.483871
99
py
null
coax-main/coax/_core/stochastic_q.py
from gymnasium.spaces import Box from ..utils import default_preprocessor from ..proba_dists import DiscretizedIntervalDist, EmpiricalQuantileDist from ..value_transforms import ValueTransform from .base_stochastic_func_type1 import BaseStochasticFuncType1 __all__ = ( 'StochasticQ', ) class StochasticQ(BaseStochasticFuncType1): r""" A q-function :math:`q(s,a)`, represented by a stochastic function :math:`\mathbb{P}_\theta(G_t|S_t=s,A_t=a)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. value_range : tuple of floats, optional A pair of floats :code:`(min_value, max_value)`. If no :code:`value_range` is given, :code:`num_bins` is the number of bins of the quantile function as in `IQN <https://arxiv.org/abs/1806.06923>`_ or `QR-DQN <https://arxiv.org/abs/1710.10044>`_. num_bins : int, optional If :code:`value_range` is given: The space of rewards is discretized in :code:`num_bins` equal sized bins. We use the default setting of 51 as suggested in the `Distributional RL <https://arxiv.org/abs/1707.06887>`_ paper. Else: The number of fractions of the quantile function of the rewards is defined by :code:`num_bins` as in `IQN <https://arxiv.org/abs/1806.06923>`_ or `QR-DQN <https://arxiv.org/abs/1710.10044>`_. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed: .. math:: \tilde{G}_t\ =\ f(G_t) This means that calling the function involves undoing this transformation using its inverse :math:`f^{-1}`. The functions :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, value_range=None, num_bins=51, observation_preprocessor=None, action_preprocessor=None, value_transform=None, random_seed=None): self.value_transform = value_transform proba_dist = self._get_proba_dist(value_transform, num_bins, value_range) # set defaults if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) if self.value_transform is None: self.value_transform = ValueTransform(lambda x: x, lambda x: x) if not isinstance(self.value_transform, ValueTransform): self.value_transform = ValueTransform(*value_transform) super().__init__( func=func, observation_space=env.observation_space, action_space=env.action_space, observation_preprocessor=observation_preprocessor, action_preprocessor=action_preprocessor, proba_dist=proba_dist, random_seed=random_seed) @property def num_bins(self): return self.proba_dist.space.n @classmethod def example_data( cls, env, value_range, num_bins=51, observation_preprocessor=None, action_preprocessor=None, value_transform=None, batch_size=1, random_seed=None): value_range = cls._check_value_range(value_range) proba_dist = cls._get_proba_dist(value_transform, num_bins, value_range) if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) return super().example_data( env=env, observation_preprocessor=observation_preprocessor, action_preprocessor=action_preprocessor, proba_dist=proba_dist, batch_size=batch_size, random_seed=random_seed) def __call__(self, s, a=None, return_logp=False): r""" Sample a value. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. return_logp : bool, optional Whether to return the log-propensity associated with the sampled output value. Returns ------- value : float or list thereof Depending on whether :code:`a` is provided, this either returns a single value or a list of :math:`n` values, one for each discrete action. logp : non-positive float or list thereof, optional The log-propensity associated with the sampled output value. This is only returned if we set ``return_logp=True``. Depending on whether :code:`a` is provided, this is either a single float or a list of :math:`n` floats, one for each discrete action. """ return super().__call__(s, a=a, return_logp=return_logp) def mean(self, s, a=None): r""" Get the mean value. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- value : float or list thereof Depending on whether :code:`a` is provided, this either returns a single value or a list of :math:`n` values, one for each discrete action. """ return super().mean(s, a=a) def mode(self, s, a=None): r""" Get the most probable value. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- value : float or list thereof Depending on whether :code:`a` is provided, this either returns a single value or a list of :math:`n` values, one for each discrete action. """ return super().mode(s, a=a) def dist_params(self, s, a=None): r""" Get the parameters of the underlying (conditional) probability distribution. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- dist_params : dict or list of dicts Depending on whether :code:`a` is provided, this either returns a single dist-params dict or a list of :math:`n` such dicts, one for each discrete action. """ return super().dist_params(s, a=a) @staticmethod def _get_proba_dist(value_transform, num_bins, value_range): if value_range is not None: if value_transform is not None: f, _ = value_transform value_range = f(value_range[0]), f(value_range[1]) reward_space = Box(*value_range, shape=()) return DiscretizedIntervalDist(reward_space, num_bins) else: return EmpiricalQuantileDist(num_quantiles=num_bins) @staticmethod def _check_value_range(value_range): if not (isinstance(value_range, (tuple, list)) and len(value_range) == 2 and isinstance(value_range[0], (int, float)) and isinstance(value_range[1], (int, float)) and value_range[0] < value_range[1]): raise TypeError("value_range is not a valid pair tuple of floats: (low, high)") return float(value_range[0]), float(value_range[1])
9,039
33.503817
100
py
null
coax-main/coax/_core/stochastic_q_test.py
from functools import partial from collections import namedtuple import jax import jax.numpy as jnp import haiku as hk from gymnasium.spaces import Discrete, Box from .._base.test_case import TestCase from ..utils import safe_sample, quantile_cos_embedding, quantiles, quantiles_uniform from .stochastic_q import StochasticQ discrete = Discrete(7) boxspace = Box(low=0, high=1, shape=(3, 5)) num_bins = 20 Env = namedtuple('Env', ('observation_space', 'action_space')) def func_type1(S, A, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) logits = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(num_bins), )) X = jax.vmap(jnp.kron)(S, A) return {'logits': logits(X)} def func_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) logits = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n * num_bins), hk.Reshape((discrete.n, num_bins)), )) return {'logits': logits(S)} def quantile_net(x, quantile_fractions): x_size = x.shape[-1] x_tiled = jnp.tile(x[:, None, :], [num_bins, 1]) quantiles_emb = quantile_cos_embedding(quantile_fractions) quantiles_emb = hk.Linear(x_size)(quantiles_emb) quantiles_emb = hk.LayerNorm(axis=-1, create_scale=True, create_offset=True)(quantiles_emb) quantiles_emb = jax.nn.sigmoid(quantiles_emb) x = x_tiled * quantiles_emb x = hk.Linear(x_size)(x) x = jax.nn.relu(x) return x def func_quantile_type1(S, A, is_training): """ type-1 q-function: (s,a) -> q(s,a) """ encoder = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu )) quantile_fractions = quantiles(batch_size=jax.tree_util.tree_leaves(S)[0].shape[0], num_quantiles=num_bins) X = jax.vmap(jnp.kron)(S, A) x = encoder(X) quantile_x = quantile_net(x, quantile_fractions=quantile_fractions) quantile_values = hk.Linear(1)(quantile_x) return {'values': quantile_values.squeeze(axis=-1), 'quantile_fractions': quantile_fractions} def func_quantile_type2(S, is_training): """ type-1 q-function: (s,a) -> q(s,a) """ encoder = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu )) quantile_fractions = quantiles_uniform(rng=hk.next_rng_key(), batch_size=jax.tree_util.tree_leaves(S)[0].shape[0], num_quantiles=num_bins) x = encoder(S) quantile_x = quantile_net(x, quantile_fractions=quantile_fractions) quantile_values = hk.Sequential(( hk.Linear(discrete.n), hk.Reshape((discrete.n, num_bins)) ))(quantile_x) return {'values': quantile_values, 'quantile_fractions': jnp.tile(quantile_fractions[:, None, :], [1, discrete.n, 1])} class TestStochasticQ(TestCase): def test_init(self): # cannot define a type-2 models on a non-discrete action space msg = r"type-2 models are only well-defined for Discrete action spaces" with self.assertRaisesRegex(TypeError, msg): StochasticQ(func_type2, Env(boxspace, boxspace), (-10, 10), num_bins=num_bins) # these should all be fine StochasticQ(func_type1, Env(discrete, discrete), (-10, 10), num_bins=num_bins) StochasticQ(func_type1, Env(discrete, boxspace), (-10, 10), num_bins=num_bins) StochasticQ(func_type1, Env(boxspace, boxspace), (-10, 10), num_bins=num_bins) StochasticQ(func_type2, Env(discrete, discrete), (-10, 10), num_bins=num_bins) StochasticQ(func_type2, Env(boxspace, discrete), (-10, 10), num_bins=num_bins) StochasticQ(func_quantile_type1, Env(discrete, discrete), num_bins=num_bins) StochasticQ(func_quantile_type1, Env(discrete, boxspace), num_bins=num_bins) StochasticQ(func_quantile_type1, Env(boxspace, boxspace), num_bins=num_bins) StochasticQ(func_quantile_type2, Env(discrete, discrete), num_bins=num_bins) StochasticQ(func_quantile_type2, Env(boxspace, discrete), num_bins=num_bins) # test_call_* ################################################################################## def test_call_discrete_discrete_type1(self): func = func_type1 env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for q_ in q(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_call_discrete_discrete_type2(self): func = func_type2 env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for q_ in q(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_call_boxspace_discrete_type1(self): func = func_type1 env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for q_ in q(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_call_boxspace_discrete_type2(self): func = func_type2 env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for q_ in q(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_call_discrete_boxspace(self): func = func_type1 env = Env(discrete, boxspace) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): q(s) def test_call_boxspace_boxspace(self): func = func_type1 env = Env(boxspace, boxspace) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_, logp = q(s, a, return_logp=True) print(q_, logp, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): q(s) # test_mode_* ################################################################################## def test_mode_discrete_discrete_type1(self): func = func_type1 env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) for q_ in q.mode(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_mode_discrete_discrete_type2(self): func = func_type2 env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) for q_ in q.mode(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_mode_boxspace_discrete_type1(self): func = func_type1 env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) for q_ in q.mode(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_mode_boxspace_discrete_type2(self): func = func_type2 env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) for q_ in q.mode(s): print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) def test_mode_discrete_boxspace(self): func = func_type1 env = Env(discrete, boxspace) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): q.mode(s) def test_mode_boxspace_boxspace(self): func = func_type1 env = Env(boxspace, boxspace) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) q_ = q.mode(s, a) print(q_, env.observation_space) self.assertIn(q_, Box(*value_range, shape=())) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): q.mode(s) def test_function_state(self): func = func_type1 env = Env(discrete, discrete) value_range = (-10, 10) q = StochasticQ(func, env, value_range, num_bins=num_bins, random_seed=19) print(q.function_state) batch_norm_avg = q.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) # other tests ################################################################################## def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, A, is_training\) or func\(S, is_training\), " r"got: func\(S, is_training, x\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) value_range = (-10, 10) StochasticQ(badfunc, env, value_range, num_bins=num_bins, random_seed=13) def test_bad_output_structure(self): def badfunc(S, is_training): dist_params = func_type2(S, is_training) dist_params['foo'] = jnp.zeros(1) return dist_params msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'foo': \*, 'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(discrete, discrete) value_range = (-10, 10) StochasticQ(badfunc, env, value_range, num_bins=num_bins, random_seed=13)
14,291
36.909814
100
py
null
coax-main/coax/_core/stochastic_reward_function.py
from .stochastic_q import StochasticQ __all__ = ( 'StochasticRewardFunction', ) class StochasticRewardFunction(StochasticQ): r""" A stochastic reward function :math:`p_\theta(r|s,a)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. value_range : tuple of floats, optional A pair of floats :code:`(min_value, max_value)`. If left unspecifed, this defaults to :code:`env.reward_range`. num_bins : int, optional The space of rewards is discretized in :code:`num_bins` equal sized bins. We use the default setting of 51 as suggested in the `Distributional RL <https://arxiv.org/abs/1707.06887>`_ paper. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed: .. math:: \tilde{G}_t\ =\ f(G_t) This means that calling the function involves undoing this transformation using its inverse :math:`f^{-1}`. The functions :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, value_range=None, num_bins=51, observation_preprocessor=None, action_preprocessor=None, value_transform=None, random_seed=None): super().__init__( func, env, value_range=(value_range or env.reward_range), num_bins=51, observation_preprocessor=None, action_preprocessor=None, value_transform=None, random_seed=None)
2,642
33.776316
100
py
null
coax-main/coax/_core/stochastic_transition_model.py
from ..utils import default_preprocessor from ..proba_dists import ProbaDist from .base_stochastic_func_type1 import BaseStochasticFuncType1 __all__ = ( 'StochasticTransitionModel', ) class StochasticTransitionModel(BaseStochasticFuncType1): r""" A stochastic transition model :math:`p_\theta(s'|s,a)`. Here, :math:`s'` is the successor state, given that we take action :math:`a` from state :math:`s`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :attr:`proba_dist.preprocess_variate <coax.proba_dists.ProbaDist.preprocess_variate>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. proba_dist : ProbaDist, optional A probability distribution that is used to interpret the output of :code:`func <coax.Policy.func>`. Check out the :mod:`coax.proba_dists` module for available options. If left unspecified, this defaults to: .. code:: python proba_dist = coax.proba_dists.ProbaDist(observation_space) random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, observation_preprocessor=None, action_preprocessor=None, proba_dist=None, random_seed=None): # set defaults if proba_dist is None: proba_dist = ProbaDist(env.observation_space) if observation_preprocessor is None: observation_preprocessor = proba_dist.preprocess_variate if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) super().__init__( func=func, observation_space=env.observation_space, action_space=env.action_space, observation_preprocessor=observation_preprocessor, action_preprocessor=action_preprocessor, proba_dist=proba_dist, random_seed=random_seed) @classmethod def example_data( cls, env, action_preprocessor=None, proba_dist=None, batch_size=1, random_seed=None): # set defaults if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) if proba_dist is None: proba_dist = ProbaDist(env.observation_space) return super().example_data( env=env, observation_preprocessor=proba_dist.preprocess_variate, action_preprocessor=action_preprocessor, proba_dist=proba_dist, batch_size=batch_size, random_seed=random_seed) def __call__(self, s, a=None, return_logp=False): r""" Sample a successor state :math:`s'` from the dynamics model :math:`p(s'|s,a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. return_logp : bool, optional Whether to return the log-propensity :math:`\log p(s'|s,a)`. Returns ------- s_next : state observation or list thereof Depending on whether :code:`a` is provided, this either returns a single next-state :math:`s'` or a list of :math:`n` next-states, one for each discrete action. logp : non-positive float or list thereof, optional The log-propensity :math:`\log p(s'|s,a)`. This is only returned if we set ``return_logp=True``. Depending on whether :code:`a` is provided, this is either a single float or a list of :math:`n` floats, one for each discrete action. """ return super().__call__(s, a=a, return_logp=return_logp) def mean(self, s, a=None): r""" Get the mean successor state :math:`s'` according to the dynamics model, :math:`s'=\arg\max_{s'}p_\theta(s'|s,a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- s_next : state observation or list thereof Depending on whether :code:`a` is provided, this either returns a single next-state :math:`s'` or a list of :math:`n` next-states, one for each discrete action. """ return super().mean(s, a=a) def mode(self, s, a=None): r""" Get the most probable successor state :math:`s'` according to the dynamics model, :math:`s'=\arg\max_{s'}p_\theta(s'|s,a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- s_next : state observation or list thereof Depending on whether :code:`a` is provided, this either returns a single next-state :math:`s'` or a list of :math:`n` next-states, one for each discrete action. """ return super().mode(s, a=a) def dist_params(self, s, a=None): r""" Get the parameters of the conditional probability distribution :math:`p_\theta(s'|s,a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action, optional A single action :math:`a`. This is *required* if the actions space is non-discrete. Returns ------- dist_params : dict or list of dicts Depending on whether :code:`a` is provided, this either returns a single dist-params dict or a list of :math:`n` such dicts, one for each discrete action. """ return super().dist_params(s, a=a)
6,627
31.174757
100
py
null
coax-main/coax/_core/stochastic_transition_model_test.py
from functools import partial from collections import namedtuple import gymnasium import jax import jax.numpy as jnp import numpy as onp import haiku as hk from .._base.test_case import TestCase from ..utils import safe_sample from .stochastic_transition_model import StochasticTransitionModel discrete = gymnasium.spaces.Discrete(7) boxspace = gymnasium.spaces.Box(low=0, high=1, shape=(3, 5)) Env = namedtuple('Env', ('observation_space', 'action_space')) def func_discrete_type1(S, A, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n), )) X = jax.vmap(jnp.kron)(S, A) return {'logits': seq(X)} def func_discrete_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n * discrete.n), hk.Reshape((discrete.n, discrete.n)), )) return {'logits': seq(S)} def func_boxspace_type1(S, A, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) mu = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape)), hk.Reshape(boxspace.shape), )) logvar = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape)), hk.Reshape(boxspace.shape), )) X = jax.vmap(jnp.kron)(S, A) return {'mu': mu(X), 'logvar': logvar(X)} def func_boxspace_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) mu = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape) * discrete.n), hk.Reshape((discrete.n, *boxspace.shape)), )) logvar = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape) * discrete.n), hk.Reshape((discrete.n, *boxspace.shape)), )) return {'mu': mu(S), 'logvar': logvar(S)} class TestStochasticTransitionModel(TestCase): def test_init(self): # cannot define a type-2 models on a non-discrete action space msg = r"type-2 models are only well-defined for Discrete action spaces" with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_boxspace_type2, Env(boxspace, boxspace)) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_discrete_type2, Env(discrete, boxspace)) msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logvar': \*, 'mu': \*}\), " r"got: PyTreeDef\({'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_discrete_type1, Env(boxspace, discrete)) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_discrete_type2, Env(boxspace, discrete)) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_discrete_type1, Env(boxspace, boxspace)) msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'logvar': \*, 'mu': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_boxspace_type1, Env(discrete, discrete)) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_boxspace_type2, Env(discrete, discrete)) with self.assertRaisesRegex(TypeError, msg): StochasticTransitionModel(func_boxspace_type1, Env(discrete, boxspace)) # these should all be fine StochasticTransitionModel(func_discrete_type1, Env(discrete, boxspace)) StochasticTransitionModel(func_discrete_type1, Env(discrete, discrete)) StochasticTransitionModel(func_discrete_type2, Env(discrete, discrete)) StochasticTransitionModel(func_boxspace_type1, Env(boxspace, boxspace)) StochasticTransitionModel(func_boxspace_type1, Env(boxspace, discrete)) StochasticTransitionModel(func_boxspace_type2, Env(boxspace, discrete)) # test_call_* ################################################################################## def test_call_discrete_discrete_type1(self): func = func_discrete_type1 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_discrete_discrete_type2(self): func = func_discrete_type2 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_boxspace_discrete_type1(self): func = func_boxspace_type1 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_boxspace_discrete_type2(self): func = func_boxspace_type2 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_discrete_boxspace(self): func = func_discrete_type1 env = Env(discrete, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p(s) def test_call_boxspace_boxspace(self): func = func_boxspace_type1 env = Env(boxspace, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next, logp = p(s, a, return_logp=True) print(s_next, logp, env.observation_space) self.assertIn(s_next, env.observation_space) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p(s) # test_mode_* ################################################################################## def test_mode_discrete_discrete_type1(self): func = func_discrete_type1 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p.mode(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_mode_discrete_discrete_type2(self): func = func_discrete_type2 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p.mode(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_mode_boxspace_discrete_type1(self): func = func_boxspace_type1 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p.mode(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_mode_boxspace_discrete_type2(self): func = func_boxspace_type2 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p.mode(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_mode_discrete_boxspace(self): func = func_discrete_type1 env = Env(discrete, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p.mode(s) def test_mode_boxspace_boxspace(self): func = func_boxspace_type1 env = Env(boxspace, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = StochasticTransitionModel(func, env, random_seed=19) s_next = p.mode(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p.mode(s) def test_function_state(self): func = func_discrete_type1 env = Env(discrete, discrete) p = StochasticTransitionModel(func, env, random_seed=19) print(p.function_state) batch_norm_avg = p.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) # other tests ################################################################################## def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, A, is_training\) or func\(S, is_training\), " r"got: func\(S, is_training, x\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) StochasticTransitionModel(badfunc, env, random_seed=13) def test_bad_output_structure(self): def badfunc(S, is_training): dist_params = func_discrete_type2(S, is_training) dist_params['foo'] = jnp.zeros(1) return dist_params msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'foo': \*, 'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(discrete, discrete) StochasticTransitionModel(badfunc, env, random_seed=13)
14,579
37.067885
100
py
null
coax-main/coax/_core/stochastic_v.py
from gymnasium.spaces import Box from ..utils import default_preprocessor from ..proba_dists import DiscretizedIntervalDist from ..value_transforms import ValueTransform from .base_stochastic_func_type2 import BaseStochasticFuncType2 __all__ = ( 'StochasticV', ) class StochasticV(BaseStochasticFuncType2): r""" A state-value function :math:`v(s)`, represented by a stochastic function :math:`\mathbb{P}_\theta(G_t|S_t=s)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. value_range : tuple of floats A pair of floats :code:`(min_value, max_value)`. num_bins : int, optional The space of rewards is discretized in :code:`num_bins` equal sized bins. We use the default setting of 51 as suggested in the `Distributional RL <https://arxiv.org/abs/1707.06887>`_ paper. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed: .. math:: \tilde{G}_t\ =\ f(G_t) This means that calling the function involves undoing this transformation using its inverse :math:`f^{-1}`. The functions :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, value_range, num_bins=51, observation_preprocessor=None, value_transform=None, random_seed=None): self.value_transform = value_transform self.value_range = self._check_value_range(value_range) proba_dist = self._get_proba_dist(self.value_range, value_transform, num_bins) # set defaults if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) if self.value_transform is None: self.value_transform = ValueTransform(lambda x: x, lambda x: x) if not isinstance(self.value_transform, ValueTransform): self.value_transform = ValueTransform(*value_transform) super().__init__( func=func, observation_space=env.observation_space, action_space=env.action_space, observation_preprocessor=observation_preprocessor, proba_dist=proba_dist, random_seed=random_seed) @property def num_bins(self): return self.proba_dist.space.n @classmethod def example_data( cls, env, value_range, num_bins=51, observation_preprocessor=None, value_transform=None, batch_size=1, random_seed=None): value_range = cls._check_value_range(value_range) proba_dist = cls._get_proba_dist(value_range, value_transform, num_bins) if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) return super().example_data( env=env, observation_preprocessor=observation_preprocessor, proba_dist=proba_dist, batch_size=batch_size, random_seed=random_seed) def __call__(self, s, return_logp=False): r""" Sample a value. Parameters ---------- s : state observation A single state observation :math:`s`. return_logp : bool, optional Whether to return the log-propensity associated with the sampled output value. Returns ------- value : float or list thereof A single value associated with the state observation :math:`s`. logp : non-positive float or list thereof, optional The log-propensity associated with the sampled output value. This is only returned if we set ``return_logp=True``. Depending on whether :code:`a` is provided, this is either a single float or a list of :math:`n` floats, one for each discrete action. """ return super().__call__(s, return_logp=return_logp) def mean(self, s): r""" Get the mean value. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- value : float A single value associated with the state observation :math:`s`. """ return super().mean(s) def mode(self, s): r""" Get the most probable value. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- value : float A single value associated with the state observation :math:`s`. """ return super().mode(s) def dist_params(self, s): r""" Get the parameters of the underlying (conditional) probability distribution. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- dist_params : dict or list of dicts Depending on whether :code:`a` is provided, this either returns a single dist-params dict or a list of :math:`n` such dicts, one for each discrete action. """ return super().dist_params(s) @staticmethod def _get_proba_dist(value_range, value_transform, num_bins): if value_transform is not None: f, _ = value_transform value_range = f(value_range[0]), f(value_range[1]) reward_space = Box(*value_range, shape=()) return DiscretizedIntervalDist(reward_space, num_bins) @staticmethod def _check_value_range(value_range): if not (isinstance(value_range, (tuple, list)) and len(value_range) == 2 and isinstance(value_range[0], (int, float)) and isinstance(value_range[1], (int, float)) and value_range[0] < value_range[1]): raise TypeError("value_range is not a valid pair tuple of floats: (low, high)") return float(value_range[0]), float(value_range[1])
6,909
30.409091
100
py
null
coax-main/coax/_core/stochastic_v_test.py
from functools import partial from collections import namedtuple import jax import jax.numpy as jnp import haiku as hk from gymnasium.spaces import Discrete, Box from .._base.test_case import TestCase from ..utils import safe_sample from .stochastic_v import StochasticV discrete = Discrete(7) boxspace = Box(low=0, high=1, shape=(3, 5)) num_bins = 20 Env = namedtuple('Env', ('observation_space', 'action_space')) def func(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) logits = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(num_bins), )) return {'logits': logits(S)} class TestStochasticV(TestCase): def test_init(self): StochasticV(func, Env(boxspace, boxspace), (-10, 10), num_bins=num_bins) StochasticV(func, Env(boxspace, discrete), (-10, 10), num_bins=num_bins) StochasticV(func, Env(discrete, boxspace), (-10, 10), num_bins=num_bins) StochasticV(func, Env(discrete, discrete), (-10, 10), num_bins=num_bins) # test_call_* ################################################################################## def test_call_discrete(self): env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19) v_, logp = v(s, return_logp=True) print(v_, logp, env.observation_space) self.assertIn(v_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) def test_call_boxspace(self): env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19) v_, logp = v(s, return_logp=True) print(v_, logp, env.observation_space) self.assertIn(v_, Box(*value_range, shape=())) self.assertArraySubdtypeFloat(logp) self.assertArrayShape(logp, ()) # test_mode_* ################################################################################## def test_mode_discrete(self): env = Env(discrete, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19) v_ = v.mode(s) print(v_, env.observation_space) self.assertIn(v_, Box(*value_range, shape=())) def test_mode_boxspace(self): env = Env(boxspace, discrete) value_range = (-10, 10) s = safe_sample(env.observation_space, seed=17) v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19) v_ = v.mode(s) print(v_, env.observation_space) self.assertIn(v_, Box(*value_range, shape=())) def test_function_state(self): env = Env(discrete, discrete) value_range = (-10, 10) v = StochasticV(func, env, value_range, num_bins=num_bins, random_seed=19) print(v.function_state) batch_norm_avg = v.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) # other tests ################################################################################## def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, is_training\), " r"got: func\(S, is_training, x\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) value_range = (-10, 10) StochasticV(badfunc, env, value_range, num_bins=num_bins, random_seed=13) def test_bad_output_structure(self): def badfunc(S, is_training): dist_params = func(S, is_training) dist_params['foo'] = jnp.zeros(1) return dist_params msg = ( r"func has bad return tree_structure, " r"expected: PyTreeDef\({'logits': \*}\), " r"got: PyTreeDef\({'foo': \*, 'logits': \*}\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(discrete, discrete) value_range = (-10, 10) StochasticV(badfunc, env, value_range, num_bins=num_bins, random_seed=13)
4,708
34.674242
100
py
null
coax-main/coax/_core/successor_state_q.py
import warnings import jax import haiku as hk from .._core.q import Q from .._core.base_stochastic_func_type1 import BaseStochasticFuncType1 from ..utils import ( check_preprocessors, is_vfunction, is_reward_function, is_transition_model, is_stochastic, jit) __all__ = ( 'SuccessorStateQ', ) class SuccessorStateQ: r""" A state-action value function :math:`q(s,a)=r(s,a)+\gamma\mathop{\mathbb{E}}_{s'\sim p(.|s,a)}v(s')`. **caution** A word of caution: If you use custom observation/action pre-/post-processors, please make sure that all three function approximators :code:`v`, :code:`p` and :code:`r` use the same ones. Parameters ---------- v : V or StochasticV A state value function :math:`v(s)`. p : TransitionModel or StochasticTransitionModel A transition model. r : RewardFunction or StochasticRewardFunction A reward function. gamma : float between 0 and 1, optional The discount factor for future rewards :math:`\gamma\in[0,1]`. """ def __init__(self, v, p, r, gamma=0.9): # some explicit type checks if not is_vfunction(v): raise TypeError(f"v must be a state-value function, got: {type(v)}") if not is_transition_model(p): raise TypeError(f"p must be a transition model, got: {type(p)}") if not is_reward_function(r): raise TypeError(f"r must be a reward function, got: {type(r)}") self.v = v self.p = p self.r = r self.gamma = gamma # we assume that self.r uses the same action preprocessor self.observation_space = self.p.observation_space self.action_space = self.p.action_space self.action_preprocessor = self.p.action_preprocessor self.observation_preprocessor = self.p.observation_preprocessor self.observation_postprocessor = self.p.observation_postprocessor self.value_transform = self.v.value_transform if not check_preprocessors( self.observation_space, self.v.observation_preprocessor, self.r.observation_preprocessor, self.p.observation_preprocessor): warnings.warn( "it seems that observation_preprocessors of v, r ,p do not match; please " "instantiate your functions approximators with the same observation_preprocessors, " "e.g. v = coax.V(..., observation_preprocessor=p.observation_preprocessor) and " "r = coax.RewardFunction(..., observation_preprocessor=p.observation_preprocessor) " "to ensure that all preprocessors match") _reshape_to_replicas = BaseStochasticFuncType1._reshape_to_replicas _reshape_from_replicas = BaseStochasticFuncType1._reshape_from_replicas @property def rng(self): return self.v.rng @property def params(self): return hk.data_structures.to_immutable_dict({ 'v': self.v.params, 'p': self.p.params, 'r': self.r.params, 'gamma': self.gamma, }) @property def function_state(self): return hk.data_structures.to_immutable_dict({ 'v': self.v.function_state, 'p': self.p.function_state, 'r': self.r.function_state, }) @property def function_type1(self): if not hasattr(self, '_function_type1'): def func(params, state, rng, S, A, is_training): rngs = hk.PRNGSequence(rng) new_state = dict(state) # s' ~ p(.|s,a) if is_stochastic(self.p): dist_params, new_state['p'] = self.p.function_type1( params['p'], state['p'], next(rngs), S, A, is_training) S_next = self.p.proba_dist.mean(dist_params) else: S_next, new_state['p'] = self.p.function_type1( params['p'], state['p'], next(rngs), S, A, is_training) # r = r(s,a) if is_stochastic(self.r): dist_params, new_state['r'] = self.r.function_type1( params['r'], state['r'], next(rngs), S, A, is_training) R = self.r.proba_dist.mean(dist_params) R = self.r.proba_dist.postprocess_variate(next(rngs), R, batch_mode=True) else: R, new_state['r'] = self.r.function_type1( params['r'], state['r'], next(rngs), S, A, is_training) # v(s') if is_stochastic(self.v): dist_params, new_state['v'] = self.v.function( params['v'], state['v'], next(rngs), S_next, is_training) V = self.v.proba_dist.mean(dist_params) V = self.v.proba_dist.postprocess_variate(next(rngs), V, batch_mode=True) else: V, new_state['v'] = self.v.function( params['v'], state['v'], next(rngs), S_next, is_training) # q = r + γ v(s') f, f_inv = self.value_transform Q_sa = f(R + params['gamma'] * f_inv(V)) assert Q_sa.ndim == 1, f"bad shape: {Q_sa.shape}" new_state = hk.data_structures.to_immutable_dict(new_state) assert jax.tree_util.tree_structure( new_state) == jax.tree_util.tree_structure(state) return Q_sa, new_state self._function_type1 = jit(func, static_argnums=(5,)) return self._function_type1 @property def function_type2(self): if not hasattr(self, '_function_type2'): def func(params, state, rng, S, is_training): rngs = hk.PRNGSequence(rng) new_state = dict(state) # s' ~ p(s'|s,.) # note: S_next is replicated, one for each (discrete) action if is_stochastic(self.p): dist_params_rep, new_state['p'] = self.p.function_type2( params['p'], state['p'], next(rngs), S, is_training) dist_params_rep = jax.tree_map(self._reshape_to_replicas, dist_params_rep) S_next_rep = self.p.proba_dist.mean(dist_params_rep) else: S_next_rep, new_state['p'] = self.p.function_type2( params['p'], state['p'], next(rngs), S, is_training) S_next_rep = jax.tree_map(self._reshape_to_replicas, S_next_rep) # r ~ p(r|s,a) # note: R is replicated, one for each (discrete) action if is_stochastic(self.r): dist_params_rep, new_state['r'] = self.r.function_type2( params['r'], state['r'], next(rngs), S, is_training) dist_params_rep = jax.tree_map(self._reshape_to_replicas, dist_params_rep) R_rep = self.r.proba_dist.mean(dist_params_rep) R_rep = self.r.proba_dist.postprocess_variate( next(rngs), R_rep, batch_mode=True) else: R_rep, new_state['r'] = self.r.function_type2( params['r'], state['r'], next(rngs), S, is_training) R_rep = jax.tree_map(self._reshape_to_replicas, R_rep) # v(s') # note: since the input S_next is replicated, so is the output V if is_stochastic(self.v): dist_params_rep, new_state['v'] = self.v.function( params['v'], state['v'], next(rngs), S_next_rep, is_training) V_rep = self.v.proba_dist.mean(dist_params_rep) V_rep = self.v.proba_dist.postprocess_variate( next(rngs), V_rep, batch_mode=True) else: V_rep, new_state['v'] = self.v.function( params['v'], state['v'], next(rngs), S_next_rep, is_training) # q = r + γ v(s') f, f_inv = self.value_transform Q_rep = f(R_rep + params['gamma'] * f_inv(V_rep)) # reshape from (batch x num_actions, *) to (batch, num_actions, *) Q_s = self._reshape_from_replicas(Q_rep) assert Q_s.ndim == 2, f"bad shape: {Q_s.shape}" assert Q_s.shape[1] == self.action_space.n, f"bad shape: {Q_s.shape}" new_state = hk.data_structures.to_immutable_dict(new_state) assert jax.tree_util.tree_structure( new_state) == jax.tree_util.tree_structure(state) return Q_s, new_state self._function_type2 = jit(func, static_argnums=(4,)) return self._function_type2 def __call__(self, s, a=None): r""" Evaluate the state-action function on a state observation :math:`s` or on a state-action pair :math:`(s, a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action A single action :math:`a`. Returns ------- q_sa or q_s : ndarray Depending on whether :code:`a` is provided, this either returns a scalar representing :math:`q(s,a)\in\mathbb{R}` or a vector representing :math:`q(s,.)\in\mathbb{R}^n`, where :math:`n` is the number of discrete actions. Naturally, this only applies for discrete action spaces. """ return Q.__call__(self, s, a=a)
9,697
38.745902
100
py
null
coax-main/coax/_core/transition_model.py
from inspect import signature from collections import namedtuple import jax import jax.numpy as jnp import numpy as onp import haiku as hk from gymnasium.spaces import Space, Discrete from ..utils import safe_sample, batch_to_single, default_preprocessor from ..proba_dists import ProbaDist from .base_func import BaseFunc, ExampleData, Inputs, ArgsType1, ArgsType2, ModelTypes __all__ = ( 'TransitionModel', ) class TransitionModel(BaseFunc): r""" A deterministic transition function :math:`s'_\theta(s,a)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. The function signature must be the same as the example below. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :attr:`proba_dist.preprocess_variate <coax.proba_dists.ProbaDist.preprocess_variate>`. The reason why the default is not :func:`coax.utils.default_preprocessor` is that we prefer consistence with :class:`coax.StochasticTransitionModel`. observation_postprocessor : function, optional Takes a batch of generated observations and makes sure that they are that are compatible with the original :code:`observation_space`. If left unspecified, this defaults to :attr:`proba_dist.postprocess_variate <coax.proba_dists.ProbaDist.postprocess_variate>`. action_preprocessor : function, optional Turns a single action into a batch of actions in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults :func:`default_preprocessor(env.action_space) <coax.utils.default_preprocessor>`. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, observation_preprocessor=None, observation_postprocessor=None, action_preprocessor=None, random_seed=None): self.observation_preprocessor = observation_preprocessor self.observation_postprocessor = observation_postprocessor self.action_preprocessor = action_preprocessor # defaults if self.observation_preprocessor is None: self.observation_preprocessor = ProbaDist(env.observation_space).preprocess_variate if self.observation_postprocessor is None: self.observation_postprocessor = ProbaDist(env.observation_space).postprocess_variate if self.action_preprocessor is None: self.action_preprocessor = default_preprocessor(env.action_space) super().__init__( func, observation_space=env.observation_space, action_space=env.action_space, random_seed=random_seed) def __call__(self, s, a=None): r""" Evaluate the state-action function on a state observation :math:`s` or on a state-action pair :math:`(s, a)`. Parameters ---------- s : state observation A single state observation :math:`s`. a : action A single action :math:`a`. Returns ------- q_sa or q_s : ndarray Depending on whether :code:`a` is provided, this either returns a scalar representing :math:`q(s,a)\in\mathbb{R}` or a vector representing :math:`q(s,.)\in\mathbb{R}^n`, where :math:`n` is the number of discrete actions. Naturally, this only applies for discrete action spaces. """ S = self.observation_preprocessor(self.rng, s) if a is None: S_next, _ = self.function_type2(self.params, self.function_state, self.rng, S, False) S_next = batch_to_single(S_next) # (batch, num_actions, *) -> (num_actions, *) n = self.action_space.n s_next = [self.observation_postprocessor(self.rng, S_next, index=i) for i in range(n)] else: A = self.action_preprocessor(self.rng, a) S_next, _ = self.function_type1(self.params, self.function_state, self.rng, S, A, False) s_next = self.observation_postprocessor(self.rng, S_next) return s_next @property def function_type1(self): r""" Same as :attr:`function`, except that it ensures a type-1 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 1: return self.function assert isinstance(self.action_space, Discrete) def project(A): assert A.ndim == 2, f"bad shape: {A.shape}" assert A.shape[1] == self.action_space.n, f"bad shape: {A.shape}" def func(leaf): # noqa: E306 assert isinstance(leaf, jnp.ndarray), f"leaf must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 2, f"bad shape: {leaf.shape}" assert leaf.shape[0] == A.shape[0], \ f"batch_size (axis=0) mismatch: leaf.shape: {leaf.shape}, A.shape: {A.shape}" assert leaf.shape[1] == A.shape[1], \ f"num_actions (axis=1) mismatch: leaf.shape: {leaf.shape}, A.shape: {A.shape}" return jax.vmap(jnp.dot)(jnp.moveaxis(leaf, 1, -1), A) return func def type1_func(type2_params, type2_state, rng, S, A, is_training): S_next, state_new = self.function(type2_params, type2_state, rng, S, is_training) S_next = jax.tree_map(project(A), S_next) return S_next, state_new return type1_func @property def function_type2(self): r""" Same as :attr:`function`, except that it ensures a type-2 function signature, regardless of the underlying :attr:`modeltype`. """ if self.modeltype == 2: return self.function if not isinstance(self.action_space, Discrete): raise ValueError( "input 'A' is required for type-1 dynamics model when action space is non-Discrete") n = self.action_space.n def reshape(leaf): # reshape from (batch * num_actions, *shape) -> (batch, *shape, num_actions) assert isinstance(leaf, jnp.ndarray), f"all leaves must be ndarray, got: {type(leaf)}" assert leaf.ndim >= 1, f"bad shape: {leaf.shape}" assert leaf.shape[0] % n == 0, \ f"first axis size must be a multiple of num_actions, got shape: {leaf.shape}" leaf = jnp.reshape(leaf, (-1, n, *leaf.shape[1:])) # (batch, num_actions, *shape) return leaf def type2_func(type1_params, type1_state, rng, S, is_training): rngs = hk.PRNGSequence(rng) batch_size = jax.tree_util.tree_leaves(S)[0].shape[0] # example: let S = [7, 2, 5, 8] and num_actions = 3, then # S_rep = [7, 7, 7, 2, 2, 2, 5, 5, 5, 8, 8, 8] # repeated # A_rep = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] # tiled S_rep = jax.tree_map(lambda x: jnp.repeat(x, n, axis=0), S) A_rep = jnp.tile(jnp.arange(n), batch_size) A_rep = self.action_preprocessor(next(rngs), A_rep) # one-hot encoding # evaluate on replicas => output shape: (batch * num_actions, *shape) S_next_rep, state_new = self.function( type1_params, type1_state, next(rngs), S_rep, A_rep, is_training) S_next = jax.tree_map(reshape, S_next_rep) return S_next, state_new return type2_func @property def modeltype(self): r""" Specifier for how the transition function is modeled, i.e. .. math:: (s,a) &\mapsto s'(s,a) &\qquad (\text{modeltype} &= 1) \\ s &\mapsto s'(s,.) &\qquad (\text{modeltype} &= 2) Note that modeltype=2 is only well-defined if the action space is :class:`Discrete <gymnasium.spaces.Discrete>`. Namely, :math:`n` is the number of discrete actions. """ return self._modeltype @classmethod def example_data( cls, env, observation_preprocessor=None, action_preprocessor=None, batch_size=1, random_seed=None): if not isinstance(env.observation_space, Space): raise TypeError( "env.observation_space must be derived from gymnasium.Space, " f"got: {type(env.observation_space)}") if not isinstance(env.action_space, Space): raise TypeError( "env.action_space must be derived from gymnasium.Space, " f"got: {type(env.action_space)}") if observation_preprocessor is None: observation_preprocessor = ProbaDist(env.observation_space).preprocess_variate if action_preprocessor is None: action_preprocessor = default_preprocessor(env.action_space) rnd = onp.random.RandomState(random_seed) rngs = hk.PRNGSequence(rnd.randint(jnp.iinfo('int32').max)) # input: state observations S = [safe_sample(env.observation_space, rnd) for _ in range(batch_size)] S = [observation_preprocessor(next(rngs), s) for s in S] S = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *S) # input: actions A = [safe_sample(env.action_space, rnd) for _ in range(batch_size)] A = [action_preprocessor(next(rngs), a) for a in A] A = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *A) # output: type1 S_next_type1 = jax.tree_map(lambda x: jnp.asarray(rnd.randn(batch_size, *x.shape[1:])), S) q1_data = ExampleData( inputs=Inputs(args=ArgsType1(S=S, A=A, is_training=True), static_argnums=(2,)), output=S_next_type1) if not isinstance(env.action_space, Discrete): return ModelTypes(type1=q1_data, type2=None) # output: type2 (if actions are discrete) S_next_type2 = jax.tree_map( lambda x: jnp.asarray(rnd.randn(batch_size, env.action_space.n, *x.shape[1:])), S) q2_data = ExampleData( inputs=Inputs(args=ArgsType2(S=S, is_training=True), static_argnums=(1,)), output=S_next_type2) return ModelTypes(type1=q1_data, type2=q2_data) def _check_signature(self, func): sig_type1 = ('S', 'A', 'is_training') sig_type2 = ('S', 'is_training') sig = tuple(signature(func).parameters) if sig not in (sig_type1, sig_type2): sig = ', '.join(sig) alt = ' or func(S, is_training)' if isinstance(self.action_space, Discrete) else '' raise TypeError( f"func has bad signature; expected: func(S, A, is_training){alt}, got: func({sig})") if sig == sig_type2 and not isinstance(self.action_space, Discrete): raise TypeError("type-2 models are only well-defined for Discrete action spaces") Env = namedtuple('Env', ('observation_space', 'action_space')) example_data_per_modeltype = self.example_data( env=Env(self.observation_space, self.action_space), action_preprocessor=self.action_preprocessor, batch_size=1, random_seed=self.random_seed) if sig == sig_type1: self._modeltype = 1 example_data = example_data_per_modeltype.type1 else: self._modeltype = 2 example_data = example_data_per_modeltype.type2 return example_data def _check_output(self, actual, expected): expected_leaves, expected_structure = jax.tree_util.tree_flatten(expected) actual_leaves, actual_structure = jax.tree_util.tree_flatten(actual) assert all(isinstance(x, jnp.ndarray) for x in expected_leaves), "bad example_data" if actual_structure != expected_structure: raise TypeError( f"func has bad return tree_structure, expected: {expected_structure}, " f"got: {actual_structure}") if not all(isinstance(x, jnp.ndarray) for x in actual_leaves): bad_types = tuple(type(x) for x in actual_leaves if not isinstance(x, jnp.ndarray)) raise TypeError( "all leaves of dist_params must be of type: jax.numpy.ndarray, " f"found leaves of type: {bad_types}") if not all(a.shape == b.shape for a, b in zip(actual_leaves, expected_leaves)): shapes_tree = jax.tree_map( lambda a, b: f"{a.shape} {'!=' if a.shape != b.shape else '=='} {b.shape}", actual, expected) raise TypeError(f"found leaves with unexpected shapes: {shapes_tree}")
12,966
39.395639
100
py
null
coax-main/coax/_core/transition_model_test.py
from functools import partial from collections import namedtuple import gymnasium import jax import jax.numpy as jnp import numpy as onp import haiku as hk from .._base.test_case import TestCase from ..utils import safe_sample from .transition_model import TransitionModel discrete = gymnasium.spaces.Discrete(7) boxspace = gymnasium.spaces.Box(low=0, high=1, shape=(3, 5)) Env = namedtuple('Env', ('observation_space', 'action_space')) def func_discrete_type1(S, A, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n), jax.nn.softmax )) X = jax.vmap(jnp.kron)(S, A) return seq(X) def func_discrete_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(discrete.n * discrete.n), hk.Reshape((discrete.n, discrete.n)), jax.nn.softmax )) return seq(S) def func_boxspace_type1(S, A, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape)), hk.Reshape(boxspace.shape), )) X = jax.vmap(jnp.kron)(S, A) return seq(X) def func_boxspace_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jnp.tanh, hk.Linear(onp.prod(boxspace.shape) * discrete.n), hk.Reshape((discrete.n, *boxspace.shape)), )) return seq(S) class TestTransitionModel(TestCase): def test_init(self): # cannot define a type-2 models on a non-discrete action space msg = r"type-2 models are only well-defined for Discrete action spaces" with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_boxspace_type2, Env(boxspace, boxspace)) with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_discrete_type2, Env(discrete, boxspace)) msg = r"found leaves with unexpected shapes: \(1(?:, 7)?, 7\) != \(1(?:, 7)?, 3, 5\)" with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_discrete_type1, Env(boxspace, discrete)) with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_discrete_type2, Env(boxspace, discrete)) with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_discrete_type1, Env(boxspace, boxspace)) msg = r"found leaves with unexpected shapes: \(1(?:, 7)?, 3, 5\) != \(1(?:, 7)?, 7\)" with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_boxspace_type1, Env(discrete, discrete)) with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_boxspace_type2, Env(discrete, discrete)) with self.assertRaisesRegex(TypeError, msg): TransitionModel(func_boxspace_type1, Env(discrete, boxspace)) # these should all be fine TransitionModel(func_discrete_type1, Env(discrete, boxspace)) TransitionModel(func_discrete_type1, Env(discrete, discrete)) TransitionModel(func_discrete_type2, Env(discrete, discrete)) TransitionModel(func_boxspace_type1, Env(boxspace, boxspace)) TransitionModel(func_boxspace_type1, Env(boxspace, discrete)) TransitionModel(func_boxspace_type2, Env(boxspace, discrete)) # test_call_* ################################################################################## def test_call_discrete_discrete_type1(self): func = func_discrete_type1 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_discrete_discrete_type2(self): func = func_discrete_type2 env = Env(discrete, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_boxspace_discrete_type1(self): func = func_boxspace_type1 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_boxspace_discrete_type2(self): func = func_boxspace_type2 env = Env(boxspace, discrete) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) for s_next in p(s): print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) def test_call_discrete_boxspace(self): func = func_discrete_type1 env = Env(discrete, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p(s) def test_call_boxspace_boxspace(self): func = func_boxspace_type1 env = Env(boxspace, boxspace) s = safe_sample(env.observation_space, seed=17) a = safe_sample(env.action_space, seed=18) p = TransitionModel(func, env, random_seed=19) s_next = p(s, a) print(s_next, env.observation_space) self.assertIn(s_next, env.observation_space) msg = r"input 'A' is required for type-1 dynamics model when action space is non-Discrete" with self.assertRaisesRegex(ValueError, msg): p(s) # other tests ################################################################################## def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, A, is_training\) or func\(S, is_training\), " r"got: func\(S, is_training, x\)" ) with self.assertRaisesRegex(TypeError, msg): env = Env(boxspace, discrete) TransitionModel(badfunc, env, random_seed=13) def test_bad_output_structure(self): def badfunc(S, is_training): S_next = func_discrete_type2(S, is_training) S_next = (13, S_next) return S_next msg = ( r"func has bad return tree_structure, expected: PyTreeDef\(\*\), " r"got: PyTreeDef\(\(\*, \*\)\)") with self.assertRaisesRegex(TypeError, msg): env = Env(discrete, discrete) TransitionModel(badfunc, env, random_seed=13)
8,653
35.982906
100
py
null
coax-main/coax/_core/v.py
from inspect import signature from collections import namedtuple import jax import jax.numpy as jnp import numpy as onp import haiku as hk from gymnasium.spaces import Space from ..utils import safe_sample, default_preprocessor from ..value_transforms import ValueTransform from .base_func import BaseFunc, ExampleData, Inputs, ArgsType2 __all__ = ( 'V', ) class V(BaseFunc): r""" A state value function :math:`v_\theta(s)`. Parameters ---------- func : function A Haiku-style function that specifies the forward pass. The function signature must be the same as the example below. env : gymnasium.Env The gymnasium-style environment. This is used to validate the input/output structure of ``func``. observation_preprocessor : function, optional Turns a single observation into a batch of observations in a form that is convenient for feeding into :code:`func`. If left unspecified, this defaults to :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`. value_transform : ValueTransform or pair of funcs, optional If provided, the target for the underlying function approximator is transformed such that: .. math:: \tilde{v}_\theta(S_t)\ \approx\ f(G_t) This means that calling the function involves undoing this transformation: .. math:: v(s)\ =\ f^{-1}(\tilde{v}_\theta(s)) Here, :math:`f` and :math:`f^{-1}` are given by ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note that a ValueTransform is just a glorified pair of functions, i.e. passing ``value_transform=(func, inverse_func)`` works just as well. random_seed : int, optional Seed for pseudo-random number generators. """ def __init__( self, func, env, observation_preprocessor=None, value_transform=None, random_seed=None): self.observation_preprocessor = observation_preprocessor self.value_transform = value_transform # defaults if self.observation_preprocessor is None: self.observation_preprocessor = default_preprocessor(env.observation_space) if self.value_transform is None: self.value_transform = ValueTransform(lambda x: x, lambda x: x) if not isinstance(self.value_transform, ValueTransform): self.value_transform = ValueTransform(*value_transform) super().__init__( func=func, observation_space=env.observation_space, action_space=None, random_seed=random_seed) def __call__(self, s): r""" Evaluate the value function on a state observation :math:`s`. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- v : ndarray, shape: () The estimated expected value associated with the input state observation ``s``. """ S = self.observation_preprocessor(self.rng, s) V, _ = self.function(self.params, self.function_state, self.rng, S, False) V = self.value_transform.inverse_func(V) return onp.asarray(V[0]) @classmethod def example_data(cls, env, observation_preprocessor=None, batch_size=1, random_seed=None): if not isinstance(env.observation_space, Space): raise TypeError( "env.observation_space must be derived from gymnasium.Space, " f"got: {type(env.observation_space)}") if observation_preprocessor is None: observation_preprocessor = default_preprocessor(env.observation_space) rnd = onp.random.RandomState(random_seed) rngs = hk.PRNGSequence(rnd.randint(jnp.iinfo('int32').max)) # input: state observations S = [safe_sample(env.observation_space, rnd) for _ in range(batch_size)] S = [observation_preprocessor(next(rngs), s) for s in S] S = jax.tree_map(lambda *x: jnp.concatenate(x, axis=0), *S) return ExampleData( inputs=Inputs(args=ArgsType2(S=S, is_training=True), static_argnums=(1,)), output=jnp.asarray(rnd.randn(batch_size)), ) def _check_signature(self, func): if tuple(signature(func).parameters) != ('S', 'is_training'): sig = ', '.join(signature(func).parameters) raise TypeError( f"func has bad signature; expected: func(S, is_training), got: func({sig})") # example inputs Env = namedtuple('Env', ('observation_space',)) return self.example_data( env=Env(self.observation_space), observation_preprocessor=self.observation_preprocessor, batch_size=1, random_seed=self.random_seed, ) def _check_output(self, actual, expected): if not isinstance(actual, jnp.ndarray): raise TypeError( f"func has bad return type; expected jnp.ndarray, got {actual.__class__.__name__}") if not jnp.issubdtype(actual.dtype, jnp.floating): raise TypeError( "func has bad return dtype; expected a subdtype of jnp.floating, " f"got dtype={actual.dtype}") if actual.shape != expected.shape: raise TypeError( f"func has bad return shape, expected: {expected.shape}, got: {actual.shape}")
5,528
33.12963
100
py
null
coax-main/coax/_core/v_test.py
from functools import partial import jax import jax.numpy as jnp import haiku as hk from .._base.test_case import TestCase from ..utils import get_transition_batch, safe_sample from .v import V def func(S, is_training): rng1, rng2, rng3 = hk.next_rng_keys(3) rate = 0.25 if is_training else 0. batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, rng1, rate), partial(batch_norm, is_training=is_training), hk.Linear(8), jax.nn.relu, partial(hk.dropout, rng2, rate), partial(batch_norm, is_training=is_training), hk.Linear(8), jax.nn.relu, partial(hk.dropout, rng3, rate), partial(batch_norm, is_training=is_training), hk.Linear(1, w_init=jnp.zeros), jnp.ravel, )) return seq(S) class TestV(TestCase): def setUp(self): self.v = V(func, self.env_discrete, random_seed=13) self.transition_batch = get_transition_batch(self.env_discrete, random_seed=7) def tearDown(self): del self.v, self.transition_batch def test_call(self): s = safe_sample(self.env_discrete.observation_space) v = self.v(s) self.assertAlmostEqual(v, 0.) def test_soft_update(self): tau = 0.13 v = self.v v_targ = v.copy() v.params = jax.tree_map(jnp.ones_like, v.params) v_targ.params = jax.tree_map(jnp.zeros_like, v.params) expected = jax.tree_map(lambda a: jnp.full_like(a, tau), v.params) v_targ.soft_update(v, tau=tau) self.assertPytreeAlmostEqual(v_targ.params, expected) def test_function_state(self): print(self.v.function_state) batch_norm_avg = self.v.function_state['batch_norm/~/mean_ema']['average'] self.assertArrayShape(batch_norm_avg, (1, 8)) self.assertArrayNotEqual(batch_norm_avg, jnp.zeros_like(batch_norm_avg)) def test_bad_input_signature(self): def badfunc(S, is_training, x): pass msg = ( r"func has bad signature; " r"expected: func\(S, is_training\), got: func\(S, is_training, x\)") with self.assertRaisesRegex(TypeError, msg): V(badfunc, self.env_discrete, random_seed=13) def test_bad_output_type(self): def badfunc(S, is_training): return 'garbage' msg = r"(?:is not a valid JAX type|func has bad return type)" with self.assertRaisesRegex(TypeError, msg): V(badfunc, self.env_discrete, random_seed=13) def test_bad_output_shape(self): def badfunc(S, is_training): V = func(S, is_training) return jnp.expand_dims(V, axis=-1) msg = r"func has bad return shape, expected: \(1,\), got: \(1, 1\)" with self.assertRaisesRegex(TypeError, msg): V(badfunc, self.env_discrete, random_seed=13) def test_bad_output_dtype(self): def badfunc(S, is_training): V = func(S, is_training) return V.astype('int32') msg = r"func has bad return dtype; expected a subdtype of jnp\.floating, got dtype=int32" with self.assertRaisesRegex(TypeError, msg): V(badfunc, self.env_discrete, random_seed=13)
3,296
34.451613
97
py
null
coax-main/coax/_core/value_based_policy.py
import gymnasium import jax import jax.numpy as jnp import haiku as hk import chex from ..utils import docstring, is_qfunction, is_stochastic, jit from ..proba_dists import CategoricalDist from .base_stochastic_func_type2 import StochasticFuncType2Mixin from .q import Q __all__ = ( 'EpsilonGreedy', 'BoltzmannPolicy', ) class BaseValueBasedPolicy(StochasticFuncType2Mixin): """ Abstract base class for value-based policies. """ def __init__(self, q): if not is_qfunction(q): raise TypeError(f"q must be a q-function, got: {type(q)}") if not isinstance(q.action_space, gymnasium.spaces.Discrete): raise TypeError(f"{self.__class__.__name__} is only well-defined for Discrete actions") self.q = q self.observation_preprocessor = self.q.observation_preprocessor self.action_preprocessor = self.q.action_preprocessor self.proba_dist = CategoricalDist(self.q.action_space) def Q_s(params, state, rng, S): rngs = hk.PRNGSequence(rng) if is_stochastic(self.q): Q_s = self.q.mean_func_type2(params['q'], state, next(rngs), S) Q_s = self.q.proba_dist.postprocess_variate(next(rngs), Q_s, batch_mode=True) else: Q_s, _ = self.q.function_type2(params['q'], state, next(rngs), S, False) chex.assert_rank(Q_s, 2) assert Q_s.shape[1] == self.q.action_space.n return Q_s self._Q_s = jit(Q_s) @property def rng(self): return self.q.rng @property @docstring(Q.function) def function(self): return self._function # this is set downstream (below) @property @docstring(Q.function_state) def function_state(self): return self.q.function_state @function_state.setter def function_state(self, new_function_state): self.q.function_state = new_function_state def __call__(self, s, return_logp=False): r""" Sample an action :math:`a\sim\pi_q(.|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. return_logp : bool, optional Whether to return the log-propensity :math:`\log\pi_q(a|s)`. Returns ------- a : action A single action :math:`a`. logp : float, optional The log-propensity :math:`\log\pi_q(a|s)`. This is only returned if we set ``return_logp=True``. """ return super().__call__(s, return_logp=return_logp) def mean(self, s): r""" Get the mean of the distribution :math:`\pi_q(.|s)`. Note that if the actions are discrete, this returns the :attr:`mode` instead. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- a : action A single action :math:`a`. """ return super().mean(s) def mode(self, s): r""" Sample a greedy action :math:`a=\arg\max_a\pi_q(a|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- a : action A single action :math:`a`. """ return super().mode(s) def dist_params(self, s): r""" Get the conditional distribution parameters of :math:`\pi_q(.|s)`. Parameters ---------- s : state observation A single state observation :math:`s`. Returns ------- dist_params : Params The distribution parameters of :math:`\pi_q(.|s)`. """ return super().dist_params(s) class EpsilonGreedy(BaseValueBasedPolicy): r""" Create an :math:`\epsilon`-greedy policy, given a q-function. This policy samples actions :math:`a\sim\pi_q(.|s)` according to the following rule: .. math:: u &\sim \text{Uniform([0, 1])} \\ a_\text{rand} &\sim \text{Uniform}(\text{actions}) \\ a\ &=\ \left\{\begin{matrix} a_\text{rand} & \text{ if } u < \epsilon \\ \arg\max_{a'} q(s,a') & \text{ otherwise } \end{matrix}\right. Parameters ---------- q : Q A state-action value function. epsilon : float between 0 and 1, optional The probability of sampling an action uniformly at random (as opposed to sampling greedily). """ def __init__(self, q, epsilon=0.1): super().__init__(q) self.epsilon = epsilon def func(params, state, rng, S, is_training): Q_s = self._Q_s(params, state, rng, S) A_greedy = (Q_s == Q_s.max(axis=1, keepdims=True)).astype(Q_s.dtype) A_greedy /= A_greedy.sum(axis=1, keepdims=True) # there may be multiple max's (ties) A_greedy *= 1 - params['epsilon'] # take away ε from greedy action(s) A_greedy += params['epsilon'] / self.q.action_space.n # spread ε evenly to all actions dist_params = {'logits': jnp.log(A_greedy + 1e-15)} return dist_params, None # return dummy function-state self._function = jit(func, static_argnums=(4,)) @property @docstring(Q.params) def params(self): return hk.data_structures.to_immutable_dict({'epsilon': self.epsilon, 'q': self.q.params}) @params.setter def params(self, new_params): if jax.tree_util.tree_structure(new_params) != jax.tree_util.tree_structure(self.params): raise TypeError("new params must have the same structure as old params") self.epsilon = new_params['epsilon'] self.q.params = new_params['q'] class BoltzmannPolicy(BaseValueBasedPolicy): r""" Derive a Boltzmann policy from a q-function. This policy samples actions :math:`a\sim\pi_q(.|s)` according to the following rule: .. math:: p &= \text{softmax}(q(s,.) / \tau) \\ a &\sim \text{Cat}(p) Note that this policy is only well-defined for *discrete* action spaces. Also, it's worth noting that if the q-function has a non-trivial value transform :math:`f(.)` (e.g. :class:`coax.value_transforms.LogTransform`), we feed in the *transformed* estimate as our logits, i.e. .. math:: p = \text{softmax}(f(q(s,.)) / \tau) Parameters ---------- q : Q A state-action value function. temperature : positive float, optional The Boltzmann temperature :math:`\tau>0` sets the sharpness of the categorical distribution. Picking a small value for :math:`\tau` results in greedy sampling while large values results in uniform sampling. """ def __init__(self, q, temperature=0.02): super().__init__(q) self.temperature = temperature def func(params, state, rng, S, is_training): Q_s = self._Q_s(params, state, rng, S) dist_params = {'logits': Q_s / params['temperature']} return dist_params, None # return dummy function-state self._function = jit(func, static_argnums=(4,)) @property @docstring(Q.params) def params(self): return hk.data_structures.to_immutable_dict( {'temperature': self.temperature, 'q': self.q.params}) @params.setter def params(self, new_params): if jax.tree_util.tree_structure(new_params) != jax.tree_util.tree_structure(self.params): raise TypeError("new params must have the same structure as old params") self.temperature = new_params['temperature'] self.q.params = new_params['q']
7,757
27.417582
100
py
null
coax-main/coax/_core/value_based_policy_test.py
from functools import partial import gymnasium import jax import haiku as hk import numpy as onp from .._base.test_case import TestCase from .q import Q from .value_based_policy import EpsilonGreedy, BoltzmannPolicy env = gymnasium.make('FrozenLakeNonSlippery-v0') def func_type2(S, is_training): batch_norm = hk.BatchNorm(False, False, 0.99) seq = hk.Sequential(( hk.Flatten(), hk.Linear(8), jax.nn.relu, partial(hk.dropout, hk.next_rng_key(), 0.25 if is_training else 0.), partial(batch_norm, is_training=is_training), hk.Linear(8), jax.nn.relu, hk.Linear(env.action_space.n), )) return seq(S) class TestEpsilonGreedy(TestCase): def setUp(self): self.env = gymnasium.make('FrozenLakeNonSlippery-v0') self.q = Q(func_type2, env) def tearDown(self): del self.q, self.env def test_call(self): pi = EpsilonGreedy(self.q, epsilon=0.1) s, info = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_greedy(self): pi = EpsilonGreedy(self.q, epsilon=0.1) s, info = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi.mode(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_dist_params(self): pi = EpsilonGreedy(self.q, epsilon=0.1) s = self.env.observation_space.sample() dist_params = pi.dist_params(s) print(onp.exp(dist_params['logits'])) self.assertEqual(dist_params['logits'].shape, (self.env.action_space.n,)) # EpsilonGreedy produces logits that are true log-propensities (is not generally the case) # this checks if the propensities are properly normalized self.assertAlmostEqual(onp.exp(dist_params['logits']).sum(), 1) class TestBoltzmannPolicy(TestCase): def setUp(self): self.env = gymnasium.make('FrozenLakeNonSlippery-v0') self.q = Q(func_type2, env) def tearDown(self): del self.q, self.env def test_call(self): pi = BoltzmannPolicy(self.q, temperature=1.0) s, info = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_greedy(self): pi = BoltzmannPolicy(self.q, temperature=1.0) s, info = self.env.reset() for t in range(self.env.spec.max_episode_steps): a = pi.mode(s) s, r, done, truncated, info = self.env.step(a) if done: break def test_dist_params(self): pi = EpsilonGreedy(self.q, epsilon=0.1) s = self.env.observation_space.sample() dist_params = pi.dist_params(s) print(onp.exp(dist_params['logits'])) self.assertEqual(dist_params['logits'].shape, (self.env.action_space.n,))
3,106
30.383838
98
py
null
coax-main/coax/_core/worker.py
import time import inspect from abc import ABC, abstractmethod from typing import Optional import gymnasium from jax.lib.xla_bridge import get_backend from ..typing import Policy from ..wrappers import TrainMonitor from ..reward_tracing._base import BaseRewardTracer from ..experience_replay._base import BaseReplayBuffer __all__ = ( 'Worker', ) class WorkerError(Exception): pass class Worker(ABC): r""" The base class for defining workers as part of a distributed agent. Parameters ---------- env : gymnasium.Env | str | function Specifies the gymnasium-style environment by either passing the env itself (gymnasium.Env), its name (str), or a function that generates the environment. param_store : Worker, optional A distributed agent is presumed to have one worker that plays the role of a parameter store. To define the parameter-store worker itself, you must leave :code:`param_store=None`. For other worker roles, however, :code:`param_store` must be provided. pi : Policy, optional The behavior policy that is used by rollout workers to generate experience. tracer : RewardTracer, optional The reward tracer that is used by rollout workers. buffer : ReplayBuffer, optional The experience-replay buffer that is populated by rollout workers and sampled from by learners. buffer_warmup : int, optional The warmup period for the experience replay buffer, i.e. the minimal number of transitions that need to be stored in the replay buffer before we start sampling from it. name : str, optional A human-readable identifier of the worker. """ pi: Optional[Policy] = None tracer: Optional[BaseRewardTracer] = None buffer: Optional[BaseReplayBuffer] = None buffer_warmup: Optional[int] = None def __init__( self, env, param_store=None, pi=None, tracer=None, buffer=None, buffer_warmup=None, name=None): # import inline to avoid hard dependency on ray import ray import ray.actor self.__ray = ray self.env = _check_env(env, name) self.param_store = param_store self.pi = pi self.tracer = tracer self.buffer = buffer self.buffer_warmup = buffer_warmup self.name = name self.env.logger.info(f"JAX platform name: '{get_backend().platform}'") @abstractmethod def get_state(self): r""" Get the internal state that is shared between workers. Returns ------- state : object The internal state. This will be consumed by :func:`set_state(state) <set_state>`. """ pass @abstractmethod def set_state(self, state): r""" Set the internal state that is shared between workers. Parameters ---------- state : object The internal state, as returned by :func:`get_state`. """ pass @abstractmethod def trace(self, s, a, r, done, logp=0.0, w=1.0): r""" This implements the reward-tracing step of a single, raw transition. Parameters ---------- s : state observation A single state observation. a : action A single action. r : float A single observed reward. done : bool Whether the episode has finished. logp : float, optional The log-propensity :math:`\log\pi(a|s)`. w : float, optional Sample weight associated with the given state-action pair. """ pass @abstractmethod def learn(self, transition_batch): r""" Update the model parameters given a transition batch. """ pass def rollout(self): assert self.pi is not None s, info = self.env.reset() for t in range(self.env.spec.max_episode_steps): a, logp = self.pi(s, return_logp=True) s_next, r, done, truncated, info = self.env.step(a) self.trace(s, a, r, done or truncated, logp) if done or truncated: break s = s_next def rollout_loop(self, max_total_steps, reward_threshold=None): reward_threshold = _check_reward_threshold(reward_threshold, self.env) T_global = self.pull_getattr('env.T') while T_global < max_total_steps and self.env.avg_G < reward_threshold: self.pull_state() self.rollout() metrics = self.pull_metrics() metrics['throughput/rollout_loop'] = 1000 / self.env.dt_ms metrics['episode/T_global'] = T_global = self.pull_getattr('env.T') + self.env.t self.push_setattr('env.T', T_global) # not exactly thread-safe, but that's okay self.env.record_metrics(metrics) def learn_loop(self, max_total_steps, batch_size=32): throughput = 0. while self.pull_getattr('env.T') < max_total_steps: t_start = time.time() self.pull_state() metrics = self.learn(self.buffer_sample(batch_size=batch_size)) metrics['throughput/learn_loop'] = throughput self.push_state() self.push_metrics(metrics) throughput = batch_size / (time.time() - t_start) def buffer_len(self): if self.param_store is None: assert self.buffer is not None len_ = len(self.buffer) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): len_ = self.__ray.get(self.param_store.buffer_len.remote()) else: len_ = self.param_store.buffer_len() return len_ def buffer_add(self, transition_batch, Adv=None): if self.param_store is None: assert self.buffer is not None if 'Adv' in inspect.signature(self.buffer.add).parameters: # duck typing self.buffer.add(transition_batch, Adv=Adv) else: self.buffer.add(transition_batch) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): self.__ray.get(self.param_store.buffer_add.remote(transition_batch, Adv)) else: self.param_store.buffer_add(transition_batch, Adv) def buffer_update(self, transition_batch_idx, Adv): if self.param_store is None: assert self.buffer is not None self.buffer.update(transition_batch_idx, Adv=Adv) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): self.__ray.get(self.param_store.buffer_update.remote(transition_batch_idx, Adv)) else: self.param_store.buffer_update(transition_batch_idx, Adv) def buffer_sample(self, batch_size=32): buffer_warmup = max(self.buffer_warmup or 0, batch_size) wait_secs = 1 / 1024. buffer_len = self.buffer_len() while buffer_len < buffer_warmup: self.env.logger.debug( f"buffer insufficiently populated: {buffer_len}/{buffer_warmup}; " f"waiting for {wait_secs}s") time.sleep(wait_secs) wait_secs = min(30, wait_secs * 2) # wait at most 30s between tries buffer_len = self.buffer_len() if self.param_store is None: assert self.buffer is not None transition_batch = self.buffer.sample(batch_size=batch_size) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): transition_batch = self.__ray.get( self.param_store.buffer_sample.remote(batch_size=batch_size)) else: transition_batch = self.param_store.buffer_sample(batch_size=batch_size) assert transition_batch is not None return transition_batch def pull_state(self): assert self.param_store is not None, "cannot call pull_state on param_store itself" if isinstance(self.param_store, self.__ray.actor.ActorHandle): self.set_state(self.__ray.get(self.param_store.get_state.remote())) else: self.set_state(self.param_store.get_state()) def push_state(self): assert self.param_store is not None, "cannot call push_state on param_store itself" if isinstance(self.param_store, self.__ray.actor.ActorHandle): self.__ray.get(self.param_store.set_state.remote(self.get_state())) else: self.param_store.set_state(self.get_state()) def pull_metrics(self): if self.param_store is None: metrics = self.env.get_metrics() elif isinstance(self.param_store, self.__ray.actor.ActorHandle): metrics = self.__ray.get(self.param_store.pull_metrics.remote()).copy() else: metrics = self.param_store.pull_metrics() return metrics def push_metrics(self, metrics): if self.param_store is None: self.env.record_metrics(metrics) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): self.__ray.get(self.param_store.push_metrics.remote(metrics)) else: self.param_store.push_metrics(metrics) def pull_getattr(self, name, default_value=...): if self.param_store is None: value = _getattr_recursive(self, name, default_value) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): value = self.__ray.get(self.param_store.pull_getattr.remote(name, default_value)) else: value = self.param_store.pull_getattr(name, default_value) return value def push_setattr(self, name, value): if self.param_store is None: _setattr_recursive(self, name, value) elif isinstance(self.param_store, self.__ray.actor.ActorHandle): self.__ray.get(self.param_store.push_setattr.remote(name, value)) else: self.param_store.push_setattr(name, value) # -- some helper functions (boilerplate) --------------------------------------------------------- # def _check_env(env, name): if isinstance(env, gymnasium.Env): pass elif isinstance(env, str): env = gymnasium.make(env) elif hasattr(env, '__call__'): env = env() else: raise TypeError(f"env must be a gymnasium.Env, str or callable; got: {type(env)}") if getattr(getattr(env, 'spec', None), 'max_episode_steps', None) is None: raise ValueError( "env.spec.max_episode_steps not set; please register env with " "gymnasium.register('Foo-v0', entry_point='foo.Foo', max_episode_steps=...) " "or wrap your env with: env = gymnasium.wrappers.TimeLimit(env, max_episode_steps=...)") if not isinstance(env, TrainMonitor): env = TrainMonitor(env, name=name, log_all_metrics=True) return env def _check_reward_threshold(reward_threshold, env): if reward_threshold is None: reward_threshold = getattr(getattr(env, 'spec', None), 'reward_threshold', None) if reward_threshold is None: reward_threshold = float('inf') return reward_threshold def _getattr_recursive(obj, name, default=...): if '.' not in name: return getattr(obj, name) if default is Ellipsis else getattr(obj, name, default) name, subname = name.split('.', 1) return _getattr_recursive(getattr(obj, name), subname, default) def _setattr_recursive(obj, name, value): if '.' not in name: return setattr(obj, name, value) name, subname = name.split('.', 1) return _setattr_recursive(getattr(obj, name), subname, value)
11,753
32.487179
100
py
null
coax-main/coax/envs/__init__.py
r""" Environments ============ .. autosummary:: :nosignatures: coax.envs.ConnectFourEnv ---- This is a collection of environments currently not included in `Gymnasium <https://gymnasium.farama.org/>`_. Object Reference ---------------- .. autoclass:: coax.envs.ConnectFourEnv """ from ._connect_four import ConnectFourEnv __all__ = ( 'ConnectFourEnv', )
377
12.034483
62
py
null
coax-main/coax/envs/_connect_four.py
from gymnasium import Env from gymnasium.spaces import Discrete, MultiDiscrete import numpy as np from .._base.errors import UnavailableActionError, EpisodeDoneError __all__ = ( 'ConnectFourEnv', ) class ConnectFourEnv(Env): r""" An adversarial environment for playing the `Connect-Four game <https://en.wikipedia.org/wiki/Connect_Four>`_. Attributes ---------- action_space : gymnasium.spaces.Discrete(7) The action space. observation_space : MultiDiscrete(nvec) The state observation space, representing the position of the current player's tokens (``s[1:,:,0]``) and the other player's tokens (``s[1:,:,1]``) as well as a mask over the space of actions, indicating which actions are available to the current player (``s[0,:,0]``) or the other player (``s[0,:,1]``). **Note:** The "current" player is relative to whose turn it is, which means that the entries ``s[:,:,0]`` and ``s[:,:,1]`` swap between turns. max_time_steps : int Maximum number of timesteps within each episode. available_actions : array of int Array of available actions. This list shrinks when columns saturate. win_reward : 1.0 The reward associated with a win. loss_reward : -1.0 The reward associated with a loss. draw_reward : 0.0 The reward associated with a draw. """ # noqa: E501 # class attributes num_rows = 6 num_cols = 7 num_players = 2 win_reward = 1.0 loss_reward = -win_reward draw_reward = 0.0 action_space = Discrete(num_cols) observation_space = MultiDiscrete( nvec=np.full((num_rows + 1, num_cols, num_players), 2, dtype='uint8')) max_time_steps = int(num_rows * num_cols) filters = np.array([ [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1]], [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]], [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]], [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]], [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]], [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]], [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]], ], dtype='uint8') def __init__(self): self._init_state() def reset(self): r""" Reset the environment to the starting position. Returns ------- s : 3d-array, shape: [num_rows + 1, num_cols, num_players] A state observation, representing the position of the current player's tokens (``s[1:,:,0]``) and the other player's tokens (``s[1:,:,1]``) as well as a mask over the space of actions, indicating which actions are available to the current player (``s[0,:,0]``) or the other player (``s[0,:,1]``). **Note:** The "current" player is relative to whose turn it is, which means that the entries ``s[:,:,0]`` and ``s[:,:,1]`` swap between turns. """ self._init_state() return self.state def step(self, a): r""" Take one step in the MDP, following the single-player convention from gymnasium. Parameters ---------- a : int, options: {0, 1, 2, 3, 4, 5, 6} The action to be taken. The action is the zero-based count of the possible insertion slots, starting from the left of the board. Returns ------- s_next : array, shape [6, 7, 2] A next-state observation, representing the position of the current player's tokens (``s[1:,:,0]``) and the other player's tokens (``s[1:,:,1]``) as well as a mask over the space of actions, indicating which actions are available to the current player (``s[0,:,0]``) or the other player (``s[0,:,1]``). **Note:** The "current" player is relative to whose turn it is, which means that the entries ``s[:,:,0]`` and ``s[:,:,1]`` swap between turns. r : float Reward associated with the transition :math:`(s, a)\to s_\text{next}`. **Note:** Since "current" player is relative to whose turn it is, you need to be careful about aligning the rewards with the correct state or state-action pair. In particular, this reward :math:`r` is the one associated with the :math:`s` and :math:`a`, i.e. *not* aligned with :math:`s_\text{next}`. done : bool Whether the episode is done. info : dict or None A dict with some extra information (or None). """ if self.done: raise EpisodeDoneError("please reset env to start new episode") if not self.action_space.contains(a): raise ValueError(f"invalid action: {repr(a)}") if a not in self.available_actions: raise UnavailableActionError("action is not available") # swap players self._players = np.roll(self._players, -1) # update state self._state[self._levels[a], a] = self._players[0] self._prev_action = a # run logic self.done, reward = self._done_reward(a) return self.state, reward, self.done, {'state_id': self.state_id} def render(self, *args, **kwargs): r""" Render the current state of the environment. """ # lookup for symbols symbol = { 1: u'\u25CF', # player 1 token (agent) 2: u'\u25CB', # player 2 token (adversary) -1: u'\u25BD', # indicator for player 1's last action -2: u'\u25BC', # indicator for player 2's last action } # render board hrule = '+---' * self.num_cols + '+\n' board = " " board += " ".join( symbol.get(-(a == self._prev_action) * self._players[1], " ") for a in range(self.num_cols)) board += " \n" board += hrule for i in range(self.num_rows): board += "| " board += " | ".join( symbol.get(self._state[i, j], " ") for j in range(self.num_cols)) board += " |\n" board += hrule board += " 0 1 2 3 4 5 6 \n" # actions print(board) @property def state(self): stacked_layers = np.stack(( (self._state == self._players[0]).astype('uint8'), (self._state == self._players[1]).astype('uint8'), ), axis=-1) # shape: [num_rows, num_cols, num_players] available_actions_mask = np.zeros( (1, self.num_cols, self.num_players), dtype='uint8') available_actions_mask[0, self.available_actions, :] = 1 return np.concatenate((available_actions_mask, stacked_layers), axis=0) @property def state_id(self): p = str(self._players[0]) d = '1' if self.done else '0' if self._prev_action is None: a = str(self.num_cols) else: a = str(self._prev_action) s = ''.join(self._state.ravel().astype('str')) # base-3 string s = '{:017x}'.format(int(s, 3)) # 17-char hex string return p + d + a + s # 20-char hex string def set_state(self, state_id): # decode state id p = int(state_id[0], 16) d = int(state_id[1], 16) a = int(state_id[2], 16) assert p in (1, 2) assert d in (0, 1) assert self.action_space.contains(a) or a == self.num_cols self._players[0] = p # 1 or 2 self._players[1] = 3 - p # 2 or 1 self.done = d == 1 self._prev_action = None if a == self.num_cols else a s = np._base_repr(int(state_id[3:], 16), 3) z = np.zeros(self.num_rows * self.num_cols, dtype='uint8') z[-len(s):] = np.array(list(s), dtype='uint8') self._state = z.reshape((self.num_rows, self.num_cols)) self._levels = np.full(self.num_cols, self.num_rows - 1, dtype='uint8') for j in range(self.num_cols): for i in self._state[::-1, j]: if i == 0: break self._levels[j] -= 1 @property def available_actions(self): actions = np.argwhere( (self._levels >= 0) & (self._levels < self.num_rows)).ravel() assert actions.size <= self.num_cols return actions @property def available_actions_mask(self): mask = np.zeros(self.num_cols, dtype='bool') mask[self.available_actions] = True return mask def _init_state(self): self._prev_action = None self._players = np.array([1, 2], dtype='uint8') self._state = np.zeros((self.num_rows, self.num_cols), dtype='uint8') self._levels = np.full(self.num_cols, self.num_rows - 1, dtype='uint8') self.done = False def _done_reward(self, a): r""" Check whether the last action `a` by the current player resulted in a win or draw for player 1 (the agent). This contains the main logic and implements the rules of the game. """ assert self.action_space.contains(a) # update filling levels self._levels[a] -= 1 s = self._state == self._players[0] for i0 in range(2, -1, -1): i1 = i0 + 4 for j0 in range(4): j1 = j0 + 4 if np.any(np.tensordot(self.filters, s[i0:i1, j0:j1]) == 4): return True, 1.0 # check for a draw if len(self.available_actions) == 0: return True, 0.0 # this is what's returned throughout the episode return False, 0.0
10,349
31.961783
79
py
null
coax-main/coax/experience_replay/__init__.py
r""" Experience Replay ================= .. autosummary:: :nosignatures: coax.experience_replay.SimpleReplayBuffer coax.experience_replay.PrioritizedReplayBuffer ---- This is where we keep our experience-replay buffer classes. Some examples of agents that use a replay buffer are: * :doc:`/examples/stubs/dqn` * :doc:`/examples/stubs/dqn_per`. For specific examples, have a look at the :doc:`agents for Atari games </examples/atari/index>`. Object Reference ---------------- .. autoclass:: coax.experience_replay.SimpleReplayBuffer .. autoclass:: coax.experience_replay.PrioritizedReplayBuffer """ from ._simple import SimpleReplayBuffer from ._prioritized import PrioritizedReplayBuffer __all__ = ( 'SimpleReplayBuffer', 'PrioritizedReplayBuffer', )
785
19.153846
96
py
null
coax-main/coax/experience_replay/_base.py
from abc import ABC, abstractmethod __all__ = ( 'BaseReplayBuffer', ) class BaseReplayBuffer(ABC): @property @abstractmethod def capacity(self): pass @abstractmethod def add(self, transition_batch): pass @abstractmethod def sample(self, batch_size=32): pass @abstractmethod def clear(self): pass @abstractmethod def __len__(self): pass @abstractmethod def __bool__(self): pass @abstractmethod def __iter__(self): pass
549
13.102564
36
py
null
coax-main/coax/experience_replay/_prioritized.py
import jax import numpy as onp import chex from ..reward_tracing import TransitionBatch from ..utils import SumTree from ._base import BaseReplayBuffer __all__ = ( 'PrioritizedReplayBuffer', ) class PrioritizedReplayBuffer(BaseReplayBuffer): r""" A simple ring buffer for experience replay, with prioritized sampling. This class uses *proportional* sampling, which means that the transitions are sampled with relative probability :math:`p_i` defined as: .. math:: p_i\ =\ \frac {\left(|\mathcal{A}_i| + \epsilon\right)^\alpha} {\sum_{j=1}^N \left(|\mathcal{A}_j| + \epsilon\right)^\alpha} Here :math:`\mathcal{A}_i` are advantages provided at insertion time and :math:`N` is the capacity of the buffer, which may be quite large. The :math:`\mathcal{A}_i` are typically just TD errors collected from a value-function updater, e.g. :func:`QLearning.td_error <coax.td_learning.QLearning.td_error>`. Since the prioritized samples are biased, the :attr:`sample` method also produces non-trivial importance weights (stored in the :class:`TransitionBatch.W <coax.reward_tracing.TransitionBatch>` attribute). The logic for constructing these weights for a sample of batch size :math:`n` is: .. math:: w_i\ =\ \frac{\left(Np_i\right)^{-\beta}}{\max_{j=1}^n \left(Np_j\right)^{-\beta}} See section 3.4 of https://arxiv.org/abs/1511.05952 for more details. Parameters ---------- capacity : positive int The capacity of the experience replay buffer. alpha : positive float, optional The sampling temperature :math:`\alpha>0`. beta : positive float, optional The importance-weight exponent :math:`\beta>0`. epsilon : positive float, optional The small regulator :math:`\epsilon>0`. random_seed : int, optional To get reproducible results. """ def __init__(self, capacity, alpha=1.0, beta=1.0, epsilon=1e-4, random_seed=None): if not (isinstance(capacity, int) and capacity > 0): raise TypeError(f"capacity must be a positive int, got: {capacity}") if not (isinstance(alpha, (float, int)) and alpha > 0): raise TypeError(f"alpha must be a positive float, got: {alpha}") if not (isinstance(beta, (float, int)) and beta > 0): raise TypeError(f"beta must be a positive float, got: {beta}") if not (isinstance(epsilon, (float, int)) and epsilon > 0): raise TypeError(f"epsilon must be a positive float, got: {epsilon}") self._capacity = int(capacity) self._alpha = float(alpha) self._beta = float(beta) self._epsilon = float(epsilon) self._random_seed = random_seed self._rnd = onp.random.RandomState(random_seed) self.clear() # sets: self._deque, self._index @property def capacity(self): return self._capacity @property def alpha(self): return self._alpha @alpha.setter def alpha(self, new_alpha): if not (isinstance(new_alpha, (float, int)) and new_alpha > 0): raise TypeError(f"alpha must be a positive float, got: {new_alpha}") if onp.isclose(new_alpha, self._alpha, rtol=0.01): return # noop if new value is too close to old value (not worth the computation cost) new_values = onp.where( self._sumtree.values <= 0, 0., # only change exponents for positive values onp.exp(onp.log(onp.maximum(self._sumtree.values, 1e-15)) * (new_alpha / self._alpha))) self._sumtree.set_values(..., new_values) self._alpha = float(new_alpha) @property def beta(self): return self._beta @beta.setter def beta(self, new_beta): if not (isinstance(new_beta, (float, int)) and new_beta > 0): raise TypeError(f"beta must be a positive float, got: {new_beta}") self._beta = float(new_beta) @property def epsilon(self): return self._epsilon @epsilon.setter def epsilon(self, new_epsilon): if not (isinstance(new_epsilon, (float, int)) and new_epsilon > 0): raise TypeError(f"epsilon must be a positive float, got: {new_epsilon}") self._epsilon = float(new_epsilon) def add(self, transition_batch, Adv): r""" Add a transition to the experience replay buffer. Parameters ---------- transition_batch : TransitionBatch A :class:`TransitionBatch <coax.reward_tracing.TransitionBatch>` object. Adv : ndarray A batch of advantages, used to construct the priorities :math:`p_i`. """ if not isinstance(transition_batch, TransitionBatch): raise TypeError( f"transition_batch must be a TransitionBatch, got: {type(transition_batch)}") transition_batch.idx = self._index + onp.arange(transition_batch.batch_size) idx = transition_batch.idx % self.capacity # wrap around chex.assert_equal_shape([idx, Adv]) self._storage[idx] = list(transition_batch.to_singles()) self._sumtree.set_values(idx, onp.power(onp.abs(Adv) + self.epsilon, self.alpha)) self._index += transition_batch.batch_size def sample(self, batch_size=32): r""" Get a batch of transitions to be used for bootstrapped updates. Parameters ---------- batch_size : positive int, optional The desired batch size of the sample. Returns ------- transitions : TransitionBatch A :class:`TransitionBatch <coax.reward_tracing.TransitionBatch>` object. """ idx = self._sumtree.sample(n=batch_size) P = self._sumtree.values[idx] / self._sumtree.root_value # prioritized, biased propensities W = onp.power(P * len(self), -self.beta) # inverse propensity weights (β≈1) W /= W.max() # for stability, ensure only down-weighting (see sec. 3.4 of arxiv:1511.05952) transition_batch = _concatenate_leaves(self._storage[idx]) chex.assert_equal_shape([transition_batch.W, W]) transition_batch.W *= W return transition_batch def update(self, idx, Adv): r""" Update the priority weights of transitions previously added to the buffer. Parameters ---------- idx : 1d array of ints The identifiers of the transitions to be updated. Adv : ndarray The corresponding updated advantages. """ idx = onp.asarray(idx, dtype='int32') Adv = onp.asarray(Adv, dtype='float32') chex.assert_equal_shape([idx, Adv]) chex.assert_rank([idx, Adv], 1) idx_lookup = idx % self.capacity # wrap around new_values = onp.where( _get_transition_batch_idx(self._storage[idx_lookup]) == idx, # only update if ids match onp.power(onp.abs(Adv) + self.epsilon, self.alpha), self._sumtree.values[idx_lookup]) self._sumtree.set_values(idx_lookup, new_values) def clear(self): r""" Clear the experience replay buffer. """ self._storage = onp.full(shape=(self.capacity,), fill_value=None, dtype='object') self._sumtree = SumTree(capacity=self.capacity, random_seed=self._random_seed) self._index = 0 def __len__(self): return min(self.capacity, self._index) def __bool__(self): return bool(len(self)) def __iter__(self): return iter(self._storage[:len(self)]) def _concatenate_leaves(pytrees): return jax.tree_map(lambda *leaves: onp.concatenate(leaves, axis=0), *pytrees) @onp.vectorize def _get_transition_batch_idx(transition): return transition.idx
7,832
32.909091
100
py
null
coax-main/coax/experience_replay/_prioritized_test.py
from copy import deepcopy import gymnasium import pytest import numpy as onp from ..utils import get_transition_batch from ._simple import SimpleReplayBuffer from ._prioritized import PrioritizedReplayBuffer @pytest.mark.parametrize('n', [2, 4]) # 2 * batch_size < capacity, 4 * batch_size > capacity def test_consistency(n): env = gymnasium.make('FrozenLakeNonSlippery-v0') buffer1 = SimpleReplayBuffer(capacity=100) buffer2 = PrioritizedReplayBuffer(capacity=100) for i in range(n): transition_batch = get_transition_batch(env, batch_size=32, random_seed=i) buffer1.add(transition_batch) buffer2.add(transition_batch, Adv=transition_batch.Rn) # test TransitionBatch.__eq__ assert buffer1._storage[0] == buffer1._storage[0] assert buffer1._storage[0] != buffer1._storage[1] # test consistency between two buffers assert len(buffer1) == len(buffer2) for i in range(len(buffer1)): t1 = buffer1._storage[i] t2 = buffer2._storage[(i + buffer2._index) % len(buffer2)] assert t1 == t2 def test_sample(): env = gymnasium.make('FrozenLakeNonSlippery-v0') buffer1 = SimpleReplayBuffer(capacity=100, random_seed=13) buffer2 = PrioritizedReplayBuffer(capacity=100, random_seed=13) for i in range(4): transition_batch = get_transition_batch(env, batch_size=32, random_seed=i) transition_batch.W = onp.ones_like(transition_batch.W) # start with uniform weights buffer1.add(transition_batch) buffer2.add(transition_batch.copy(), Adv=transition_batch.Rn) assert onp.allclose(buffer1.sample(batch_size=10).W, onp.ones(10)) assert not onp.allclose(buffer2.sample(batch_size=10).W, onp.ones(10)) def test_alpha(): env = gymnasium.make('FrozenLakeNonSlippery-v0') buffer = PrioritizedReplayBuffer(capacity=100, random_seed=13, alpha=0.8) for i in range(4): transition_batch = get_transition_batch(env, batch_size=32, random_seed=i) transition_batch.W = onp.ones_like(transition_batch.W) # start with uniform weights buffer.add(transition_batch.copy(), Adv=transition_batch.Rn) with pytest.raises(TypeError): buffer.alpha = 'foo' with pytest.raises(TypeError): buffer.alpha = 0. with pytest.raises(TypeError): buffer.alpha = -1. assert onp.isclose(buffer.alpha, 0.8) old_values = deepcopy(buffer._sumtree.values) old_alpha = buffer.alpha buffer.alpha *= 1.5 assert onp.isclose(buffer.alpha, 1.2) new_values = buffer._sumtree.values new_alpha = buffer.alpha diff = 2 * (new_values - old_values) / (new_values + old_values) assert onp.min(onp.abs(diff)) > 1e-3 assert onp.allclose(onp.power(new_values, 1 / new_alpha), onp.power(old_values, 1 / old_alpha)) def test_update(): env = gymnasium.make('FrozenLakeNonSlippery-v0') buffer = PrioritizedReplayBuffer(capacity=100, random_seed=13, alpha=0.8) for i in range(buffer.capacity): transition_batch = get_transition_batch(env, random_seed=i) transition_batch.W = onp.ones_like(transition_batch.W) # start with uniform weights buffer.add(transition_batch.copy(), Adv=transition_batch.Rn) t = buffer.sample(50) old_values = deepcopy(buffer._sumtree.values) print(t) # add more transitions after sampling for i in range(buffer.capacity // 2): transition_batch = get_transition_batch(env, random_seed=(buffer.capacity + i)) transition_batch.W = onp.ones_like(transition_batch.W) # start with uniform weights buffer.add(transition_batch.copy(), Adv=transition_batch.Rn) # update values where some transitions in buffer have been replaced by newer transitions Adv_new = get_transition_batch(env, batch_size=t.batch_size, random_seed=7).Rn buffer.update(t.idx, Adv_new) new_values = buffer._sumtree.values # all values in first half are replaced by buffer.add() r = slice(None, 50) diff = 2 * (new_values[r] - old_values[r]) / (new_values[r] + old_values[r]) print(onp.abs(diff)) assert onp.min(onp.abs(diff)) > 1e-3 # not replaced by buffer.add(), but updated by buffer.update() u = t.idx[t.idx >= 50] diff = 2 * (new_values[u] - old_values[u]) / (new_values[u] + old_values[u]) print(onp.abs(diff)) assert onp.min(onp.abs(diff)) > 1e-4 # neither replaced by buffer.add() nor updated by buffer.update() n = ~onp.isin(onp.arange(100), t.idx) & (onp.arange(100) >= 50) print(new_values[n]) print(old_values[n]) assert onp.sum(n) > 0 assert onp.allclose(new_values[n], old_values[n])
4,654
36.540323
99
py
null
coax-main/coax/experience_replay/_simple.py
import random import jax import numpy as onp from ..reward_tracing import TransitionBatch from ._base import BaseReplayBuffer __all__ = ( 'SimpleReplayBuffer', ) class SimpleReplayBuffer(BaseReplayBuffer): r""" A simple ring buffer for experience replay. Parameters ---------- capacity : positive int The capacity of the experience replay buffer. random_seed : int, optional To get reproducible results. """ def __init__(self, capacity, random_seed=None): self._capacity = int(capacity) random.seed(random_seed) self._random_state = random.getstate() self.clear() # sets self._storage @property def capacity(self): return self._capacity def add(self, transition_batch): r""" Add a transition to the experience replay buffer. Parameters ---------- transition_batch : TransitionBatch A :class:`TransitionBatch <coax.reward_tracing.TransitionBatch>` object. """ if not isinstance(transition_batch, TransitionBatch): raise TypeError( f"transition_batch must be a TransitionBatch, got: {type(transition_batch)}") transition_batch.idx = onp.arange(self._index, self._index + transition_batch.batch_size) self._index += transition_batch.batch_size self._storage.extend(transition_batch.to_singles()) while len(self) > self.capacity: self._storage.pop(0) def sample(self, batch_size=32): r""" Get a batch of transitions to be used for bootstrapped updates. Parameters ---------- batch_size : positive int, optional The desired batch size of the sample. Returns ------- transitions : TransitionBatch A :class:`TransitionBatch <coax.reward_tracing.TransitionBatch>` object. """ # sandwich sample in between setstate/getstate in case global random state was tampered with random.setstate(self._random_state) transitions = random.sample(self._storage, batch_size) self._random_state = random.getstate() return jax.tree_map(lambda *leaves: onp.concatenate(leaves, axis=0), *transitions) def clear(self): r""" Clear the experience replay buffer. """ self._storage = list() self._index = 0 def __len__(self): return len(self._storage) def __bool__(self): return bool(len(self)) def __iter__(self): return iter(self._storage)
2,588
25.151515
100
py
null
coax-main/coax/model_updaters/__init__.py
r""" Model Updaters ============== .. autosummary:: :nosignatures: coax.model_updaters.ModelUpdater ---- This is a collection of objects that are used to update dynamics models, i.e. transition models and reward functions. Object Reference ---------------- .. autoclass:: coax.model_updaters.ModelUpdater """ # TODO(krholshe): think of better names for this module and classes from ._model_updater import ModelUpdater __all__ = ( 'ModelUpdater', )
472
14.258065
99
py
null
coax-main/coax/model_updaters/_model_updater.py
import jax import jax.numpy as jnp import haiku as hk import optax from ..utils import ( get_grads_diagnostics, is_stochastic, is_reward_function, is_transition_model, jit) from ..value_losses import huber from ..regularizers import Regularizer __all__ = ( 'ModelUpdater', ) class ModelUpdater: r""" Model updater that uses *sampling* for maximum-likelihood estimation. Parameters ---------- model : [Stochastic]TransitionModel or [Stochastic]RewardFunction The main dynamics model to update. optimizer : optax optimizer, optional An optax-style optimizer. The default optimizer is :func:`optax.adam(1e-3) <optax.adam>`. loss_function : callable, optional The loss function that will be used to regress to the (bootstrapped) target. The loss function is expected to be of the form: .. math:: L(y_\text{true}, y_\text{pred}, w)\in\mathbb{R} where :math:`w>0` are sample weights. If left unspecified, this defaults to :func:`coax.value_losses.huber`. Check out the :mod:`coax.value_losses` module for other predefined loss functions. regularizer : Regularizer, optional A stochastic regularizer, see :mod:`coax.regularizers`. """ def __init__(self, model, optimizer=None, loss_function=None, regularizer=None): if not (is_reward_function(model) or is_transition_model(model)): raise TypeError(f"model must be a dynamics model, got: {type(model)}") if not isinstance(regularizer, (Regularizer, type(None))): raise TypeError(f"regularizer must be a Regularizer, got: {type(regularizer)}") self.model = model self.loss_function = huber if loss_function is None else loss_function self.regularizer = regularizer # optimizer self._optimizer = optax.adam(1e-3) if optimizer is None else optimizer self._optimizer_state = self.optimizer.init(self.model.params) def apply_grads_func(opt, opt_state, params, grads): updates, new_opt_state = opt.update(grads, opt_state, params) new_params = optax.apply_updates(params, updates) return new_opt_state, new_params def loss_func(params, state, hyperparams, rng, transition_batch): rngs = hk.PRNGSequence(rng) S = self.model.observation_preprocessor(next(rngs), transition_batch.S) A = self.model.action_preprocessor(next(rngs), transition_batch.A) W = jnp.clip(transition_batch.W, 0.1, 10.) # clip importance weights to reduce variance if is_stochastic(self.model): dist_params, new_state = \ self.model.function_type1(params, state, next(rngs), S, A, True) y_pred = self.model.proba_dist.sample(dist_params, next(rngs)) else: y_pred, new_state = self.model.function_type1(params, state, next(rngs), S, A, True) if is_transition_model(self.model): y_true = self.model.observation_preprocessor(next(rngs), transition_batch.S_next) elif is_reward_function(self.model): y_true = self.model.value_transform.transform_func(transition_batch.Rn) else: raise AssertionError(f"unexpected model type: {type(self.model)}") loss = self.loss_function(y_true, y_pred, W) metrics = { f'{self.__class__.__name__}/loss': loss, f'{self.__class__.__name__}/loss_bare': loss, } # add regularization term if self.regularizer is not None: hparams = hyperparams['regularizer'] loss = loss + jnp.mean(W * self.regularizer.function(dist_params, **hparams)) metrics[f'{self.__class__.__name__}/loss'] = loss metrics.update(self.regularizer.metrics_func(dist_params, **hparams)) return loss, (metrics, new_state) def grads_and_metrics_func(params, state, hyperparams, rng, transition_batch): grads, (metrics, new_state) = \ jax.grad(loss_func, has_aux=True)(params, state, hyperparams, rng, transition_batch) # add some diagnostics of the gradients metrics.update(get_grads_diagnostics(grads, f'{self.__class__.__name__}/grads_')) return grads, new_state, metrics self._apply_grads_func = jit(apply_grads_func, static_argnums=0) self._grads_and_metrics_func = jit(grads_and_metrics_func) def update(self, transition_batch): r""" Update the model parameters (weights) of the underlying function approximator. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Returns ------- metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ grads, function_state, metrics = self.grads_and_metrics(transition_batch) if any(jnp.any(jnp.isnan(g)) for g in jax.tree_util.tree_leaves(grads)): raise RuntimeError(f"found nan's in grads: {grads}") self.apply_grads(grads, function_state) return metrics def apply_grads(self, grads, function_state): r""" Update the model parameters (weights) of the underlying function approximator given pre-computed gradients. This method is useful in situations in which computation of the gradients is deligated to a separate (remote) process. Parameters ---------- grads : pytree with ndarray leaves A batch of gradients, generated by the :attr:`grads` method. function_state : pytree The internal state of the forward-pass function. See :attr:`Q.function_state <coax.Q.function_state>` and :func:`haiku.transform_with_state` for more details. """ self.model.function_state = function_state self.optimizer_state, self.model.params = \ self._apply_grads_func(self.optimizer, self.optimizer_state, self.model.params, grads) def grads_and_metrics(self, transition_batch): r""" Compute the gradients associated with a batch of transitions. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Returns ------- grads : pytree with ndarray leaves A batch of gradients. function_state : pytree The internal state of the forward-pass function. See :attr:`Q.function_state <coax.Q.function_state>` and :func:`haiku.transform_with_state` for more details. metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ return self._grads_and_metrics_func( self.model.params, self.model.function_state, self.hyperparams, self.model.rng, transition_batch) @property def hyperparams(self): return hk.data_structures.to_immutable_dict({ 'regularizer': getattr(self.regularizer, 'hyperparams', {})}) @property def optimizer(self): return self._optimizer @optimizer.setter def optimizer(self, new_optimizer): new_optimizer_state_structure = jax.tree_util.tree_structure( new_optimizer.init(self.model.params)) if new_optimizer_state_structure != jax.tree_util.tree_structure(self.optimizer_state): raise AttributeError("cannot set optimizer attr: mismatch in optimizer_state structure") self._optimizer = new_optimizer @property def optimizer_state(self): return self._optimizer_state @optimizer_state.setter def optimizer_state(self, new_optimizer_state): new_tree_structure = jax.tree_util.tree_structure(new_optimizer_state) tree_structure = jax.tree_util.tree_structure(self.optimizer_state) if new_tree_structure != tree_structure: raise AttributeError("cannot set optimizer_state attr: mismatch in tree structure") self._optimizer_state = new_optimizer_state
8,272
35.606195
100
py
null
coax-main/coax/model_updaters/_model_updater_test.py
from copy import deepcopy from optax import sgd from .._base.test_case import TestCase from .._core.stochastic_transition_model import StochasticTransitionModel from ..utils import get_transition_batch from ..regularizers import EntropyRegularizer from ._model_updater import ModelUpdater class TestModelUpdater(TestCase): def setUp(self): self.transition_discrete = get_transition_batch(self.env_discrete, random_seed=42) self.transition_boxspace = get_transition_batch(self.env_boxspace, random_seed=42) def test_update_type1(self): env = self.env_discrete func_p = self.func_p_type1 transition_batch = self.transition_discrete p = StochasticTransitionModel(func_p, env, random_seed=11) updater = ModelUpdater(p, optimizer=sgd(1.0)) params = deepcopy(p.params) function_state = deepcopy(p.function_state) updater.update(transition_batch) self.assertPytreeNotEqual(params, p.params) self.assertPytreeNotEqual(function_state, p.function_state) def test_update_type2(self): env = self.env_discrete func_p = self.func_p_type2 transition_batch = self.transition_discrete p = StochasticTransitionModel(func_p, env, random_seed=11) updater = ModelUpdater(p, optimizer=sgd(1.0)) params = deepcopy(p.params) function_state = deepcopy(p.function_state) updater.update(transition_batch) self.assertPytreeNotEqual(params, p.params) self.assertPytreeNotEqual(function_state, p.function_state) def test_policyreg(self): env = self.env_discrete func_p = self.func_p_type1 transition_batch = self.transition_discrete p = StochasticTransitionModel(func_p, env, random_seed=11) params_init = deepcopy(p.params) function_state_init = deepcopy(p.function_state) # first update without policy regularizer updater = ModelUpdater(p, optimizer=sgd(1.0)) updater.update(transition_batch) params_without_reg = deepcopy(p.params) function_state_without_reg = deepcopy(p.function_state) self.assertPytreeNotEqual(params_without_reg, params_init) self.assertPytreeNotEqual(function_state_without_reg, function_state_init) # reset weights p = StochasticTransitionModel(func_p, env, random_seed=11) self.assertPytreeAlmostEqual(params_init, p.params) self.assertPytreeAlmostEqual(function_state_init, p.function_state) # then update with policy regularizer reg = EntropyRegularizer(p, beta=1.0) updater = ModelUpdater(p, optimizer=sgd(1.0), regularizer=reg) updater.update(transition_batch) params_with_reg = deepcopy(p.params) function_state_with_reg = deepcopy(p.function_state) self.assertPytreeNotEqual(params_with_reg, params_init) self.assertPytreeNotEqual(params_with_reg, params_without_reg) # <---- important self.assertPytreeNotEqual(function_state_with_reg, function_state_init) self.assertPytreeAlmostEqual(function_state_with_reg, function_state_without_reg) # same!
3,182
37.349398
98
py
null
coax-main/coax/policy_objectives/__init__.py
r""" Policy Objectives ================= .. autosummary:: :nosignatures: coax.policy_objectives.VanillaPG coax.policy_objectives.PPOClip coax.policy_objectives.DeterministicPG coax.policy_objectives.SoftPG ---- This is a collection of policy objectives that can be used in policy-gradient methods. Object Reference ---------------- .. autoclass:: coax.policy_objectives.VanillaPG .. autoclass:: coax.policy_objectives.PPOClip .. autoclass:: coax.policy_objectives.DeterministicPG .. autoclass:: coax.policy_objectives.SoftPG """ from ._base import PolicyObjective from ._vanilla_pg import VanillaPG from ._ppo_clip import PPOClip from ._deterministic_pg import DeterministicPG from ._soft_pg import SoftPG __all__ = ( 'PolicyObjective', 'VanillaPG', # 'CrossEntropy', # TODO 'PPOClip', 'DeterministicPG', 'SoftPG' )
873
18.422222
77
py
null
coax-main/coax/policy_objectives/_base.py
import warnings import jax import jax.numpy as jnp import optax import haiku as hk from .._core.policy import Policy from ..utils import get_grads_diagnostics, jit from ..regularizers import Regularizer class PolicyObjective: r""" Abstract base class for policy objectives. To see a concrete example, have a look at :class:`coax.policy_objectives.VanillaPG`. Parameters ---------- pi : Policy The parametrized policy :math:`\pi_\theta(a|s)`. regularizer : Regularizer, optional A policy regularizer, see :mod:`coax.regularizers`. """ REQUIRES_PROPENSITIES = None def __init__(self, pi, optimizer=None, regularizer=None): if not isinstance(pi, Policy): raise TypeError(f"pi must be a Policy, got: {type(pi)}") if not isinstance(regularizer, (Regularizer, type(None))): raise TypeError(f"regularizer must be a Regularizer, got: {type(regularizer)}") self._pi = pi self._regularizer = regularizer # optimizer self._optimizer = optax.adam(1e-3) if optimizer is None else optimizer self._optimizer_state = self.optimizer.init(self._pi.params) def loss_func(params, state, hyperparams, rng, transition_batch, Adv): objective, (dist_params, log_pi, state_new) = \ self.objective_func(params, state, hyperparams, rng, transition_batch, Adv) # flip sign to turn objective into loss loss = -objective # keep track of performance metrics metrics = { f'{self.__class__.__name__}/loss': loss, f'{self.__class__.__name__}/loss_bare': loss, f'{self.__class__.__name__}/kl_div_old': jnp.mean(jnp.exp(transition_batch.logP) * (transition_batch.logP - log_pi)), } # add regularization term if self.regularizer is not None: hparams = hyperparams['regularizer'] W = jnp.clip(transition_batch.W, 0.1, 10.) # clip imp. weights to reduce variance regularizer, regularizer_metrics = self.regularizer.batch_eval(params, hparams, state, rng, transition_batch) loss = loss + jnp.mean(W * regularizer) metrics[f'{self.__class__.__name__}/loss'] = loss metrics.update({f'{self.__class__.__name__}/{k}': v for k, v in regularizer_metrics.items()}) # also pass auxiliary data to avoid multiple forward passes return loss, (metrics, state_new) def grads_and_metrics_func(params, state, hyperparams, rng, transition_batch, Adv): grads_func = jax.grad(loss_func, has_aux=True) grads, (metrics, state_new) = \ grads_func(params, state, hyperparams, rng, transition_batch, Adv) # add some diagnostics of the gradients metrics.update(get_grads_diagnostics(grads, f'{self.__class__.__name__}/grads_')) return grads, state_new, metrics def apply_grads_func(opt, opt_state, params, grads): updates, new_opt_state = opt.update(grads, opt_state, params) new_params = optax.apply_updates(params, updates) return new_opt_state, new_params self._grad_and_metrics_func = jit(grads_and_metrics_func) self._apply_grads_func = jit(apply_grads_func, static_argnums=0) @property def pi(self): return self._pi @property def regularizer(self): return self._regularizer @property def optimizer(self): return self._optimizer @optimizer.setter def optimizer(self, new_optimizer): new_optimizer_state_structure = jax.tree_util.tree_structure( new_optimizer.init(self._f.params)) if new_optimizer_state_structure != jax.tree_util.tree_structure(self.optimizer_state): raise AttributeError("cannot set optimizer attr: mismatch in optimizer_state structure") self._optimizer = new_optimizer @property def optimizer_state(self): return self._optimizer_state @optimizer_state.setter def optimizer_state(self, new_optimizer_state): self._optimizer_state = new_optimizer_state @property def hyperparams(self): return hk.data_structures.to_immutable_dict({ 'regularizer': getattr(self.regularizer, 'hyperparams', {})}) def update(self, transition_batch, Adv): r""" Update the model parameters (weights) of the underlying function approximator. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray A batch of advantages :math:`\mathcal{A}(s,a)=q(s,a)-v(s)`. Returns ------- metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ grads, function_state, metrics = self.grads_and_metrics(transition_batch, Adv) if any(jnp.any(jnp.isnan(g)) for g in jax.tree_util.tree_leaves(grads)): raise RuntimeError(f"found nan's in grads: {grads}") self.apply_grads(grads, function_state) return metrics def apply_grads(self, grads, function_state): r""" Update the model parameters (weights) of the underlying function approximator given pre-computed gradients. This method is useful in situations in which computation of the gradients is deligated to a separate (remote) process. Parameters ---------- grads : pytree with ndarray leaves A batch of gradients, generated by the :attr:`grads` method. function_state : pytree The internal state of the forward-pass function. See :attr:`Policy.function_state <coax.Policy.function_state>` and :func:`haiku.transform_with_state` for more details. """ self._pi.function_state = function_state self.optimizer_state, self._pi.params = \ self._apply_grads_func(self.optimizer, self.optimizer_state, self._pi.params, grads) def grads_and_metrics(self, transition_batch, Adv): r""" Compute the gradients associated with a batch of transitions with corresponding advantages. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray A batch of advantages :math:`\mathcal{A}(s,a)=q(s,a)-v(s)`. Returns ------- grads : pytree with ndarray leaves A batch of gradients. function_state : pytree The internal state of the forward-pass function. See :attr:`Policy.function_state <coax.Policy.function_state>` and :func:`haiku.transform_with_state` for more details. metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ if self.REQUIRES_PROPENSITIES and jnp.all(transition_batch.logP == 0): warnings.warn( f"In order for {self.__class__.__name__} to work properly, transition_batch.logP " "should be non-zero. Please sample actions with their propensities: " "a, logp = pi(s, return_logp=True) and then add logp to your reward tracer, " "e.g. nstep_tracer.add(s, a, r, done, logp)") return self._grad_and_metrics_func( self._pi.params, self._pi.function_state, self.hyperparams, self._pi.rng, transition_batch, Adv)
7,993
35.009009
100
py
null
coax-main/coax/policy_objectives/_deterministic_pg.py
import warnings import jax.numpy as jnp import haiku as hk import chex from ..utils import check_preprocessors, is_qfunction, is_stochastic from ._base import PolicyObjective class DeterministicPG(PolicyObjective): r""" A deterministic policy-gradient objective, a.k.a. DDPG-style objective. See :doc:`spinup:algorithms/ddpg` and references therein for more details. .. math:: J(\theta; s,a)\ =\ q_\text{targ}(s, a_\theta(s)) Here :math:`a_\theta(s)` is the *mode* of the underlying conditional probability distribution :math:`\pi_\theta(.|s)`. See e.g. the :attr:`mode` method of :class:`coax.proba_dists.NormalDist`. In other words, we evaluate the policy according to the current estimate of its best-case performance. This objective has the property that it explicitly maximizes the q-value. The full policy loss is constructed as: .. math:: \text{loss}(\theta; s,a)\ =\ -J(\theta; s,a) - \beta_\text{ent}\,H[\pi_\theta] + \beta_\text{kl-div}\, KL[\pi_{\theta_\text{prior}}, \pi_\theta] N.B. in order to unclutter the notation we abbreviated :math:`\pi(.|s)` by :math:`\pi`. Parameters ---------- pi : Policy The parametrized policy :math:`\pi_\theta(a|s)`. q_targ : Q The target state-action value function :math:`q_\text{targ}(s,a)`. optimizer : optax optimizer, optional An optax-style optimizer. The default optimizer is :func:`optax.adam(1e-3) <optax.adam>`. regularizer : Regularizer, optional A policy regularizer, see :mod:`coax.regularizers`. """ REQUIRES_PROPENSITIES = False def __init__(self, pi, q_targ, optimizer=None, regularizer=None): if not is_qfunction(q_targ): raise TypeError(f"q must be a q-function, got: {type(q_targ)}") if q_targ.modeltype != 1: raise TypeError("q must be a type-1 q-function") super().__init__(pi=pi, optimizer=optimizer, regularizer=regularizer) self.q_targ = q_targ if not check_preprocessors( self.pi.action_space, self.q_targ.action_preprocessor, self.pi.proba_dist.preprocess_variate): warnings.warn( "it seems that q_targ.action_preprocessor does not match " "pi.proba_dist.preprocess_variate; please instantiate your q-function using " "q = coax.Q(..., action_preprocessor=pi.proba_dist.preprocess_variate) to ensure " "that the preprocessors match") @property def hyperparams(self): return hk.data_structures.to_immutable_dict({ 'regularizer': getattr(self.regularizer, 'hyperparams', {}), 'q': {'params': self.q_targ.params, 'function_state': self.q_targ.function_state}}) def objective_func(self, params, state, hyperparams, rng, transition_batch, Adv): rngs = hk.PRNGSequence(rng) # get distribution params from function approximator S = self.pi.observation_preprocessor(next(rngs), transition_batch.S) dist_params, state_new = self.pi.function(params, state, next(rngs), S, True) # compute objective: q(s, a_greedy) S = self.q_targ.observation_preprocessor(next(rngs), transition_batch.S) A = self.pi.proba_dist.mode(dist_params) log_pi = self.pi.proba_dist.log_proba(dist_params, A) params_q, state_q = hyperparams['q']['params'], hyperparams['q']['function_state'] if is_stochastic(self.q_targ): dist_params_q, _ = self.q_targ.function_type1(params_q, state_q, rng, S, A, True) Q = self.q_targ.proba_dist.mean(dist_params_q) Q = self.q_targ.proba_dist.postprocess_variate(next(rngs), Q, batch_mode=True) else: Q, _ = self.q_targ.function_type1(params_q, state_q, next(rngs), S, A, True) # clip importance weights to reduce variance W = jnp.clip(transition_batch.W, 0.1, 10.) # the objective chex.assert_equal_shape([W, Q]) chex.assert_rank([W, Q], 1) objective = W * Q return jnp.mean(objective), (dist_params, log_pi, state_new) def update(self, transition_batch, Adv=None): r""" Update the model parameters (weights) of the underlying function approximator. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray, ignored This input is ignored; it is included for consistency with other policy objectives. Returns ------- metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ return super().update(transition_batch, None) def grads_and_metrics(self, transition_batch, Adv=None): r""" Compute the gradients associated with a batch of transitions with corresponding advantages. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray, ignored This input is ignored; it is included for consistency with other policy objectives. Returns ------- grads : pytree with ndarray leaves A batch of gradients. function_state : pytree The internal state of the forward-pass function. See :attr:`Policy.function_state <coax.Policy.function_state>` and :func:`haiku.transform_with_state` for more details. metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ return super().grads_and_metrics(transition_batch, None)
5,813
32.606936
98
py
null
coax-main/coax/policy_objectives/_deterministic_pg_test.py
from copy import deepcopy import jax.numpy as jnp from optax import sgd from .._base.test_case import TestCase from .._core.policy import Policy from .._core.q import Q from ..utils import tree_ravel from ._deterministic_pg import DeterministicPG class TestDeterministicPG(TestCase): def test_update_discrete(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete print(transitions) pi = Policy(func, env) q_targ = Q(self.func_q_type1, env, action_preprocessor=pi.proba_dist.preprocess_variate) updater = DeterministicPG(pi, q_targ, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_boxspace(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace print(transitions) pi = Policy(func, env) q_targ = Q(self.func_q_type1, env, action_preprocessor=pi.proba_dist.preprocess_variate) updater = DeterministicPG(pi, q_targ, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params)
1,802
31.196429
96
py
null
coax-main/coax/policy_objectives/_ppo_clip.py
import jax.numpy as jnp import haiku as hk import chex from ._base import PolicyObjective class PPOClip(PolicyObjective): r""" PPO-clip policy objective. .. math:: J(\theta; s,a)\ =\ \min\Big( \rho_\theta\,\mathcal{A}(s,a)\,,\ \bar{\rho}_\theta\,\mathcal{A}(s,a)\Big) where :math:`\rho_\theta` and :math:`\bar{\rho}_\theta` are the bare and clipped probability ratios, respectively: .. math:: \rho_\theta\ =\ \frac{\pi_\theta(a|s)}{\pi_{\theta_\text{old}}(a|s)}\ , \qquad \bar{\rho}_\theta\ =\ \big[\rho_\theta\big]^{1+\epsilon}_{1-\epsilon} This objective has the property that it allows for slightly more off-policy updates than the vanilla policy gradient. Parameters ---------- pi : Policy The parametrized policy :math:`\pi_\theta(a|s)`. optimizer : optax optimizer, optional An optax-style optimizer. The default optimizer is :func:`optax.adam(1e-3) <optax.adam>`. regularizer : Regularizer, optional A policy regularizer, see :mod:`coax.regularizers`. epsilon : positive float, optional The clipping parameter :math:`\epsilon` that is used to defined the clipped importance weight :math:`\bar{\rho}`. """ REQUIRES_PROPENSITIES = True def __init__(self, pi, optimizer=None, regularizer=None, epsilon=0.2): super().__init__(pi=pi, optimizer=optimizer, regularizer=regularizer) self.epsilon = epsilon @property def hyperparams(self): return hk.data_structures.to_immutable_dict({ 'regularizer': getattr(self.regularizer, 'hyperparams', {}), 'epsilon': self.epsilon}) def objective_func(self, params, state, hyperparams, rng, transition_batch, Adv): rngs = hk.PRNGSequence(rng) # get distribution params from function approximator S = self.pi.observation_preprocessor(next(rngs), transition_batch.S) dist_params, state_new = self.pi.function(params, state, next(rngs), S, True) # compute probability ratios A = self.pi.proba_dist.preprocess_variate(next(rngs), transition_batch.A) log_pi = self.pi.proba_dist.log_proba(dist_params, A) ratio = jnp.exp(log_pi - transition_batch.logP) # π_new / π_old ratio_clip = jnp.clip(ratio, 1 - hyperparams['epsilon'], 1 + hyperparams['epsilon']) # clip importance weights to reduce variance W = jnp.clip(transition_batch.W, 0.1, 10.) # ppo-clip objective chex.assert_equal_shape([W, Adv, ratio, ratio_clip]) chex.assert_rank([W, Adv, ratio, ratio_clip], 1) objective = W * jnp.minimum(Adv * ratio, Adv * ratio_clip) # also pass auxiliary data to avoid multiple forward passes return jnp.mean(objective), (dist_params, log_pi, state_new)
2,898
31.573034
92
py
null
coax-main/coax/policy_objectives/_ppo_clip_test.py
from copy import deepcopy import jax.numpy as jnp from optax import sgd from .._base.test_case import TestCase from .._core.policy import Policy from ..utils import tree_ravel from ._ppo_clip import PPOClip class TestPPOClip(TestCase): def test_update_discrete(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete print(transitions) pi = Policy(func, env) updater = PPOClip(pi, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_box(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace print(transitions) pi = Policy(func, env) updater = PPOClip(pi, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params)
1,603
29.264151
80
py
null
coax-main/coax/policy_objectives/_soft_pg.py
import jax.numpy as jnp import haiku as hk import chex from ._base import PolicyObjective from ..utils import is_qfunction, is_stochastic class SoftPG(PolicyObjective): def __init__(self, pi, q_targ_list, optimizer=None, regularizer=None): super().__init__(pi, optimizer=optimizer, regularizer=regularizer) self._check_input_lists(q_targ_list) self.q_targ_list = q_targ_list @property def hyperparams(self): return hk.data_structures.to_immutable_dict({ 'regularizer': getattr(self.regularizer, 'hyperparams', {}), 'q': {'params': [q_targ.params for q_targ in self.q_targ_list], 'function_state': [q_targ.function_state for q_targ in self.q_targ_list]}}) def objective_func(self, params, state, hyperparams, rng, transition_batch, Adv): rngs = hk.PRNGSequence(rng) # get distribution params from function approximator S = self.pi.observation_preprocessor(next(rngs), transition_batch.S) dist_params, state_new = self.pi.function(params, state, next(rngs), S, True) A = self.pi.proba_dist.sample(dist_params, next(rngs)) log_pi = self.pi.proba_dist.log_proba(dist_params, A) Q_sa_list = [] qs = list(zip(self.q_targ_list, hyperparams['q'] ['params'], hyperparams['q']['function_state'])) for q_targ, params_q, state_q in qs: # compute objective: q(s, a) S = q_targ.observation_preprocessor(next(rngs), transition_batch.S) if is_stochastic(q_targ): dist_params_q, _ = q_targ.function_type1(params_q, state_q, rng, S, A, True) Q = q_targ.proba_dist.mean(dist_params_q) Q = q_targ.proba_dist.postprocess_variate(next(rngs), Q, batch_mode=True) else: Q, _ = q_targ.function_type1(params_q, state_q, next(rngs), S, A, True) Q_sa_list.append(Q) # take the min to mitigate over-estimation Q_sa_next_list = jnp.stack(Q_sa_list, axis=-1) assert Q_sa_next_list.ndim == 2, f"bad shape: {Q_sa_next_list.shape}" Q = jnp.min(Q_sa_next_list, axis=-1) assert Q.ndim == 1, f"bad shape: {Q.shape}" # clip importance weights to reduce variance W = jnp.clip(transition_batch.W, 0.1, 10.) # the objective chex.assert_equal_shape([W, Q]) chex.assert_rank([W, Q], 1) objective = W * Q return jnp.mean(objective), (dist_params, log_pi, state_new) def _check_input_lists(self, q_targ_list): # check input: q_targ_list if not isinstance(q_targ_list, (tuple, list)): raise TypeError(f"q_targ_list must be a list or a tuple, got: {type(q_targ_list)}") if not q_targ_list: raise ValueError("q_targ_list cannot be empty") for q_targ in q_targ_list: if not is_qfunction(q_targ): raise TypeError(f"all q_targ in q_targ_list must be a coax.Q, got: {type(q_targ)}") def update(self, transition_batch, Adv=None): r""" Update the model parameters (weights) of the underlying function approximator. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray, ignored This input is ignored; it is included for consistency with other policy objectives. Returns ------- metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ return super().update(transition_batch, None) def grads_and_metrics(self, transition_batch, Adv=None): r""" Compute the gradients associated with a batch of transitions with corresponding advantages. Parameters ---------- transition_batch : TransitionBatch A batch of transitions. Adv : ndarray, ignored This input is ignored; it is included for consistency with other policy objectives. Returns ------- grads : pytree with ndarray leaves A batch of gradients. function_state : pytree The internal state of the forward-pass function. See :attr:`Policy.function_state <coax.Policy.function_state>` and :func:`haiku.transform_with_state` for more details. metrics : dict of scalar ndarrays The structure of the metrics dict is ``{name: score}``. """ return super().grads_and_metrics(transition_batch, None)
4,604
34.423077
99
py
null
coax-main/coax/policy_objectives/_soft_pg_test.py
# ------------------------------------------------------------------------------------------------ # # MIT License # # # # Copyright (c) 2020, Microsoft Corporation # # # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # # and associated documentation files (the "Software"), to deal in the Software without # # restriction, including without limitation the rights to use, copy, modify, merge, publish, # # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # # Software is furnished to do so, subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included in all copies or # # substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # ------------------------------------------------------------------------------------------------ # from copy import deepcopy import jax.numpy as jnp from optax import sgd from .._base.test_case import TestCase from .._core.q import Q from .._core.policy import Policy from ..utils import tree_ravel from ._soft_pg import SoftPG class TestSoftPG(TestCase): def test_update_discrete(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete print(transitions) pi = Policy(func, env) q1_targ = Q(self.func_q_type1, env) q2_targ = Q(self.func_q_type1, env) updater = SoftPG(pi, [q1_targ, q2_targ], optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_boxspace(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace print(transitions) pi = Policy(func, env) q1_targ = Q(self.func_q_type1, env) q2_targ = Q(self.func_q_type1, env) updater = SoftPG(pi, [q1_targ, q2_targ], optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_bad_q_targ_list(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace print(transitions) pi = Policy(func, env) q1_targ = Q(self.func_q_type1, env) msg = f"q_targ_list must be a list or a tuple, got: {type(q1_targ)}" with self.assertRaisesRegex(TypeError, msg): SoftPG(pi, q1_targ, optimizer=sgd(1.0))
4,226
43.968085
100
py
null
coax-main/coax/policy_objectives/_vanilla_pg.py
import jax.numpy as jnp import haiku as hk import chex from ._base import PolicyObjective class VanillaPG(PolicyObjective): r""" A vanilla policy-gradient objective, a.k.a. REINFORCE-style objective. .. math:: J(\theta; s,a)\ =\ \mathcal{A}(s,a)\,\log\pi_\theta(a|s) This objective has the property that its gradient with respect to :math:`\theta` yields the REINFORCE-style policy gradient. Parameters ---------- pi : Policy The parametrized policy :math:`\pi_\theta(a|s)`. optimizer : optax optimizer, optional An optax-style optimizer. The default optimizer is :func:`optax.adam(1e-3) <optax.adam>`. regularizer : Regularizer, optional A policy regularizer, see :mod:`coax.regularizers`. """ REQUIRES_PROPENSITIES = False def objective_func(self, params, state, hyperparams, rng, transition_batch, Adv): rngs = hk.PRNGSequence(rng) # get distribution params from function approximator S = self.pi.observation_preprocessor(next(rngs), transition_batch.S) dist_params, state_new = self.pi.function(params, state, next(rngs), S, True) # compute REINFORCE-style objective A = self.pi.proba_dist.preprocess_variate(next(rngs), transition_batch.A) log_pi = self.pi.proba_dist.log_proba(dist_params, A) # clip importance weights to reduce variance W = jnp.clip(transition_batch.W, 0.1, 10.) # some consistency checks chex.assert_equal_shape([W, Adv, log_pi]) chex.assert_rank([W, Adv, log_pi], 1) objective = W * Adv * log_pi # also pass auxiliary data to avoid multiple forward passes return jnp.mean(objective), (dist_params, log_pi, state_new)
1,774
29.603448
85
py
null
coax-main/coax/policy_objectives/_vanilla_pg_test.py
from copy import deepcopy import jax.numpy as jnp from optax import sgd from .._base.test_case import TestCase from .._core.policy import Policy from ..utils import tree_ravel from ..regularizers import EntropyRegularizer, KLDivRegularizer from ._vanilla_pg import VanillaPG class TestVanillaPG(TestCase): def test_update_discrete(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_box(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_discrete_entropyreg(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete reg = EntropyRegularizer print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, regularizer=reg(pi), optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_box_entropyreg(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace reg = EntropyRegularizer print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, regularizer=reg(pi), optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_discrete_kldivreg(self): env = self.env_discrete func = self.func_pi_discrete transitions = self.transitions_discrete reg = KLDivRegularizer print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, regularizer=reg(pi), optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params) def test_update_box_kldivreg(self): env = self.env_boxspace func = self.func_pi_boxspace transitions = self.transitions_boxspace reg = KLDivRegularizer print(transitions) pi = Policy(func, env) updater = VanillaPG(pi, regularizer=reg(pi), optimizer=sgd(1.0)) params = deepcopy(pi.params) function_state = deepcopy(pi.function_state) grads, _, _ = updater.grads_and_metrics(transitions, Adv=transitions.Rn) self.assertGreater(jnp.max(jnp.abs(tree_ravel(grads))), 0.) updater.update(transitions, Adv=transitions.Rn) self.assertPytreeNotEqual(function_state, pi.function_state) self.assertPytreeNotEqual(params, pi.params)
4,663
32.797101
80
py
null
coax-main/coax/proba_dists/__init__.py
r""" .. autosummary:: :nosignatures: coax.proba_dists.ProbaDist coax.proba_dists.CategoricalDist coax.proba_dists.NormalDist coax.proba_dists.DiscretizedIntervalDist coax.proba_dists.EmpiricalQuantileDist coax.proba_dists.SquashedNormalDist ----- Probability Distributions ========================= This is a collection of **differentiable** probability distributions used throughout the package. Object Reference ---------------- .. autoclass:: coax.proba_dists.ProbaDist .. autoclass:: coax.proba_dists.CategoricalDist .. autoclass:: coax.proba_dists.NormalDist .. autoclass:: coax.proba_dists.DiscretizedIntervalDist .. autoclass:: coax.proba_dists.EmpiricalQuantileDist .. autoclass:: coax.proba_dists.SquashedNormalDist """ from ._composite import ProbaDist from ._categorical import CategoricalDist from ._normal import NormalDist from ._discretized_interval import DiscretizedIntervalDist from ._empirical_quantile import EmpiricalQuantileDist from ._squashed_normal import SquashedNormalDist __all__ = ( 'ProbaDist', 'CategoricalDist', 'NormalDist', 'DiscretizedIntervalDist', 'EmpiricalQuantileDist', 'SquashedNormalDist', )
1,198
23.469388
97
py
null
coax-main/coax/proba_dists/_base.py
from abc import ABC, abstractmethod import gymnasium import jax from ..utils import batch_to_single class BaseProbaDist(ABC): r""" Abstract base class for probability distributions. Check out :class:`coax.proba_dists.CategoricalDist` for a specific example. """ __slots__ = ( '_space', '_sample_func', '_mean_func', '_mode_func', '_log_proba_func', '_entropy_func', '_cross_entropy_func', '_kl_divergence_func', '_affine_transform_func', '_default_priors_func', ) def __init__(self, space): if not isinstance(space, gymnasium.Space): raise TypeError("space must be derived from gymnasium.Space") self._space = space @property def space(self): r""" The gymnasium-style space that specifies the domain of the distribution. """ return self._space @property def hyperparams(self): r""" The distribution hyperparameters. """ return {} @property def sample(self): r""" JIT-compiled function that generates differentiable variates. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. rng : PRNGKey A key for seeding the pseudo-random number generator. Returns ------- X : ndarray A batch of differentiable variates. """ return self._sample_func @property def mean(self): r""" JIT-compiled functions that generates differentiable means of the distribution. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- X : ndarray A batch of differentiable variates. """ return self._mean_func @property def mode(self): r""" JIT-compiled functions that generates differentiable modes of the distribution. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- X : ndarray A batch of differentiable variates. """ return self._mode_func @property def log_proba(self): r""" JIT-compiled function that evaluates log-probabilities. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. X : ndarray A batch of variates, e.g. a batch of actions :math:`a` collected from experience. Returns ------- logP : ndarray of floats A batch of log-probabilities associated with the provided variates. """ return self._log_proba_func @property def entropy(self): r""" JIT-compiled function that computes the entropy of the distribution. .. math:: H\ =\ -\mathbb{E}_p \log p Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- H : ndarray of floats A batch of entropy values. """ return self._entropy_func @property def cross_entropy(self): r""" JIT-compiled function that computes the cross-entropy of a distribution :math:`q` relative to another categorical distribution :math:`p`: .. math:: \text{CE}[p,q]\ =\ -\mathbb{E}_p \log q Parameters ---------- dist_params_p : pytree with ndarray leaves The distribution parameters of the *base* distribution :math:`p`. dist_params_q : pytree with ndarray leaves The distribution parameters of the *auxiliary* distribution :math:`q`. """ return self._cross_entropy_func @property def kl_divergence(self): r""" JIT-compiled function that computes the Kullback-Leibler divergence of a categorical distribution :math:`q` relative to another distribution :math:`p`: .. math:: \text{KL}[p,q]\ = -\mathbb{E}_p \left(\log q -\log p\right) Parameters ---------- dist_params_p : pytree with ndarray leaves The distribution parameters of the *base* distribution :math:`p`. dist_params_q : pytree with ndarray leaves The distribution parameters of the *auxiliary* distribution :math:`q`. """ return self._kl_divergence_func @property def affine_transform(self): r""" Transform the distribution :math:`\mathcal{D}\to\mathcal{D}'` in such a way that its associated variables :math:`X\sim\mathcal{D}` and :math:`X'\sim\mathcal{D}'` are related via an affine transformation: .. math:: X' = X\times\text{scale} + \text{shift} Parameters ---------- dist_params : pytree with ndarray leaves The distribution parameters of the original distribution :math:`\mathcal{D}`. scale : float or ndarray The multiplicative factor of the affine transformation. shift : float or ndarray The additive shift of the affine transformation. value_transform : ValueTransform, optional The transform to apply to the values before the affine transform, i.e. .. math:: X' = f\bigl(f^{-1}(X)\times\text{scale} + \text{shift}\bigr) Returns ------- dist_params : pytree with ndarray leaves The distribution parameters of the transformed distribution :math:`\mathcal{D}'`. """ return self._affine_transform_func @property def dist_params_structure(self): r""" The tree structure of the distribution parameters. """ return jax.tree_util.tree_structure(self.default_priors) @property @abstractmethod def default_priors(self): r""" The default distribution parameters. """ pass def postprocess_variate(self, rng, X, index=0, batch_mode=False): r""" The post-processor specific to variates drawn from this ditribution. This method provides the interface between differentiable, batched variates, i.e. outputs of :func:`sample` and :func:`mode` and the provided gymnasium space. Parameters ---------- rng : PRNGKey A key for seeding the pseudo-random number generator. X : raw variates A batch of **raw** clean variates, i.e. same format as the outputs of :func:`sample` and :func:`mode`. index : int, optional The index to pick out from the batch. Note that this only applies if :code:`batch_mode=False`. batch_mode : bool, optional Whether to return a batch or a single instance. Returns ------- x or X : clean variate A single clean variate or a batch thereof (if ``batch_mode=True``). A variate is called **clean** if it is an instance of the gymnasium-style :attr:`space`, i.e. it satisfies :code:`x in self.space`. """ return X if batch_mode else batch_to_single(X) def preprocess_variate(self, rng, X): r""" The pre-processor to ensure that an instance of the :attr:`space` is processed into the same structure as variates drawn from this ditribution, i.e. outputs of :func:`sample` and :func:`mode`. Parameters ---------- rng : PRNGKey A key for seeding the pseudo-random number generator. X : clean variates A batch of clean variates, i.e. instances of the gymnasium-style :attr:`space`. Returns ------- X : raw variates A batch of **raw** clean variates, i.e. same format as the outputs of :func:`sample` and :func:`mode`. """ return X
8,223
23.99696
100
py
null
coax-main/coax/proba_dists/_categorical.py
import jax import jax.numpy as jnp from gymnasium.spaces import Discrete from ..utils import argmax, jit from ._base import BaseProbaDist __all__ = ( 'CategoricalDist', ) class CategoricalDist(BaseProbaDist): r""" A differentiable categorical distribution. The input ``dist_params`` to each of the functions is expected to be of the form: .. code:: python dist_params = {'logits': array([...])} which represent the (conditional) distribution parameters. The ``logits``, denoted :math:`z\in\mathbb{R}^n`, are related to the categorical distribution parameters :math:`p\in\Delta^n` via a softmax: .. math:: p_k\ =\ \text{softmax}_k(z)\ =\ \frac{\text{e}^{z_k}}{\sum_j\text{e}^{z_j}} Parameters ---------- space : gymnasium.spaces.Discrete The gymnasium-style space that specifies the domain of the distribution. gumbel_softmax_tau : positive float, optional The parameter :math:`\tau` specifies the sharpness of the Gumbel-softmax sampling (see :func:`sample` method below). A good value for :math:`\tau` balances the trade-off between getting proper deterministic variates (i.e. one-hot vectors) versus getting smooth differentiable variates. """ __slots__ = (*BaseProbaDist.__slots__, '_gumbel_softmax_tau') def __init__(self, space, gumbel_softmax_tau=0.2): if not isinstance(space, Discrete): raise TypeError(f"{self.__class__.__name__} can only be defined over Discrete spaces") super().__init__(space) self._gumbel_softmax_tau = gumbel_softmax_tau def check_shape(x, name): if not isinstance(x, jnp.ndarray): raise TypeError(f"expected an jax.numpy.ndarray, got: {type(x)}") if not (x.ndim == 2 and x.shape[1] == space.n): raise ValueError(f"expected {name}.shape: (?, {space.n}), got: {x.shape}") return x def sample(dist_params, rng): logits = check_shape(dist_params['logits'], 'logits') logp = jax.nn.log_softmax(logits) u = jax.random.uniform(rng, logp.shape) g = -jnp.log(-jnp.log(u)) # g ~ Gumbel(0,1) return jax.nn.softmax((g + logp) / self.gumbel_softmax_tau) def mean(dist_params): logits = check_shape(dist_params['logits'], 'logits') return jax.nn.softmax(logits) def mode(dist_params): logits = check_shape(dist_params['logits'], 'logits') logp = jax.nn.log_softmax(logits) return jax.nn.softmax(logp / self.gumbel_softmax_tau) def log_proba(dist_params, X): X = check_shape(X, 'X') logits = check_shape(dist_params['logits'], 'logits') logp = jax.nn.log_softmax(logits) return jnp.einsum('ij,ij->i', X, logp) def entropy(dist_params): logits = check_shape(dist_params['logits'], 'logits') logp = jax.nn.log_softmax(logits) return jnp.einsum('ij,ij->i', jnp.exp(logp), -logp) def cross_entropy(dist_params_p, dist_params_q): logits_p = check_shape(dist_params_p['logits'], 'logits_p') logits_q = check_shape(dist_params_q['logits'], 'logits_q') p = jax.nn.softmax(logits_p) logq = jax.nn.log_softmax(logits_q) return jnp.einsum('ij,ij->i', p, -logq) def kl_divergence(dist_params_p, dist_params_q): logits_p = check_shape(dist_params_p['logits'], 'logits_p') logits_q = check_shape(dist_params_q['logits'], 'logits_q') logp = jax.nn.log_softmax(logits_p) logq = jax.nn.log_softmax(logits_q) return jnp.einsum('ij,ij->i', jnp.exp(logp), logp - logq) def affine_transform_func(dist_params, scale, shift, value_transform=None): raise NotImplementedError("affine_transform is ill-defined on categorical variables") self._sample_func = jit(sample) self._mean_func = jit(mean) self._mode_func = jit(mode) self._log_proba_func = jit(log_proba) self._entropy_func = jit(entropy) self._cross_entropy_func = jit(cross_entropy) self._kl_divergence_func = jit(kl_divergence) self._affine_transform_func = affine_transform_func @property def hyperparams(self): return {'gumbel_softmax_tau': self.gumbel_softmax_tau} @property def gumbel_softmax_tau(self): return self._gumbel_softmax_tau @property def default_priors(self): return {'logits': jnp.zeros((1, self.space.n))} def preprocess_variate(self, rng, X): X = jnp.asarray(X) assert X.ndim <= 1, f"unexpected X.shape: {X.shape}" assert jnp.issubdtype(X.dtype, jnp.integer), f"expected an integer dtype, got {X.dtype}" return jax.nn.one_hot(X, self.space.n).reshape(-1, self.space.n) def postprocess_variate(self, rng, X, index=0, batch_mode=False): assert X.ndim == 2 assert X.shape[1] == self.space.n X = argmax(rng, X, axis=1) return X if batch_mode else int(X[index]) @property def sample(self): r""" JIT-compiled function that generates differentiable variates using Gumbel-softmax sampling. :math:`x\sim\text{Cat}(p)` is implemented as .. math:: u_k\ &\sim\ \text{Unif}(0, 1) \\ g_k\ &=\ -\log(-\log(u_k)) \\ x_k\ &=\ \text{softmax}_k\left( \frac{g_k + \log p_k}{\tau} \right) Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. rng : PRNGKey A key for seeding the pseudo-random number generator. Returns ------- X : ndarray A batch of variates :math:`x\sim\text{Cat}(p)`. In order to ensure differentiability of the variates this is not an integer, but instead an *almost*-one-hot encoded version thereof. For example, instead of sampling :math:`x=2` from a 4-class categorical distribution, Gumbel-softmax will return a vector like :math:`x=[0.05, 0.02, 0.86, 0.07]`. The latter representation can be viewed as an *almost*-one-hot encoded version of the former. """ return self._sample_func @property def mean(self): r""" JIT-compiled functions that generates differentiable means of the distribution. Strictly speaking, the mean of a categorical variable is not well defined. We opt for returning the raw probabilities: :math:`\text{mean}_k=p_k`. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- X : ndarray A batch of would-be variates :math:`x\sim\text{Cat}(p)`. In contrast to the output of other methods, these aren't true variates because they are not *almost*-one-hot encoded. """ return self._mean_func @property def mode(self): r""" JIT-compiled functions that generates differentiable modes of the distribution, for which we use a similar trick as in Gumbel-softmax sampling: .. math:: \text{mode}_k\ =\ \text{softmax}_k\left( \frac{\log p_k}{\tau} \right) Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- X : ndarray A batch of variates :math:`x\sim\text{Cat}(p)`. In order to ensure differentiability of the variates this is not an integer, but instead an *almost*-one-hot encoded version thereof. For example, instead of sampling :math:`x=2` from a 4-class categorical distribution, Gumbel-softmax will return a vector like :math:`x=(0.05, 0.02, 0.86, 0.07)`. The latter representation can be viewed as an *almost*-one-hot encoded version of the former. """ return self._mode_func @property def log_proba(self): r""" JIT-compiled function that evaluates log-probabilities. Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. X : ndarray A batch of variates, e.g. a batch of actions :math:`a` collected from experience. Returns ------- logP : ndarray of floats A batch of log-probabilities associated with the provided variates. """ return self._log_proba_func @property def entropy(self): r""" JIT-compiled function that computes the entropy of the distribution. .. math:: H\ =\ -\sum_k p_k \log p_k Parameters ---------- dist_params : pytree with ndarray leaves A batch of distribution parameters. Returns ------- H : ndarray of floats A batch of entropy values. """ return self._entropy_func @property def cross_entropy(self): r""" JIT-compiled function that computes the cross-entropy of a categorical distribution :math:`q` relative to another categorical distribution :math:`p`: .. math:: \text{CE}[p,q]\ =\ -\sum_k p_k \log q_k Parameters ---------- dist_params_p : pytree with ndarray leaves The distribution parameters of the *base* distribution :math:`p`. dist_params_q : pytree with ndarray leaves The distribution parameters of the *auxiliary* distribution :math:`q`. """ return self._cross_entropy_func @property def kl_divergence(self): r""" JIT-compiled function that computes the Kullback-Leibler divergence of a categorical distribution :math:`q` relative to another categorical distribution :math:`p`: .. math:: \text{KL}[p,q]\ =\ -\sum_k p_k \left(\log q_k -\log p_k\right) Parameters ---------- dist_params_p : pytree with ndarray leaves The distribution parameters of the *base* distribution :math:`p`. dist_params_q : pytree with ndarray leaves The distribution parameters of the *auxiliary* distribution :math:`q`. """ return self._kl_divergence_func
10,618
30.698507
100
py
null
coax-main/coax/proba_dists/_composite.py
from enum import Enum import gymnasium import numpy as onp import haiku as hk import jax from ..utils import jit from ._base import BaseProbaDist from ._categorical import CategoricalDist from ._normal import NormalDist __all__ = ( 'ProbaDist', ) class StructureType(Enum): LEAF = 0 LIST = 1 DICT = 2 class ProbaDist(BaseProbaDist): r""" A composite probability distribution. This consists of a nested structure, whose leaves are either :class:`coax.proba_dists.CategoricalDist` or :class:`coax.proba_dists.NormalDist` instances. Parameters ---------- space : gymnasium.Space The gymnasium-style space that specifies the domain of the distribution. This may be any space included in the :mod:`gymnasium.spaces` module. """ __slots__ = BaseProbaDist.__slots__ + ('_structure', '_structure_type') def __init__(self, space): super().__init__(space) if isinstance(self.space, gymnasium.spaces.Discrete): self._structure_type = StructureType.LEAF self._structure = CategoricalDist(space) elif isinstance(self.space, gymnasium.spaces.Box): self._structure_type = StructureType.LEAF self._structure = NormalDist(space) elif isinstance(self.space, gymnasium.spaces.MultiDiscrete): self._structure_type = StructureType.LIST self._structure = [self.__class__(gymnasium.spaces.Discrete(n)) for n in space.nvec] elif isinstance(self.space, gymnasium.spaces.MultiBinary): self._structure_type = StructureType.LIST self._structure = [self.__class__(gymnasium.spaces.Discrete(2)) for _ in range(space.n)] elif isinstance(self.space, gymnasium.spaces.Tuple): self._structure_type = StructureType.LIST self._structure = [self.__class__(sp) for sp in space.spaces] elif isinstance(self.space, gymnasium.spaces.Dict): self._structure_type = StructureType.DICT self._structure = {k: self.__class__(sp) for k, sp in space.spaces.items()} else: raise TypeError(f"unsupported space: {space.__class__.__name__}") def sample(dist_params, rng): if self._structure_type == StructureType.LEAF: return self._structure.sample(dist_params, rng) rngs = hk.PRNGSequence(rng) if self._structure_type == StructureType.LIST: return [ dist.sample(dist_params[i], next(rngs)) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.DICT: return { k: dist.sample(dist_params[k], next(rngs)) for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") def mean(dist_params): if self._structure_type == StructureType.LEAF: return self._structure.mean(dist_params) if self._structure_type == StructureType.LIST: return [ dist.mean(dist_params[i]) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.DICT: return { k: dist.mean(dist_params[k]) for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") def mode(dist_params): if self._structure_type == StructureType.LEAF: return self._structure.mode(dist_params) if self._structure_type == StructureType.LIST: return [ dist.mode(dist_params[i]) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.DICT: return { k: dist.mode(dist_params[k]) for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") def log_proba(dist_params, X): if self._structure_type == StructureType.LEAF: return self._structure.log_proba(dist_params, X) if self._structure_type == StructureType.LIST: return sum( dist.log_proba(dist_params[i], X[i]) for i, dist in enumerate(self._structure)) if self._structure_type == StructureType.DICT: return sum( dist.log_proba(dist_params[k], X[k]) for k, dist in self._structure.items()) def entropy(dist_params): if self._structure_type == StructureType.LEAF: return self._structure.entropy(dist_params) if self._structure_type == StructureType.LIST: return sum( dist.entropy(dist_params[i]) for i, dist in enumerate(self._structure)) if self._structure_type == StructureType.DICT: return sum( dist.entropy(dist_params[k]) for k, dist in self._structure.items()) raise AssertionError(f"bad structure_type: {self._structure_type}") def cross_entropy(dist_params_p, dist_params_q): if self._structure_type == StructureType.LEAF: return self._structure.cross_entropy(dist_params_p, dist_params_q) if self._structure_type == StructureType.LIST: return sum( dist.cross_entropy(dist_params_p[i], dist_params_q[i]) for i, dist in enumerate(self._structure)) if self._structure_type == StructureType.DICT: return sum( dist.cross_entropy(dist_params_p[k], dist_params_q[k]) for k, dist in self._structure.items()) raise AssertionError(f"bad structure_type: {self._structure_type}") def kl_divergence(dist_params_p, dist_params_q): if self._structure_type == StructureType.LEAF: return self._structure.kl_divergence(dist_params_p, dist_params_q) if self._structure_type == StructureType.LIST: return sum( dist.kl_divergence(dist_params_p[i], dist_params_q[i]) for i, dist in enumerate(self._structure)) if self._structure_type == StructureType.DICT: return sum( dist.kl_divergence(dist_params_p[k], dist_params_q[k]) for k, dist in self._structure.items()) raise AssertionError(f"bad structure_type: {self._structure_type}") def affine_transform(dist_params, scale, shift, value_transform=None): if value_transform is None: value_transform = jax.tree_map(lambda _: None, self._structure) if self._structure_type == StructureType.LEAF: return self._structure.affine_transform(dist_params, scale, shift, value_transform) if self._structure_type == StructureType.LIST: assert len(dist_params) == len(scale) == len(shift) == len(self._structure) assert len(value_transform) == len(self._structure) return [ dist.affine_transform(dist_params[i], scale[i], shift[i], value_transform[i]) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.DICT: assert set(dist_params) == set(scale) == set(shift) == set(self._structure) assert set(value_transform) == set(self._structure) return { k: dist.affine_transform(dist_params[k], scale[k], shift[k], value_transform[k]) for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") self._sample_func = jit(sample) self._mean_func = jit(mean) self._mode_func = jit(mode) self._log_proba_func = jit(log_proba) self._entropy_func = jit(entropy) self._cross_entropy_func = jit(cross_entropy) self._kl_divergence_func = jit(kl_divergence) self._affine_transform_func = jit(affine_transform) @property def hyperparams(self): if self._structure_type == StructureType.LEAF: return self._structure.hyperparams if self._structure_type == StructureType.LIST: return tuple(dist.hyperparams for dist in self._structure) if self._structure_type == StructureType.DICT: return {k: dist.hyperparams for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") @property def default_priors(self): if self._structure_type == StructureType.LEAF: return self._structure.default_priors if self._structure_type == StructureType.LIST: return tuple(dist.default_priors for dist in self._structure) if self._structure_type == StructureType.DICT: return {k: dist.default_priors for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}") def postprocess_variate(self, rng, X, index=0, batch_mode=False): rngs = hk.PRNGSequence(rng) if self._structure_type == StructureType.LEAF: return self._structure.postprocess_variate( next(rngs), X, index=index, batch_mode=batch_mode) if isinstance(self.space, (gymnasium.spaces.MultiDiscrete, gymnasium.spaces.MultiBinary)): assert self._structure_type == StructureType.LIST return onp.stack([ dist.postprocess_variate(next(rngs), X[i], index=index, batch_mode=batch_mode) for i, dist in enumerate(self._structure)], axis=-1) if isinstance(self.space, gymnasium.spaces.Tuple): assert self._structure_type == StructureType.LIST return tuple( dist.postprocess_variate(next(rngs), X[i], index=index, batch_mode=batch_mode) for i, dist in enumerate(self._structure)) if isinstance(self.space, gymnasium.spaces.Dict): assert self._structure_type == StructureType.DICT return { k: dist.postprocess_variate(next(rngs), X[k], index=index, batch_mode=batch_mode) for k, dist in self._structure.items()} raise AssertionError( f"postprocess_variate not implemented for space: {self.space.__class__.__name__}; " "please send us a bug report / feature request") def preprocess_variate(self, rng, X): rngs = hk.PRNGSequence(rng) if self._structure_type == StructureType.LEAF: return self._structure.preprocess_variate(next(rngs), X) if isinstance(self.space, (gymnasium.spaces.MultiDiscrete, gymnasium.spaces.MultiBinary)): assert self._structure_type == StructureType.LIST return [ dist.preprocess_variate(next(rngs), X[..., i]) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.LIST: return [ dist.preprocess_variate(next(rngs), X[i]) for i, dist in enumerate(self._structure)] if self._structure_type == StructureType.DICT: return { k: dist.preprocess_variate(next(rngs), X[k]) for k, dist in self._structure.items()} raise AssertionError(f"bad structure_type: {self._structure_type}")
11,802
40.125436
100
py
null
coax-main/coax/proba_dists/_composite_test.py
import gymnasium import jax import jax.numpy as jnp import haiku as hk from .._base.test_case import TestCase from ._normal import NormalDist from ._categorical import CategoricalDist from ._composite import ProbaDist, StructureType discrete = gymnasium.spaces.Discrete(7) box = gymnasium.spaces.Box(low=0, high=1, shape=(3, 5)) multidiscrete = gymnasium.spaces.MultiDiscrete([11, 13, 17]) multibinary = gymnasium.spaces.MultiBinary(17) tuple_flat = gymnasium.spaces.Tuple((discrete, box)) dict_flat = gymnasium.spaces.Dict({'d': discrete, 'b': box}) tuple_nested = gymnasium.spaces.Tuple((discrete, box, multidiscrete, tuple_flat, dict_flat)) dict_nested = gymnasium.spaces.Dict( {'d': discrete, 'b': box, 'm': multidiscrete, 't': tuple_flat, 'n': dict_flat}) class TestProbaDist(TestCase): decimal = 5 def setUp(self): self.rngs = hk.PRNGSequence(13) def tearDown(self): del self.rngs def test_discrete(self): dist = ProbaDist(discrete) self.assertEqual(dist._structure_type, StructureType.LEAF) self.assertIsInstance(dist._structure, CategoricalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertArrayShape(sample, (1, discrete.n)) self.assertAlmostEqual(sample.sum(), 1) mode = dist.mode(dist.default_priors) self.assertArrayShape(mode, (1, discrete.n)) self.assertAlmostEqual(mode.sum(), 1) def test_box(self): dist = ProbaDist(box) self.assertEqual(dist._structure_type, StructureType.LEAF) self.assertIsInstance(dist._structure, NormalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertArrayShape(sample, (1, *box.shape)) mode = dist.mode(dist.default_priors) self.assertArrayShape(mode, (1, *box.shape)) def test_multidiscrete(self): dist = ProbaDist(multidiscrete) self.assertEqual(dist._structure_type, StructureType.LIST) sample = dist.sample(dist.default_priors, next(self.rngs)) mode = dist.mode(dist.default_priors) for i, subdist in enumerate(dist._structure): self.assertEqual(subdist._structure_type, StructureType.LEAF) self.assertIsInstance(subdist._structure, CategoricalDist) self.assertEqual(subdist._structure.space.n, multidiscrete.nvec[i]) self.assertArrayShape(sample[i], (1, multidiscrete.nvec[i])) self.assertAlmostEqual(sample[i].sum(), 1) self.assertArrayShape(mode[i], (1, multidiscrete.nvec[i])) self.assertAlmostEqual(mode[i].sum(), 1) def test_multibinary(self): dist = ProbaDist(multibinary) self.assertEqual(dist._structure_type, StructureType.LIST) sample = dist.sample(dist.default_priors, next(self.rngs)) for i, subdist in enumerate(dist._structure): self.assertEqual(subdist._structure_type, StructureType.LEAF) self.assertIsInstance(subdist._structure, CategoricalDist) self.assertEqual(subdist._structure.space.n, 2) self.assertArrayShape(sample[i], (1, 2)) self.assertAlmostEqual(sample[i].sum(), 1) def test_tuple_flat(self): dist = ProbaDist(tuple_flat) self.assertEqual(dist._structure_type, StructureType.LIST) for subdist in dist._structure: self.assertEqual(subdist._structure_type, StructureType.LEAF) self.assertIsInstance(dist._structure[0]._structure, CategoricalDist) self.assertIsInstance(dist._structure[1]._structure, NormalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertArrayShape(sample[0], (1, discrete.n)) self.assertAlmostEqual(sample[0].sum(), 1) self.assertArrayShape(sample[1], (1, *box.shape)) mode = dist.mode(dist.default_priors) self.assertArrayShape(mode[0], (1, discrete.n)) self.assertAlmostEqual(mode[0].sum(), 1) self.assertArrayShape(mode[1], (1, *box.shape)) def test_dict_flat(self): dist = ProbaDist(dict_flat) self.assertEqual(dist._structure_type, StructureType.DICT) for subdist in dist._structure.values(): self.assertEqual(subdist._structure_type, StructureType.LEAF) self.assertIsInstance(dist._structure['d']._structure, CategoricalDist) self.assertIsInstance(dist._structure['b']._structure, NormalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertArrayShape(sample['d'], (1, discrete.n)) self.assertAlmostEqual(sample['d'].sum(), 1) self.assertArrayShape(sample['b'], (1, *box.shape)) mode = dist.mode(dist.default_priors) self.assertArrayShape(mode['d'], (1, discrete.n)) self.assertAlmostEqual(mode['d'].sum(), 1) self.assertArrayShape(mode['b'], (1, *box.shape)) def test_tuple_nested(self): dist = ProbaDist(tuple_nested) self.assertEqual(len(dist._structure), 5) self.assertEqual(dist._structure_type, StructureType.LIST) self.assertEqual(dist._structure[2]._structure_type, StructureType.LIST) self.assertIsInstance(dist._structure[2]._structure, list) self.assertIsInstance(dist._structure[2]._structure[1]._structure, CategoricalDist) self.assertEqual(dist._structure[3]._structure_type, StructureType.LIST) self.assertIsInstance(dist._structure[3]._structure, list) self.assertIsInstance(dist._structure[3]._structure[1]._structure, NormalDist) self.assertEqual(dist._structure[4]._structure_type, StructureType.DICT) self.assertIsInstance(dist._structure[4]._structure, dict) self.assertIsInstance(dist._structure[4]._structure['b']._structure, NormalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertEqual(len(sample), len(dist._structure)) self.assertArrayShape(sample[3][0], (1, discrete.n)) self.assertAlmostEqual(sample[3][0].sum(), 1) self.assertArrayShape(sample[3][1], (1, *box.shape)) self.assertArrayShape(sample[4]['d'], (1, discrete.n)) self.assertAlmostEqual(sample[4]['d'].sum(), 1) self.assertArrayShape(sample[4]['b'], (1, *box.shape)) mode = dist.mode(dist.default_priors) self.assertEqual(len(mode), len(dist._structure)) self.assertArrayShape(mode[3][0], (1, discrete.n)) self.assertAlmostEqual(mode[3][0].sum(), 1) self.assertArrayShape(mode[3][1], (1, *box.shape)) self.assertArrayShape(mode[4]['d'], (1, discrete.n)) self.assertAlmostEqual(mode[4]['d'].sum(), 1) self.assertArrayShape(mode[4]['b'], (1, *box.shape)) def test_dict_nested(self): dist = ProbaDist(dict_nested) self.assertEqual(len(dist._structure), 5) self.assertEqual(dist._structure_type, StructureType.DICT) self.assertEqual(dist._structure['m']._structure_type, StructureType.LIST) self.assertIsInstance(dist._structure['m']._structure, list) self.assertIsInstance(dist._structure['m']._structure[1]._structure, CategoricalDist) self.assertEqual(dist._structure['t']._structure_type, StructureType.LIST) self.assertIsInstance(dist._structure['t']._structure, list) self.assertIsInstance(dist._structure['t']._structure[1]._structure, NormalDist) self.assertEqual(dist._structure['n']._structure_type, StructureType.DICT) self.assertIsInstance(dist._structure['n']._structure, dict) self.assertIsInstance(dist._structure['n']._structure['b']._structure, NormalDist) sample = dist.sample(dist.default_priors, next(self.rngs)) self.assertEqual(sample.keys(), dist._structure.keys()) self.assertArrayShape(sample['t'][0], (1, discrete.n)) self.assertAlmostEqual(sample['t'][0].sum(), 1) self.assertArrayShape(sample['t'][1], (1, *box.shape)) self.assertArrayShape(sample['n']['d'], (1, discrete.n)) self.assertAlmostEqual(sample['n']['d'].sum(), 1) self.assertArrayShape(sample['n']['b'], (1, *box.shape)) mode = dist.mode(dist.default_priors) self.assertEqual(mode.keys(), dist._structure.keys()) self.assertArrayShape(mode['t'][0], (1, discrete.n)) self.assertAlmostEqual(mode['t'][0].sum(), 1) self.assertArrayShape(mode['t'][1], (1, *box.shape)) self.assertArrayShape(mode['n']['d'], (1, discrete.n)) self.assertAlmostEqual(mode['n']['d'].sum(), 1) self.assertArrayShape(mode['n']['b'], (1, *box.shape)) def test_aggregated_quantities(self): space = gymnasium.spaces.Dict({ 'foo': gymnasium.spaces.Box(low=0, high=1, shape=(2, 7)), 'bar': gymnasium.spaces.MultiDiscrete([3, 5]), }) dist = ProbaDist(space) params_p = { 'foo': { 'mu': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), 'logvar': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), }, 'bar': [ {'logits': jax.random.normal(next(self.rngs), shape=(11, 3))}, {'logits': jax.random.normal(next(self.rngs), shape=(11, 5))}, ], } params_q = { 'foo': { 'mu': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), 'logvar': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), }, 'bar': [ {'logits': jax.random.normal(next(self.rngs), shape=(11, 3))}, {'logits': jax.random.normal(next(self.rngs), shape=(11, 5))}, ], } sample = dist.sample(params_p, next(self.rngs)) log_proba = dist.log_proba(params_p, sample) self.assertArrayShape(log_proba, (11,)) self.assertTrue(jnp.all(log_proba < 0)) entropy = dist.entropy(params_p) self.assertArrayShape(entropy, (11,)) cross_entropy = dist.cross_entropy(params_p, params_q) self.assertArrayShape(cross_entropy, (11,)) self.assertTrue(jnp.all(cross_entropy > entropy)) kl_divergence = dist.kl_divergence(params_p, params_q) self.assertArrayShape(kl_divergence, (11,)) self.assertTrue(jnp.all(kl_divergence > 0)) kl_div_from_ce = dist.cross_entropy(params_p, params_q) - dist.entropy(params_p) self.assertArrayAlmostEqual(kl_divergence, kl_div_from_ce) def test_prepostprocess_variate(self): space = gymnasium.spaces.Dict({ 'box': gymnasium.spaces.Box(low=0, high=1, shape=(2, 7)), 'multidiscrete': gymnasium.spaces.MultiDiscrete([3, 5]), }) dist = ProbaDist(space) dist_params = { 'box': { 'mu': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), 'logvar': jax.random.normal(next(self.rngs), shape=(11, 2, 7)), }, 'multidiscrete': [ {'logits': jax.random.normal(next(self.rngs), shape=(11, 3))}, {'logits': jax.random.normal(next(self.rngs), shape=(11, 5))}, ], } X_raw = dist.sample(dist_params, next(self.rngs)) X_clean = dist.postprocess_variate(next(self.rngs), X_raw, batch_mode=True) x_clean = dist.postprocess_variate(next(self.rngs), X_raw, batch_mode=False) print(jax.tree_map(jnp.shape, X_raw)) print(jax.tree_map(jnp.shape, X_clean)) print(X_clean) self.assertArrayShape(X_raw['box'], (11, 2, 7)) self.assertArrayShape(X_clean['box'], (11, 2, 7)) self.assertFalse(jnp.all(X_raw['box'] > 0)) self.assertNotIn(X_raw['box'][0], space['box']) self.assertTrue(jnp.all(X_clean['box'] > 0)) self.assertIn(X_clean['box'][0], space['box']) self.assertArrayShape(X_raw['multidiscrete'][0], (11, 3)) self.assertArrayShape(X_raw['multidiscrete'][1], (11, 5)) self.assertArrayShape(X_clean['multidiscrete'], (11, 2)) self.assertNotIn(X_raw['multidiscrete'][0], space['multidiscrete']) self.assertIn(X_clean['multidiscrete'][0], space['multidiscrete']) self.assertIn(x_clean['multidiscrete'], space['multidiscrete']) # Check if bijective. X_clean_ = dist.postprocess_variate( next(self.rngs), dist.preprocess_variate(next(self.rngs), X_clean), batch_mode=True) x_clean_ = dist.postprocess_variate( next(self.rngs), dist.preprocess_variate(next(self.rngs), x_clean), batch_mode=False) self.assertPytreeAlmostEqual(X_clean_, X_clean) self.assertPytreeAlmostEqual(x_clean_, x_clean)
12,738
46.356877
97
py
null
coax-main/coax/proba_dists/_discretized_interval.py
import jax import jax.numpy as jnp import numpy as onp import chex from gymnasium.spaces import Box, Discrete from ..utils import isscalar, jit from ._categorical import CategoricalDist __all__ = ( 'DiscretizedIntervalDist', ) class DiscretizedIntervalDist(CategoricalDist): r""" A categorical distribution over a discretized interval. The input ``dist_params`` to each of the functions is expected to be of the form: .. code:: python dist_params = {'logits': array([...])} which represent the (conditional) distribution parameters. The ``logits``, denoted :math:`z\in\mathbb{R}^n`, are related to the categorical distribution parameters :math:`p\in\Delta^n` via a softmax: .. math:: p_k\ =\ \text{softmax}_k(z)\ =\ \frac{\text{e}^{z_k}}{\sum_j\text{e}^{z_j}} Parameters ---------- space : gymnasium.spaces.Box The gymnasium-style space that specifies the domain of the distribution. The shape of the Box must have :code:`prod(shape) == 1`, i.e. a single interval. num_bins : int, optional The number of equal-sized bins used in the discretization. gumbel_softmax_tau : positive float, optional The parameter :math:`\tau` specifies the sharpness of the Gumbel-softmax sampling (see :func:`sample` method below). A good value for :math:`\tau` balances the trade-off between getting proper deterministic variates (i.e. one-hot vectors) versus getting smooth differentiable variates. """ __slots__ = (*CategoricalDist.__slots__, '__space_orig', '__low', '__high', '__atoms') def __init__(self, space, num_bins=20, gumbel_softmax_tau=0.2): if not isinstance(space, Box): raise TypeError(f"{self.__class__.__name__} can only be defined over Box spaces") if onp.prod(space.shape) > 1: raise TypeError(f"{self.__class__.__name__} can only be defined a single interval") super().__init__(space=Discrete(num_bins), gumbel_softmax_tau=gumbel_softmax_tau) self.__space_orig = space self.__low = low = float(space.low) self.__high = high = float(space.high) self.__atoms = low + (jnp.arange(num_bins) + 0.5) * (high - low) / num_bins def affine_transform(dist_params, scale, shift, value_transform=None): """ implements the "Categorical Algorithm" from https://arxiv.org/abs/1707.06887 """ # check inputs chex.assert_rank([dist_params['logits'], scale, shift], [2, {0, 1}, {0, 1}]) p = jax.nn.softmax(dist_params['logits']) batch_size = p.shape[0] if isscalar(scale): scale = jnp.full(shape=(batch_size,), fill_value=jnp.squeeze(scale)) if isscalar(shift): shift = jnp.full(shape=(batch_size,), fill_value=jnp.squeeze(shift)) chex.assert_shape(p, (batch_size, self.num_bins)) chex.assert_shape([scale, shift], (batch_size,)) if value_transform is None: f = f_inv = lambda x: x else: f, f_inv = value_transform # variable names correspond to those defined in: https://arxiv.org/abs/1707.06887 z = self.__atoms Vmin, Vmax, Δz = z[0], z[-1], z[1] - z[0] Tz = f(jax.vmap(jnp.add)(jnp.outer(scale, f_inv(z)), shift)) Tz = jnp.clip(Tz, Vmin, Vmax) # keep values in valid range chex.assert_shape(Tz, (batch_size, self.num_bins)) b = (Tz - Vmin) / Δz # float in [0, num_bins - 1] l = jnp.floor(b).astype('int32') # noqa: E741 # int in {0, 1, ..., num_bins - 1} u = jnp.ceil(b).astype('int32') # int in {0, 1, ..., num_bins - 1} chex.assert_shape([p, b, l, u], (batch_size, self.num_bins)) m = jnp.zeros_like(p) i = jnp.expand_dims(jnp.arange(batch_size), axis=1) # batch index m = m.at[(i, l)].add(p * (u - b), indices_are_sorted=True) m = m.at[(i, u)].add(p * (b - l), indices_are_sorted=True) m = m.at[(i, l)].add(p * (l == u), indices_are_sorted=True) # chex.assert_tree_all_close(jnp.sum(m, axis=1), jnp.ones(batch_size), rtol=1e-6) # # The above index trickery is equivalent to: # m_alt = onp.zeros((batch_size, self.num_bins)) # for i in range(batch_size): # for j in range(self.num_bins): # if l[i, j] == u[i, j]: # m_alt[i, l[i, j]] += p[i, j] # don't split if b[i, j] is an integer # else: # m_alt[i, l[i, j]] += p[i, j] * (u[i, j] - b[i, j]) # m_alt[i, u[i, j]] += p[i, j] * (b[i, j] - l[i, j]) # chex.assert_tree_all_close(m, m_alt, rtol=1e-6) return {'logits': jnp.log(jnp.maximum(m, 1e-16))} self._affine_transform_func = jit(affine_transform, static_argnums=(3,)) @property def space_orig(self): return self.__space_orig @property def low(self): return self.__low @property def high(self): return self.__high @property def num_bins(self): return self.space.n @property def atoms(self): return self.__atoms.copy() def preprocess_variate(self, rng, X): X = jnp.asarray(X) assert X.ndim <= 1, f"unexpected X.shape: {X.shape}" assert jnp.issubdtype(X.dtype, jnp.integer), f"expected an integer dtype, got {X.dtype}" low, high = float(self.space_orig.low), float(self.space_orig.high) return jax.nn.one_hot(jnp.floor((X - low) * self.num_bins / (high - low)), self.num_bins) def postprocess_variate(self, rng, X, index=0, batch_mode=False): # map almost-one-hot vectors to bin-indices (ints) chex.assert_rank(X, {2, 3}) assert X.shape[-1] == self.num_bins # map bin-probabilities to real values X = jnp.dot(X, self.__atoms) chex.assert_rank(X, {1, 2}) return X if batch_mode else X[index]
6,166
37.54375
98
py
null
coax-main/coax/proba_dists/_empirical_quantile.py
import chex import jax import jax.numpy as jnp from gymnasium.spaces import Box from ..utils import jit, isscalar from ._base import BaseProbaDist __all__ = ( 'EmpiricalQuantileDist', ) class EmpiricalQuantileDist(BaseProbaDist): def __init__(self, num_quantiles): self.num_quantiles = num_quantiles super().__init__(Box(low=-jnp.inf, high=jnp.inf, shape=[num_quantiles])) def check_shape(x, name): if not isinstance(x, jnp.ndarray): raise TypeError(f"expected an jax.numpy.ndarray, got: {type(x)}") return x def mean(dist_params): values = check_shape(dist_params['values'], 'values') return jnp.mean(values, axis=-1) def sample(dist_params, rng): # bootstrapping values = check_shape(dist_params['values'], 'values') return jax.random.choice(rng, values, values.shape, replace=True) def log_proba(dist_params, X): X = check_shape(X, 'X') values = check_shape(dist_params['values'], 'values') occurrences = jnp.mean(X[None, ...] == values[..., None], axis=-1) return jnp.log(occurrences) def affine_transform(dist_params, scale, shift, value_transform=None): chex.assert_rank([dist_params['values'], scale, shift], [2, {0, 1}, {0, 1}]) values = check_shape(dist_params['values'], 'values') quantile_fractions = check_shape( dist_params['quantile_fractions'], 'quantile_fractions') batch_size = values.shape[0] if isscalar(scale): scale = jnp.full(shape=(batch_size, 1), fill_value=jnp.squeeze(scale)) if isscalar(shift): shift = jnp.full(shape=(batch_size, 1), fill_value=jnp.squeeze(shift)) scale = jnp.reshape(scale, (batch_size, 1)) shift = jnp.reshape(shift, (batch_size, 1)) chex.assert_shape(values, (batch_size, self.num_quantiles)) chex.assert_shape([scale, shift], (batch_size, 1)) if value_transform is None: f = f_inv = lambda x: x else: f, f_inv = value_transform return {'values': f(shift + scale * f_inv(values)), 'quantile_fractions': quantile_fractions} self._sample_func = jit(sample) self._mean_func = jit(mean) self._log_proba_func = jit(log_proba) self._affine_transform_func = jit(affine_transform, static_argnums=(3,)) @property def default_priors(self): return {'values': jnp.zeros((1, self.num_quantiles)), 'quantile_fractions': jnp.ones((1, self.num_quantiles,))} @property def sample(self): return self._sample_func @property def mean(self): return self._mean_func @property def log_proba(self): return self._log_proba_func
2,964
32.693182
89
py