text
stringlengths
81
112k
Make `p` listy and the same length as `q`. def listify(p:OptListOrItem=None, q:OptListOrItem=None): "Make `p` listy and the same length as `q`." if p is None: p=[] elif isinstance(p, str): p = [p] elif not isinstance(p, Iterable): p = [p] #Rank 0 tensors in PyTorch are Iterable but don't h...
Change `name` from camel to snake style. def camel2snake(name:str)->str: "Change `name` from camel to snake style." s1 = re.sub(_camel_re1, r'\1_\2', name) return re.sub(_camel_re2, r'\1_\2', s1).lower()
Build log-stepped array from `start` to `stop` in `n` steps. def even_mults(start:float, stop:float, n:int)->np.ndarray: "Build log-stepped array from `start` to `stop` in `n` steps." mult = stop/start step = mult**(1/(n-1)) return np.array([start*(step**i) for i in range(n)])
Extract the keys in `names` from the `kwargs`. def extract_kwargs(names:Collection[str], kwargs:KWArgs): "Extract the keys in `names` from the `kwargs`." new_kwargs = {} for arg_name in names: if arg_name in kwargs: arg_val = kwargs.pop(arg_name) new_kwargs[arg_name] = arg_v...
Split iterables `a` in equal parts of size `sz` def partition(a:Collection, sz:int)->List[Collection]: "Split iterables `a` in equal parts of size `sz`" return [a[i:i+sz] for i in range(0, len(a), sz)]
Split data in `a` equally among `n_cpus` cores def partition_by_cores(a:Collection, n_cpus:int)->List[Collection]: "Split data in `a` equally among `n_cpus` cores" return partition(a, len(a)//n_cpus + 1)
Categorifies the columns `col_names` in `df`. def series2cat(df:DataFrame, *col_names): "Categorifies the columns `col_names` in `df`." for c in listify(col_names): df[c] = df[c].astype('category').cat.as_ordered()
Download `url` to `dest` unless it exists and not `overwrite`. def download_url(url:str, dest:str, overwrite:bool=False, pbar:ProgressBar=None, show_progress=True, chunk_size=1024*1024, timeout=4, retries=5)->None: "Download `url` to `dest` unless it exists and not `overwrite`." if os.path.exi...
Return `Path(path)/Path(fname)`, `path` defaults to current dir. def join_path(fname:PathOrStr, path:PathOrStr='.')->Path: "Return `Path(path)/Path(fname)`, `path` defaults to current dir." return Path(path)/Path(fname)
Join `path` to every file name in `fnames`. def join_paths(fnames:FilePathList, path:PathOrStr='.')->Collection[Path]: "Join `path` to every file name in `fnames`." path = Path(path) return [join_path(o,path) for o in fnames]
Return `ndarray` of `str` of lines of text from `path`. def loadtxt_str(path:PathOrStr)->np.ndarray: "Return `ndarray` of `str` of lines of text from `path`." with open(path, 'r') as f: lines = f.readlines() return np.array([l.strip() for l in lines])
Save in `fname` the content of `texts`. def save_texts(fname:PathOrStr, texts:Collection[str]): "Save in `fname` the content of `texts`." with open(fname, 'w') as f: for t in texts: f.write(f'{t}\n')
Return the column indexes of `names` in `df`. def df_names_to_idx(names:IntsOrStrs, df:DataFrame): "Return the column indexes of `names` in `df`." if not is_listy(names): names = [names] if isinstance(names[0], int): return names return [df.columns.get_loc(c) for c in names]
One-hot encode `x` with `c` classes. def one_hot(x:Collection[int], c:int): "One-hot encode `x` with `c` classes." res = np.zeros((c,), np.float32) res[listify(x)] = 1. return res
Return the slice of `a` corresponding to `idxs`. def index_row(a:Union[Collection,pd.DataFrame,pd.Series], idxs:Collection[int])->Any: "Return the slice of `a` corresponding to `idxs`." if a is None: return a if isinstance(a,(pd.DataFrame,pd.Series)): res = a.iloc[idxs] if isinstance(res,(p...
Return the arguments of `func`. def func_args(func)->bool: "Return the arguments of `func`." code = func.__code__ return code.co_varnames[:code.co_argcount]
Split `kwargs` between those expected by `func` and the others. def split_kwargs_by_func(kwargs, func): "Split `kwargs` between those expected by `func` and the others." args = func_args(func) func_kwargs = {a:kwargs.pop(a) for a in args if a in kwargs} return func_kwargs, kwargs
Same as `np.array` but also handles generators. `kwargs` are passed to `np.array` with `dtype`. def array(a, dtype:type=None, **kwargs)->np.ndarray: "Same as `np.array` but also handles generators. `kwargs` are passed to `np.array` with `dtype`." if not isinstance(a, collections.Sized) and not getattr(a,'__arr...
Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %. def text2html_table(items:Collection[Collection[str]])->str: "Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %." html_code = f"""<table border="1" class="dataframe">""" html_code +=...
Call `func` on every element of `arr` in parallel using `max_workers`. def parallel(func, arr:Collection, max_workers:int=None): "Call `func` on every element of `arr` in parallel using `max_workers`." max_workers = ifnone(max_workers, defaults.cpus) if max_workers<2: results = [func(o,i) for i,o in progre...
Like `plt.subplots` but with consistent axs shape, `kwargs` passed to `fig.suptitle` with `title` def subplots(rows:int, cols:int, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, title=None, **kwargs): "Like `plt.subplots` but with consistent axs shape, `kwargs` passed to `fig.suptitle` with `title`" fig...
Return the representation of the first `n_max` elements in `items`. def show_some(items:Collection, n_max:int=5, sep:str=','): "Return the representation of the first `n_max` elements in `items`." if items is None or len(items) == 0: return '' res = sep.join([f'{o}' for o in items[:n_max]]) if len(it...
Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it. def get_tmp_file(dir=None): "Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it." with tempfile.NamedTemporaryFile(delete=False, dir=dir) as f: return f.name
Compose `funcs` def compose(funcs:List[Callable])->Callable: "Compose `funcs`" def compose_(funcs, x, *args, **kwargs): for f in listify(funcs): x = f(x, *args, **kwargs) return x return partial(compose_, funcs)
Subclass this method if you want to customize the way this `ItemBase` is shown on `ax`. def show(self, ax:plt.Axes, **kwargs): "Subclass this method if you want to customize the way this `ItemBase` is shown on `ax`." ax.set_title(str(self))
Init layer parameters. def init_params(net): '''Init layer parameters.''' for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): ...
Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer. def conv_bn_lrelu(ni:int, nf:int, ks:int=3, stride:int=1)->nn.Sequential: "Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer." return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks//2), nn.BatchNo...
starts with conv layer - `ch_in` channels in - then has `num_blocks` `ResLayer` def make_group_layer(self, ch_in:int, num_blocks:int, stride:int=1): "starts with conv layer - `ch_in` channels in - then has `num_blocks` `ResLayer`" return [conv_bn_lrelu(ch_in, ch_in*2,stride=stride) ] + [...
Create a Learner for collaborative filtering on `data`. def collab_learner(data, n_factors:int=None, use_nn:bool=False, emb_szs:Dict[str,int]=None, layers:Collection[int]=None, ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, bn_final:bool=F...
Create a `DataBunch` suitable for collaborative filtering from `ratings`. def from_df(cls, ratings:DataFrame, valid_pct:float=0.2, user_name:Optional[str]=None, item_name:Optional[str]=None, rating_name:Optional[str]=None, test:DataFrame=None, seed:int=None, path:PathOrStr='.', bs:int=64, ...
Fetch item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.) def get_idx(self, arr:Collection, is_item:bool=True): "Fetch item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)" m = self.model.eval().cpu() requires_grad(m,False) ...
Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.) def bias(self, arr:Collection, is_item:bool=True): "Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)" idx = self.get_idx(arr, is_item) m = self.model ...
Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.) def weight(self, arr:Collection, is_item:bool=True): "Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)" idx = self.get_idx(arr, is_item) m = self.model ...
Draws a representation of a random forest in IPython. Parameters: ----------- t: The tree you wish to draw df: The data used to train the tree. This is used to get the names of the features. def draw_tree(t, df, size=10, ratio=0.6, precision=0): """ Draws a representation of a random forest in IPyt...
Gets a random sample of n rows from df, without replacement. Parameters: ----------- df: A pandas data frame, that you wish to sample from. n: The number of rows you wish to sample. Returns: -------- return value: A random sample of n rows of df. Examples: --------- >>> df = pd.D...
add_datepart converts a column of df from a datetime64 to many columns containing the information from the date. This applies changes inplace. Parameters: ----------- df: A pandas data frame. df gain several new columns. fldname: A string that is the name of the date column you wish to expand. ...
Change any columns of strings in a panda's dataframe to a column of categorical values. This applies the changes inplace. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. Examples: --------- >>> df = pd.DataFrame({'col1' : ...
Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The category codes are determined by trn. trn: A pandas dataframe. Whe...
Fill missing data in a column of df with the median, and add a {name}_na column which specifies if the data was missing. Parameters: ----------- df: The data frame that will be changed. col: The column of data to fix by filling in missing data. name: The name of the new filled column in df. ...
Changes the column col from a categorical type to it's integer codes. Parameters: ----------- df: A pandas dataframe. df[name] will be filled with the integer codes from col. col: The column you wish to change into the categories. name: The column name you wish to insert into df. This column...
proc_df takes a data frame df and splits off the response variable, and changes the df into an entirely numeric dataframe. For each column of df which is not in skip_flds nor in ignore_flds, na values are replaced by the median value of the column. Parameters: ----------- df: The data frame you...
Changes Scikit learn's random forests to give each tree a random sample of n random rows. def set_rf_samples(n): """ Changes Scikit learn's random forests to give each tree a random sample of n random rows. """ forest._generate_sample_indices = (lambda rs, n_samples: forest.check_random_sta...
Undoes the changes produced by set_rf_samples. def reset_rf_samples(): """ Undoes the changes produced by set_rf_samples. """ forest._generate_sample_indices = (lambda rs, n_samples: forest.check_random_state(rs).randint(0, n_samples, n_samples))
Return globally assigned variables. def get_global_vars(mod): "Return globally assigned variables." # https://stackoverflow.com/questions/8820276/docstring-for-variable/31764368#31764368 import ast,re with open(mod.__file__, 'r') as f: fstr = f.read() flines = fstr.splitlines() d = {} for n...
Execute notebook `fname` with `metadata` for preprocessing. def execute_nb(fname, metadata=None, save=True, show_doc_only=False): "Execute notebook `fname` with `metadata` for preprocessing." # Any module used in the notebook that isn't inside must be in the same directory as this script with open(fname) a...
Create the documentation notebook for module `mod_name` in path `dest_path` def create_module_page(mod, dest_path, force=False): "Create the documentation notebook for module `mod_name` in path `dest_path`" nb = get_empty_notebook() mod_name = mod.__name__ strip_name = strip_fastai(mod_name) init_c...
Search a given `path_dir` and return all the modules contained inside except those in `exclude` def get_module_names(path_dir, exclude=None): if exclude is None: exclude = _default_exclude "Search a given `path_dir` and return all the modules contained inside except those in `exclude`" files = sorted(path_...
Read a notebook in `fname` and return its corresponding json def read_nb(fname): "Read a notebook in `fname` and return its corresponding json" with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4)
Build a dictionary containing the position of the `cells`. def read_nb_content(cells, mod_name): "Build a dictionary containing the position of the `cells`." doc_fns = {} for i, cell in enumerate(cells): if cell['cell_type'] == 'code': for match in SHOW_DOC_RE.findall(cell['source']): ...
Create documentation links for all cells in markdown with backticks. def link_markdown_cells(cells, modules): "Create documentation links for all cells in markdown with backticks." for i, cell in enumerate(cells): if cell['cell_type'] == 'markdown': cell['source'] = link_docstring(modules, ...
Return the position to insert a given function doc in a notebook. def get_insert_idx(pos_dict, name): "Return the position to insert a given function doc in a notebook." keys,i = list(pos_dict.keys()),0 while i < len(keys) and str.lower(keys[i]) < str.lower(name): i+=1 if i == len(keys): return -1 ...
Update the `pos_dict` by moving all positions after `start_key` by `nbr`. def update_pos(pos_dict, start_key, nbr=2): "Update the `pos_dict` by moving all positions after `start_key` by `nbr`." for key,idx in pos_dict.items(): if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr return p...
Insert the function doc `cells` at their correct position and updates `pos_dict`. def insert_cells(cells, pos_dict, ft_name, append=False): "Insert the function doc `cells` at their correct position and updates `pos_dict`." idx = get_insert_idx(pos_dict, ft_name) if append or idx == -1: cells += [get_doc_c...
Creates jekyll metadata for given notebook path. def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs): "Creates jekyll metadata for given notebook path." nb = read_nb(nb_path) data = {'title': title, 'summary': summary, 'keywords': keywords, **kwargs} ...
Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority def get_imported_modules(cells, nb_module_name=''): "Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority"...
Update the documentation notebook of a given module. def update_module_page(mod, dest_path='.'): "Update the documentation notebook of a given module." doc_path = get_doc_path(mod, dest_path) strip_name = strip_fastai(mod.__name__) nb = read_nb(doc_path) cells = nb['cells'] link_markdown_cells...
`source_path` can be a directory or a file. Assume all modules reside in the fastai directory. def update_notebooks(source_path, dest_path=None, update_html=True, document_new_fns=False, update_nb_links=True, html_path=None, force=False): "`source_path` can be a directory or a file. Assume all...
Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element. def dropout_mask(x:Tensor, sz:Collection[int], p:float): "Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element." return x.new(*sz).bernoulli_(1-p).div_(1-p)
Split a RNN `model` in groups for differential learning rates. def awd_lstm_lm_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." groups = [[rnn, dp] for rnn, dp in zip(model[0].rnns, model[0].hidden_dps)] return groups + [[model[0].encoder, model[0]...
Convert a value `x` from 0 to 1 (inclusive) to an RGBA tuple according to `cmap` times transparency `alpha_mult`. def value2rgba(x:float, cmap:Callable=cm.RdYlGn, alpha_mult:float=1.0)->Tuple: "Convert a value `x` from 0 to 1 (inclusive) to an RGBA tuple according to `cmap` times transparency `alpha_mult`." c ...
Apply dropout to the raw weights. def _setweights(self): "Apply dropout to the raw weights." for layer in self.layer_names: raw_w = getattr(self, f'{layer}_raw') self.module._parameters[layer] = F.dropout(raw_w, p=self.weight_p, training=self.training)
Return one hidden state. def _one_hidden(self, l:int)->Tensor: "Return one hidden state." nh = (self.n_hid if l != self.n_layers - 1 else self.emb_sz) // self.n_dir return one_param(self).new(1, self.bs, nh).zero_()
Reset the hidden states. def reset(self): "Reset the hidden states." [r.reset() for r in self.rnns if hasattr(r, 'reset')] if self.qrnn: self.hidden = [self._one_hidden(l) for l in range(self.n_layers)] else: self.hidden = [(self._one_hidden(l), self._one_hidden(l)) for l in range(self....
Calculate the intrinsic attention of the input w.r.t to an output `class_id`, or the classification given by the model if `None`. For reference, see the Sequential Jacobian session at https://www.cs.toronto.edu/~graves/preprint.pdf def intrinsic_attention(self, text:str, class_id:int=None): """Calculat...
Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of actual class. `max_len` is the maximum number of tokens displayed. def show_top_losses(self, k:int, max_len:int=70)->None: """ Create a tabulation showing the first `k` tex...
Initialize the schedulers for training. def on_train_begin(self, epoch:int, **kwargs:Any)->None: "Initialize the schedulers for training." res = {'epoch':self.start_epoch} if self.start_epoch is not None else None self.start_epoch = ifnone(self.start_epoch, epoch) self.scheds = [p.sched...
Take a step in lr,mom sched, start next stepper when the current one is complete. def on_batch_end(self, train, **kwargs:Any)->None: "Take a step in lr,mom sched, start next stepper when the current one is complete." if train: if self.idx_s >= len(self.scheds): return {'stop_training': True...
Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly. def tensor(x:Any, *rest)->Tensor: "Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly." if len(rest): x = (x,)+rest # XXX: Pytorch bug in dataloader using num_workers>0; T...
Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`. def to_detach(b:Tensors, cpu:bool=True): "Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`." if is_listy(b): return [to_detach(o, cpu) for o in b] if not isinstance(b,Tensor): return b b = b.de...
Recursively map lists of items in `b ` to their wrapped data. def to_data(b:ItemsList): "Recursively map lists of items in `b ` to their wrapped data." if is_listy(b): return [to_data(o) for o in b] return b.data if isinstance(b,ItemBase) else b
Recursively map lists of tensors in `b ` to the cpu. def to_cpu(b:ItemsList): "Recursively map lists of tensors in `b ` to the cpu." if is_listy(b): return [to_cpu(o) for o in b] return b.cpu() if isinstance(b,Tensor) else b
Recursively map lists of tensors in `b ` to FP16. def to_half(b:Collection[Tensor])->Collection[Tensor]: "Recursively map lists of tensors in `b ` to FP16." if is_listy(b): return [to_half(o) for o in b] return b.half() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b
Recursively map lists of tensors in `b ` to FP16. def to_float(b:Collection[Tensor])->Collection[Tensor]: "Recursively map lists of tensors in `b ` to FP16." if is_listy(b): return [to_float(o) for o in b] return b.float() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b
Recursively put `b` on `device`. def to_device(b:Tensors, device:torch.device): "Recursively put `b` on `device`." device = ifnone(device, defaults.device) if is_listy(b): return [to_device(o, device) for o in b] if is_dict(b): return {k: to_device(v, device) for k, v in b.items()} return b.to(devi...
Convert `batch` items to tensor data. def data_collate(batch:ItemsList)->Tensor: "Convert `batch` items to tensor data." return torch.utils.data.dataloader.default_collate(to_data(batch))
If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b` def requires_grad(m:nn.Module, b:Optional[bool]=None)->Optional[bool]: "If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b`" ps = list(m.parameters()) if...
Return list of trainable params in `m`. def trainable_params(m:nn.Module)->ParamList: "Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res
Return the children of `m` and its direct parameters not registered in modules. def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],...
Split `model` according to the indexes in `idxs`. def split_model_idx(model:nn.Module, idxs:Collection[int])->ModuleList: "Split `model` according to the indexes in `idxs`." layers = flatten_model(model) if idxs[0] != 0: idxs = [0] + idxs if idxs[-1] != len(layers): idxs.append(len(layers)) return ...
Split `model` according to the layers in `splits`. def split_model(model:nn.Module=None, splits:Collection[Union[nn.Module,ModuleList]]=None): "Split `model` according to the layers in `splits`." splits = listify(splits) if isinstance(splits[0], nn.Module): layers = flatten_model(model) idx...
Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest. def split_no_wd_params(layer_groups:Collection[nn.Module])->List[List[nn.Parameter]]: "Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest." split_params = ...
Set bn layers in eval mode for all recursive children of `m`. def set_bn_eval(m:nn.Module)->None: "Set bn layers in eval mode for all recursive children of `m`." for l in m.children(): if isinstance(l, bn_types) and not next(l.parameters()).requires_grad: l.eval() set_bn_eval(l)
If `module` is batchnorm don't use half precision. def bn2float(module:nn.Module)->nn.Module: "If `module` is batchnorm don't use half precision." if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): bn2float(child) return module
Initialize `m` weights with `func` and set `bias` to 0. def init_default(m:nn.Module, func:LayerFunc=nn.init.kaiming_normal_)->None: "Initialize `m` weights with `func` and set `bias` to 0." if func: if hasattr(m, 'weight'): func(m.weight) if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bi...
Initialize the non-batchnorm layers of `m` with `init_func`. def cond_init(m:nn.Module, init_func:LayerFunc): "Initialize the non-batchnorm layers of `m` with `init_func`." if (not isinstance(m, bn_types)) and requires_grad(m): init_default(m, init_func)
Initialize all non-batchnorm layers of `m` with `init_func`. def apply_init(m, init_func:LayerFunc): "Initialize all non-batchnorm layers of `m` with `init_func`." apply_leaf(m, partial(cond_init, init_func=init_func))
Return the shape of the first weight layer in `m`. def in_channels(m:nn.Module) -> List[int]: "Return the shape of the first weight layer in `m`." for l in flatten_model(m): if hasattr(l, 'weight'): return l.weight.shape[1] raise Exception('No weight layer')
Return the torch type corresponding to `dtype`. def model_type(dtype): "Return the torch type corresponding to `dtype`." return (torch.float32 if np.issubdtype(dtype, np.floating) else torch.int64 if np.issubdtype(dtype, np.integer) else None)
Tranform numpy array `a` to a tensor of the same type. def np2model_tensor(a): "Tranform numpy array `a` to a tensor of the same type." dtype = model_type(a.dtype) res = as_tensor(a) if not dtype: return res return res.type(dtype)
Compute PCA of `x` with `k` dimensions. def _pca(x, k=2): "Compute PCA of `x` with `k` dimensions." x = x-torch.mean(x,0) U,S,V = torch.svd(x.t()) return torch.mm(x,U[:,:k])
Grab the `i`-th batch in `x`, `batch_first` stating the batch dimension. def grab_idx(x,i,batch_first:bool=True): "Grab the `i`-th batch in `x`, `batch_first` stating the batch dimension." if batch_first: return ([o[i].cpu() for o in x] if is_listy(x) else x[i].cpu()) else: return ([o[:,i].cpu(...
Inplace logit of `x`, clamped to avoid inf def logit_(x:Tensor)->Tensor: "Inplace logit of `x`, clamped to avoid inf" x.clamp_(1e-7, 1-1e-7) return (x.reciprocal_().sub_(1)).log_().neg_()
Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`. def uniform(low:Number, high:Number=None, size:Optional[List[int]]=None)->FloatOrTensor: "Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`." if high is None: high=low return random.uniform(low,high) ...
Draw 1 or shape=`size` random floats from uniform dist: min=log(`low`), max=log(`high`). def log_uniform(low, high, size:Optional[List[int]]=None)->FloatOrTensor: "Draw 1 or shape=`size` random floats from uniform dist: min=log(`low`), max=log(`high`)." res = uniform(log(low), log(high), size) return exp(r...
Draw 1 or shape=`size` random booleans (`True` occuring with probability `p`). def rand_bool(p:float, size:Optional[List[int]]=None)->BoolOrTensor: "Draw 1 or shape=`size` random booleans (`True` occuring with probability `p`)." return uniform(0,1,size)<p
Generate int or tensor `size` of ints between `low` and `high` (included). def uniform_int(low:int, high:int, size:Optional[List[int]]=None)->IntOrTensor: "Generate int or tensor `size` of ints between `low` and `high` (included)." return random.randint(low,high) if size is None else torch.randint(low,high+1,s...
Try to convert `o` to int, default to `o` if not possible. def try_int(o:Any)->Any: "Try to convert `o` to int, default to `o` if not possible." # NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o) ...
Return the model maybe wrapped inside `model`. def get_model(model:nn.Module): "Return the model maybe wrapped inside `model`." return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model
Check that `out` and `targ` have the same number of elements and flatten them. def flatten_check(out:Tensor, targ:Tensor) -> Tensor: "Check that `out` and `targ` have the same number of elements and flatten them." out,targ = out.contiguous().view(-1),targ.contiguous().view(-1) assert len(out) == len(targ),...
create new OrderedDict that does not contain `module.` def remove_module_load(state_dict): """create new OrderedDict that does not contain `module.`""" new_state_dict = OrderedDict() for k, v in state_dict.items(): new_state_dict[k[7:]] = v return new_state_dict