id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
20,700
fastai/fastai
fastai/core.py
show_some
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(items) > n_max: res += '...' return res
python
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(items) > n_max: res += '...' return res
[ "def", "show_some", "(", "items", ":", "Collection", ",", "n_max", ":", "int", "=", "5", ",", "sep", ":", "str", "=", "','", ")", ":", "if", "items", "is", "None", "or", "len", "(", "items", ")", "==", "0", ":", "return", "''", "res", "=", "sep", ".", "join", "(", "[", "f'{o}'", "for", "o", "in", "items", "[", ":", "n_max", "]", "]", ")", "if", "len", "(", "items", ")", ">", "n_max", ":", "res", "+=", "'...'", "return", "res" ]
Return the representation of the first `n_max` elements in `items`.
[ "Return", "the", "representation", "of", "the", "first", "n_max", "elements", "in", "items", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L340-L345
20,701
fastai/fastai
fastai/core.py
get_tmp_file
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
python
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
[ "def", "get_tmp_file", "(", "dir", "=", "None", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "dir", "=", "dir", ")", "as", "f", ":", "return", "f", ".", "name" ]
Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it.
[ "Create", "and", "return", "a", "tmp", "filename", "optionally", "at", "a", "specific", "path", ".", "os", ".", "remove", "when", "done", "with", "it", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L347-L349
20,702
fastai/fastai
fastai/core.py
ItemBase.show
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))
python
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))
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", ",", "*", "*", "kwargs", ")", ":", "ax", ".", "set_title", "(", "str", "(", "self", ")", ")" ]
Subclass this method if you want to customize the way this `ItemBase` is shown on `ax`.
[ "Subclass", "this", "method", "if", "you", "want", "to", "customize", "the", "way", "this", "ItemBase", "is", "shown", "on", "ax", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L157-L159
20,703
fastai/fastai
fastai/vision/models/darknet.py
conv_bn_lrelu
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.BatchNorm2d(nf), nn.LeakyReLU(negative_slope=0.1, inplace=True))
python
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.BatchNorm2d(nf), nn.LeakyReLU(negative_slope=0.1, inplace=True))
[ "def", "conv_bn_lrelu", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "3", ",", "stride", ":", "int", "=", "1", ")", "->", "nn", ".", "Sequential", ":", "return", "nn", ".", "Sequential", "(", "nn", ".", "Conv2d", "(", "ni", ",", "nf", ",", "kernel_size", "=", "ks", ",", "bias", "=", "False", ",", "stride", "=", "stride", ",", "padding", "=", "ks", "//", "2", ")", ",", "nn", ".", "BatchNorm2d", "(", "nf", ")", ",", "nn", ".", "LeakyReLU", "(", "negative_slope", "=", "0.1", ",", "inplace", "=", "True", ")", ")" ]
Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer.
[ "Create", "a", "seuence", "Conv2d", "-", ">", "BatchNorm2d", "-", ">", "LeakyReLu", "layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/models/darknet.py#L6-L11
20,704
fastai/fastai
fastai/vision/models/darknet.py
Darknet.make_group_layer
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) ] + [(ResLayer(ch_in*2)) for i in range(num_blocks)]
python
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) ] + [(ResLayer(ch_in*2)) for i in range(num_blocks)]
[ "def", "make_group_layer", "(", "self", ",", "ch_in", ":", "int", ",", "num_blocks", ":", "int", ",", "stride", ":", "int", "=", "1", ")", ":", "return", "[", "conv_bn_lrelu", "(", "ch_in", ",", "ch_in", "*", "2", ",", "stride", "=", "stride", ")", "]", "+", "[", "(", "ResLayer", "(", "ch_in", "*", "2", ")", ")", "for", "i", "in", "range", "(", "num_blocks", ")", "]" ]
starts with conv layer - `ch_in` channels in - then has `num_blocks` `ResLayer`
[ "starts", "with", "conv", "layer", "-", "ch_in", "channels", "in", "-", "then", "has", "num_blocks", "ResLayer" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/models/darknet.py#L24-L27
20,705
fastai/fastai
fastai/collab.py
collab_learner
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=False, **learn_kwargs)->Learner: "Create a Learner for collaborative filtering on `data`." emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) u,m = data.train_ds.x.classes.values() if use_nn: model = EmbeddingNN(emb_szs=emb_szs, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range, use_bn=use_bn, bn_final=bn_final, **learn_kwargs) else: model = EmbeddingDotBias(n_factors, len(u), len(m), y_range=y_range) return CollabLearner(data, model, **learn_kwargs)
python
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=False, **learn_kwargs)->Learner: "Create a Learner for collaborative filtering on `data`." emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) u,m = data.train_ds.x.classes.values() if use_nn: model = EmbeddingNN(emb_szs=emb_szs, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range, use_bn=use_bn, bn_final=bn_final, **learn_kwargs) else: model = EmbeddingDotBias(n_factors, len(u), len(m), y_range=y_range) return CollabLearner(data, model, **learn_kwargs)
[ "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", "=", "False", ",", "*", "*", "learn_kwargs", ")", "->", "Learner", ":", "emb_szs", "=", "data", ".", "get_emb_szs", "(", "ifnone", "(", "emb_szs", ",", "{", "}", ")", ")", "u", ",", "m", "=", "data", ".", "train_ds", ".", "x", ".", "classes", ".", "values", "(", ")", "if", "use_nn", ":", "model", "=", "EmbeddingNN", "(", "emb_szs", "=", "emb_szs", ",", "layers", "=", "layers", ",", "ps", "=", "ps", ",", "emb_drop", "=", "emb_drop", ",", "y_range", "=", "y_range", ",", "use_bn", "=", "use_bn", ",", "bn_final", "=", "bn_final", ",", "*", "*", "learn_kwargs", ")", "else", ":", "model", "=", "EmbeddingDotBias", "(", "n_factors", ",", "len", "(", "u", ")", ",", "len", "(", "m", ")", ",", "y_range", "=", "y_range", ")", "return", "CollabLearner", "(", "data", ",", "model", ",", "*", "*", "learn_kwargs", ")" ]
Create a Learner for collaborative filtering on `data`.
[ "Create", "a", "Learner", "for", "collaborative", "filtering", "on", "data", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/collab.py#L98-L107
20,706
fastai/fastai
fastai/collab.py
CollabDataBunch.from_df
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, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False) -> 'CollabDataBunch': "Create a `DataBunch` suitable for collaborative filtering from `ratings`." user_name = ifnone(user_name, ratings.columns[0]) item_name = ifnone(item_name, ratings.columns[1]) rating_name = ifnone(rating_name,ratings.columns[2]) cat_names = [user_name,item_name] src = (CollabList.from_df(ratings, cat_names=cat_names, procs=Categorify) .split_by_rand_pct(valid_pct=valid_pct, seed=seed).label_from_df(cols=rating_name)) if test is not None: src.add_test(CollabList.from_df(test, cat_names=cat_names)) return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device, collate_fn=collate_fn, no_check=no_check)
python
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, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False) -> 'CollabDataBunch': "Create a `DataBunch` suitable for collaborative filtering from `ratings`." user_name = ifnone(user_name, ratings.columns[0]) item_name = ifnone(item_name, ratings.columns[1]) rating_name = ifnone(rating_name,ratings.columns[2]) cat_names = [user_name,item_name] src = (CollabList.from_df(ratings, cat_names=cat_names, procs=Categorify) .split_by_rand_pct(valid_pct=valid_pct, seed=seed).label_from_df(cols=rating_name)) if test is not None: src.add_test(CollabList.from_df(test, cat_names=cat_names)) return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device, collate_fn=collate_fn, no_check=no_check)
[ "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", ",", "val_bs", ":", "int", "=", "None", ",", "num_workers", ":", "int", "=", "defaults", ".", "cpus", ",", "dl_tfms", ":", "Optional", "[", "Collection", "[", "Callable", "]", "]", "=", "None", ",", "device", ":", "torch", ".", "device", "=", "None", ",", "collate_fn", ":", "Callable", "=", "data_collate", ",", "no_check", ":", "bool", "=", "False", ")", "->", "'CollabDataBunch'", ":", "user_name", "=", "ifnone", "(", "user_name", ",", "ratings", ".", "columns", "[", "0", "]", ")", "item_name", "=", "ifnone", "(", "item_name", ",", "ratings", ".", "columns", "[", "1", "]", ")", "rating_name", "=", "ifnone", "(", "rating_name", ",", "ratings", ".", "columns", "[", "2", "]", ")", "cat_names", "=", "[", "user_name", ",", "item_name", "]", "src", "=", "(", "CollabList", ".", "from_df", "(", "ratings", ",", "cat_names", "=", "cat_names", ",", "procs", "=", "Categorify", ")", ".", "split_by_rand_pct", "(", "valid_pct", "=", "valid_pct", ",", "seed", "=", "seed", ")", ".", "label_from_df", "(", "cols", "=", "rating_name", ")", ")", "if", "test", "is", "not", "None", ":", "src", ".", "add_test", "(", "CollabList", ".", "from_df", "(", "test", ",", "cat_names", "=", "cat_names", ")", ")", "return", "src", ".", "databunch", "(", "path", "=", "path", ",", "bs", "=", "bs", ",", "val_bs", "=", "val_bs", ",", "num_workers", "=", "num_workers", ",", "device", "=", "device", ",", "collate_fn", "=", "collate_fn", ",", "no_check", "=", "no_check", ")" ]
Create a `DataBunch` suitable for collaborative filtering from `ratings`.
[ "Create", "a", "DataBunch", "suitable", "for", "collaborative", "filtering", "from", "ratings", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/collab.py#L55-L68
20,707
fastai/fastai
old/fastai/structured.py
set_rf_samples
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_state(rs).randint(0, n_samples, n))
python
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_state(rs).randint(0, n_samples, n))
[ "def", "set_rf_samples", "(", "n", ")", ":", "forest", ".", "_generate_sample_indices", "=", "(", "lambda", "rs", ",", "n_samples", ":", "forest", ".", "check_random_state", "(", "rs", ")", ".", "randint", "(", "0", ",", "n_samples", ",", "n", ")", ")" ]
Changes Scikit learn's random forests to give each tree a random sample of n random rows.
[ "Changes", "Scikit", "learn", "s", "random", "forests", "to", "give", "each", "tree", "a", "random", "sample", "of", "n", "random", "rows", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/structured.py#L382-L387
20,708
fastai/fastai
old/fastai/structured.py
reset_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))
python
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))
[ "def", "reset_rf_samples", "(", ")", ":", "forest", ".", "_generate_sample_indices", "=", "(", "lambda", "rs", ",", "n_samples", ":", "forest", ".", "check_random_state", "(", "rs", ")", ".", "randint", "(", "0", ",", "n_samples", ",", "n_samples", ")", ")" ]
Undoes the changes produced by set_rf_samples.
[ "Undoes", "the", "changes", "produced", "by", "set_rf_samples", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/structured.py#L389-L393
20,709
fastai/fastai
fastai/gen_doc/gen_notebooks.py
get_global_vars
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 node in ast.walk(ast.parse(fstr)): if isinstance(node,ast.Assign) and hasattr(node.targets[0], 'id'): key,lineno = node.targets[0].id,node.targets[0].lineno codestr = flines[lineno] match = re.match(f"^({key})\s*=\s*.*", codestr) if match and match.group(1) != '__all__': # only top level assignment d[key] = f'`{codestr}` {get_source_link(mod, lineno)}' return d
python
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 node in ast.walk(ast.parse(fstr)): if isinstance(node,ast.Assign) and hasattr(node.targets[0], 'id'): key,lineno = node.targets[0].id,node.targets[0].lineno codestr = flines[lineno] match = re.match(f"^({key})\s*=\s*.*", codestr) if match and match.group(1) != '__all__': # only top level assignment d[key] = f'`{codestr}` {get_source_link(mod, lineno)}' return d
[ "def", "get_global_vars", "(", "mod", ")", ":", "# 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", "node", "in", "ast", ".", "walk", "(", "ast", ".", "parse", "(", "fstr", ")", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Assign", ")", "and", "hasattr", "(", "node", ".", "targets", "[", "0", "]", ",", "'id'", ")", ":", "key", ",", "lineno", "=", "node", ".", "targets", "[", "0", "]", ".", "id", ",", "node", ".", "targets", "[", "0", "]", ".", "lineno", "codestr", "=", "flines", "[", "lineno", "]", "match", "=", "re", ".", "match", "(", "f\"^({key})\\s*=\\s*.*\"", ",", "codestr", ")", "if", "match", "and", "match", ".", "group", "(", "1", ")", "!=", "'__all__'", ":", "# only top level assignment", "d", "[", "key", "]", "=", "f'`{codestr}` {get_source_link(mod, lineno)}'", "return", "d" ]
Return globally assigned variables.
[ "Return", "globally", "assigned", "variables", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L52-L66
20,710
fastai/fastai
fastai/gen_doc/gen_notebooks.py
execute_nb
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) as f: nb = nbformat.read(f, as_version=4) ep_class = ExecuteShowDocPreprocessor if show_doc_only else ExecutePreprocessor ep = ep_class(timeout=600, kernel_name='python3') metadata = metadata or {} ep.preprocess(nb, metadata) if save: with open(fname, 'wt') as f: nbformat.write(nb, f) NotebookNotary().sign(nb)
python
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) as f: nb = nbformat.read(f, as_version=4) ep_class = ExecuteShowDocPreprocessor if show_doc_only else ExecutePreprocessor ep = ep_class(timeout=600, kernel_name='python3') metadata = metadata or {} ep.preprocess(nb, metadata) if save: with open(fname, 'wt') as f: nbformat.write(nb, f) NotebookNotary().sign(nb)
[ "def", "execute_nb", "(", "fname", ",", "metadata", "=", "None", ",", "save", "=", "True", ",", "show_doc_only", "=", "False", ")", ":", "# Any module used in the notebook that isn't inside must be in the same directory as this script", "with", "open", "(", "fname", ")", "as", "f", ":", "nb", "=", "nbformat", ".", "read", "(", "f", ",", "as_version", "=", "4", ")", "ep_class", "=", "ExecuteShowDocPreprocessor", "if", "show_doc_only", "else", "ExecutePreprocessor", "ep", "=", "ep_class", "(", "timeout", "=", "600", ",", "kernel_name", "=", "'python3'", ")", "metadata", "=", "metadata", "or", "{", "}", "ep", ".", "preprocess", "(", "nb", ",", "metadata", ")", "if", "save", ":", "with", "open", "(", "fname", ",", "'wt'", ")", "as", "f", ":", "nbformat", ".", "write", "(", "nb", ",", "f", ")", "NotebookNotary", "(", ")", ".", "sign", "(", "nb", ")" ]
Execute notebook `fname` with `metadata` for preprocessing.
[ "Execute", "notebook", "fname", "with", "metadata", "for", "preprocessing", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L79-L89
20,711
fastai/fastai
fastai/gen_doc/gen_notebooks.py
create_module_page
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_cell = [get_md_cell(f'## Title for {strip_name} (use plain english, not module name!)'), get_md_cell('Type an introduction of the package here.')] cells = [get_code_cell(f'from fastai.gen_doc.nbdoc import *\nfrom {mod_name} import * ', True)] gvar_map = get_global_vars(mod) if gvar_map: cells.append(get_md_cell('### Global Variable Definitions:')) for name in get_exports(mod): if name in gvar_map: cells.append(get_md_cell(gvar_map[name])) for ft_name in get_ft_names(mod, include_inner=True): if not hasattr(mod, ft_name): warnings.warn(f"Module {strip_name} doesn't have a function named {ft_name}.") continue cells += _symbol_skeleton(ft_name) elt = getattr(mod, ft_name) nb['cells'] = init_cell + cells + [get_md_cell(UNDOC_HEADER)] doc_path = get_doc_path(mod, dest_path) write_nb(nb, doc_path, 'w' if force else 'x') execute_nb(doc_path) return doc_path
python
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_cell = [get_md_cell(f'## Title for {strip_name} (use plain english, not module name!)'), get_md_cell('Type an introduction of the package here.')] cells = [get_code_cell(f'from fastai.gen_doc.nbdoc import *\nfrom {mod_name} import * ', True)] gvar_map = get_global_vars(mod) if gvar_map: cells.append(get_md_cell('### Global Variable Definitions:')) for name in get_exports(mod): if name in gvar_map: cells.append(get_md_cell(gvar_map[name])) for ft_name in get_ft_names(mod, include_inner=True): if not hasattr(mod, ft_name): warnings.warn(f"Module {strip_name} doesn't have a function named {ft_name}.") continue cells += _symbol_skeleton(ft_name) elt = getattr(mod, ft_name) nb['cells'] = init_cell + cells + [get_md_cell(UNDOC_HEADER)] doc_path = get_doc_path(mod, dest_path) write_nb(nb, doc_path, 'w' if force else 'x') execute_nb(doc_path) return doc_path
[ "def", "create_module_page", "(", "mod", ",", "dest_path", ",", "force", "=", "False", ")", ":", "nb", "=", "get_empty_notebook", "(", ")", "mod_name", "=", "mod", ".", "__name__", "strip_name", "=", "strip_fastai", "(", "mod_name", ")", "init_cell", "=", "[", "get_md_cell", "(", "f'## Title for {strip_name} (use plain english, not module name!)'", ")", ",", "get_md_cell", "(", "'Type an introduction of the package here.'", ")", "]", "cells", "=", "[", "get_code_cell", "(", "f'from fastai.gen_doc.nbdoc import *\\nfrom {mod_name} import * '", ",", "True", ")", "]", "gvar_map", "=", "get_global_vars", "(", "mod", ")", "if", "gvar_map", ":", "cells", ".", "append", "(", "get_md_cell", "(", "'### Global Variable Definitions:'", ")", ")", "for", "name", "in", "get_exports", "(", "mod", ")", ":", "if", "name", "in", "gvar_map", ":", "cells", ".", "append", "(", "get_md_cell", "(", "gvar_map", "[", "name", "]", ")", ")", "for", "ft_name", "in", "get_ft_names", "(", "mod", ",", "include_inner", "=", "True", ")", ":", "if", "not", "hasattr", "(", "mod", ",", "ft_name", ")", ":", "warnings", ".", "warn", "(", "f\"Module {strip_name} doesn't have a function named {ft_name}.\"", ")", "continue", "cells", "+=", "_symbol_skeleton", "(", "ft_name", ")", "elt", "=", "getattr", "(", "mod", ",", "ft_name", ")", "nb", "[", "'cells'", "]", "=", "init_cell", "+", "cells", "+", "[", "get_md_cell", "(", "UNDOC_HEADER", ")", "]", "doc_path", "=", "get_doc_path", "(", "mod", ",", "dest_path", ")", "write_nb", "(", "nb", ",", "doc_path", ",", "'w'", "if", "force", "else", "'x'", ")", "execute_nb", "(", "doc_path", ")", "return", "doc_path" ]
Create the documentation notebook for module `mod_name` in path `dest_path`
[ "Create", "the", "documentation", "notebook", "for", "module", "mod_name", "in", "path", "dest_path" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L93-L117
20,712
fastai/fastai
fastai/gen_doc/gen_notebooks.py
get_module_names
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_dir.glob('*'), key=lambda x: (x.is_dir(), x.name), reverse=True) # directories first res = [f'{path_dir.name}'] for f in files: if f.is_dir() and f.name in exclude: continue # exclude directories if any([f.name.endswith(ex) for ex in exclude]): continue # exclude extensions if f.suffix == '.py': res.append(f'{path_dir.name}.{f.stem}') elif f.is_dir(): res += [f'{path_dir.name}.{name}' for name in get_module_names(f)] return res
python
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_dir.glob('*'), key=lambda x: (x.is_dir(), x.name), reverse=True) # directories first res = [f'{path_dir.name}'] for f in files: if f.is_dir() and f.name in exclude: continue # exclude directories if any([f.name.endswith(ex) for ex in exclude]): continue # exclude extensions if f.suffix == '.py': res.append(f'{path_dir.name}.{f.stem}') elif f.is_dir(): res += [f'{path_dir.name}.{name}' for name in get_module_names(f)] return res
[ "def", "get_module_names", "(", "path_dir", ",", "exclude", "=", "None", ")", ":", "if", "exclude", "is", "None", ":", "exclude", "=", "_default_exclude", "files", "=", "sorted", "(", "path_dir", ".", "glob", "(", "'*'", ")", ",", "key", "=", "lambda", "x", ":", "(", "x", ".", "is_dir", "(", ")", ",", "x", ".", "name", ")", ",", "reverse", "=", "True", ")", "# directories first", "res", "=", "[", "f'{path_dir.name}'", "]", "for", "f", "in", "files", ":", "if", "f", ".", "is_dir", "(", ")", "and", "f", ".", "name", "in", "exclude", ":", "continue", "# exclude directories", "if", "any", "(", "[", "f", ".", "name", ".", "endswith", "(", "ex", ")", "for", "ex", "in", "exclude", "]", ")", ":", "continue", "# exclude extensions", "if", "f", ".", "suffix", "==", "'.py'", ":", "res", ".", "append", "(", "f'{path_dir.name}.{f.stem}'", ")", "elif", "f", ".", "is_dir", "(", ")", ":", "res", "+=", "[", "f'{path_dir.name}.{name}'", "for", "name", "in", "get_module_names", "(", "f", ")", "]", "return", "res" ]
Search a given `path_dir` and return all the modules contained inside except those in `exclude`
[ "Search", "a", "given", "path_dir", "and", "return", "all", "the", "modules", "contained", "inside", "except", "those", "in", "exclude" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L121-L132
20,713
fastai/fastai
fastai/gen_doc/gen_notebooks.py
read_nb
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)
python
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)
[ "def", "read_nb", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "return", "nbformat", ".", "reads", "(", "f", ".", "read", "(", ")", ",", "as_version", "=", "4", ")" ]
Read a notebook in `fname` and return its corresponding json
[ "Read", "a", "notebook", "in", "fname", "and", "return", "its", "corresponding", "json" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L134-L136
20,714
fastai/fastai
fastai/gen_doc/gen_notebooks.py
read_nb_content
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']): doc_fns[match] = i return doc_fns
python
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']): doc_fns[match] = i return doc_fns
[ "def", "read_nb_content", "(", "cells", ",", "mod_name", ")", ":", "doc_fns", "=", "{", "}", "for", "i", ",", "cell", "in", "enumerate", "(", "cells", ")", ":", "if", "cell", "[", "'cell_type'", "]", "==", "'code'", ":", "for", "match", "in", "SHOW_DOC_RE", ".", "findall", "(", "cell", "[", "'source'", "]", ")", ":", "doc_fns", "[", "match", "]", "=", "i", "return", "doc_fns" ]
Build a dictionary containing the position of the `cells`.
[ "Build", "a", "dictionary", "containing", "the", "position", "of", "the", "cells", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L139-L146
20,715
fastai/fastai
fastai/gen_doc/gen_notebooks.py
link_markdown_cells
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, cell['source'])
python
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, cell['source'])
[ "def", "link_markdown_cells", "(", "cells", ",", "modules", ")", ":", "for", "i", ",", "cell", "in", "enumerate", "(", "cells", ")", ":", "if", "cell", "[", "'cell_type'", "]", "==", "'markdown'", ":", "cell", "[", "'source'", "]", "=", "link_docstring", "(", "modules", ",", "cell", "[", "'source'", "]", ")" ]
Create documentation links for all cells in markdown with backticks.
[ "Create", "documentation", "links", "for", "all", "cells", "in", "markdown", "with", "backticks", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L156-L160
20,716
fastai/fastai
fastai/gen_doc/gen_notebooks.py
get_insert_idx
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 else: return pos_dict[keys[i]]
python
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 else: return pos_dict[keys[i]]
[ "def", "get_insert_idx", "(", "pos_dict", ",", "name", ")", ":", "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", "else", ":", "return", "pos_dict", "[", "keys", "[", "i", "]", "]" ]
Return the position to insert a given function doc in a notebook.
[ "Return", "the", "position", "to", "insert", "a", "given", "function", "doc", "in", "a", "notebook", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L162-L167
20,717
fastai/fastai
fastai/gen_doc/gen_notebooks.py
update_pos
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 pos_dict
python
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 pos_dict
[ "def", "update_pos", "(", "pos_dict", ",", "start_key", ",", "nbr", "=", "2", ")", ":", "for", "key", ",", "idx", "in", "pos_dict", ".", "items", "(", ")", ":", "if", "str", ".", "lower", "(", "key", ")", ">=", "str", ".", "lower", "(", "start_key", ")", ":", "pos_dict", "[", "key", "]", "+=", "nbr", "return", "pos_dict" ]
Update the `pos_dict` by moving all positions after `start_key` by `nbr`.
[ "Update", "the", "pos_dict", "by", "moving", "all", "positions", "after", "start_key", "by", "nbr", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L169-L173
20,718
fastai/fastai
fastai/gen_doc/gen_notebooks.py
insert_cells
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_cell(ft_name), get_empty_cell()] else: cells.insert(idx, get_doc_cell(ft_name)) cells.insert(idx+1, get_empty_cell()) pos_dict = update_pos(pos_dict, ft_name, 2) return cells, pos_dict
python
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_cell(ft_name), get_empty_cell()] else: cells.insert(idx, get_doc_cell(ft_name)) cells.insert(idx+1, get_empty_cell()) pos_dict = update_pos(pos_dict, ft_name, 2) return cells, pos_dict
[ "def", "insert_cells", "(", "cells", ",", "pos_dict", ",", "ft_name", ",", "append", "=", "False", ")", ":", "idx", "=", "get_insert_idx", "(", "pos_dict", ",", "ft_name", ")", "if", "append", "or", "idx", "==", "-", "1", ":", "cells", "+=", "[", "get_doc_cell", "(", "ft_name", ")", ",", "get_empty_cell", "(", ")", "]", "else", ":", "cells", ".", "insert", "(", "idx", ",", "get_doc_cell", "(", "ft_name", ")", ")", "cells", ".", "insert", "(", "idx", "+", "1", ",", "get_empty_cell", "(", ")", ")", "pos_dict", "=", "update_pos", "(", "pos_dict", ",", "ft_name", ",", "2", ")", "return", "cells", ",", "pos_dict" ]
Insert the function doc `cells` at their correct position and updates `pos_dict`.
[ "Insert", "the", "function", "doc", "cells", "at", "their", "correct", "position", "and", "updates", "pos_dict", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L175-L183
20,719
fastai/fastai
fastai/gen_doc/gen_notebooks.py
update_nb_metadata
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} data = {k:v for (k,v) in data.items() if v is not None} # remove none values if not data: return nb['metadata']['jekyll'] = data write_nb(nb, nb_path) NotebookNotary().sign(nb)
python
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} data = {k:v for (k,v) in data.items() if v is not None} # remove none values if not data: return nb['metadata']['jekyll'] = data write_nb(nb, nb_path) NotebookNotary().sign(nb)
[ "def", "update_nb_metadata", "(", "nb_path", "=", "None", ",", "title", "=", "None", ",", "summary", "=", "None", ",", "keywords", "=", "'fastai'", ",", "overwrite", "=", "True", ",", "*", "*", "kwargs", ")", ":", "nb", "=", "read_nb", "(", "nb_path", ")", "data", "=", "{", "'title'", ":", "title", ",", "'summary'", ":", "summary", ",", "'keywords'", ":", "keywords", ",", "*", "*", "kwargs", "}", "data", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "data", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "# remove none values", "if", "not", "data", ":", "return", "nb", "[", "'metadata'", "]", "[", "'jekyll'", "]", "=", "data", "write_nb", "(", "nb", ",", "nb_path", ")", "NotebookNotary", "(", ")", ".", "sign", "(", "nb", ")" ]
Creates jekyll metadata for given notebook path.
[ "Creates", "jekyll", "metadata", "for", "given", "notebook", "path", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L204-L212
20,720
fastai/fastai
fastai/gen_doc/gen_notebooks.py
get_imported_modules
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" module_names = get_top_level_modules() nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell['source']) if cell['cell_type'] == 'code'] parts = nb_module_name.split('.') parent_modules = ['.'.join(parts[:(x+1)]) for x in range_of(parts)] # Imports parent modules - a.b.c = [a, a.b, a.b.c] all_modules = module_names + nb_imports + parent_modules mods = [import_mod(m, ignore_errors=True) for m in all_modules] return [m for m in mods if m is not None]
python
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" module_names = get_top_level_modules() nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell['source']) if cell['cell_type'] == 'code'] parts = nb_module_name.split('.') parent_modules = ['.'.join(parts[:(x+1)]) for x in range_of(parts)] # Imports parent modules - a.b.c = [a, a.b, a.b.c] all_modules = module_names + nb_imports + parent_modules mods = [import_mod(m, ignore_errors=True) for m in all_modules] return [m for m in mods if m is not None]
[ "def", "get_imported_modules", "(", "cells", ",", "nb_module_name", "=", "''", ")", ":", "module_names", "=", "get_top_level_modules", "(", ")", "nb_imports", "=", "[", "match", ".", "group", "(", "1", ")", "for", "cell", "in", "cells", "for", "match", "in", "IMPORT_RE", ".", "finditer", "(", "cell", "[", "'source'", "]", ")", "if", "cell", "[", "'cell_type'", "]", "==", "'code'", "]", "parts", "=", "nb_module_name", ".", "split", "(", "'.'", ")", "parent_modules", "=", "[", "'.'", ".", "join", "(", "parts", "[", ":", "(", "x", "+", "1", ")", "]", ")", "for", "x", "in", "range_of", "(", "parts", ")", "]", "# Imports parent modules - a.b.c = [a, a.b, a.b.c]", "all_modules", "=", "module_names", "+", "nb_imports", "+", "parent_modules", "mods", "=", "[", "import_mod", "(", "m", ",", "ignore_errors", "=", "True", ")", "for", "m", "in", "all_modules", "]", "return", "[", "m", "for", "m", "in", "mods", "if", "m", "is", "not", "None", "]" ]
Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority
[ "Finds", "all", "submodules", "of", "notebook", "-", "sorted", "by", "submodules", ">", "top", "level", "modules", ">", "manual", "imports", ".", "This", "gives", "notebook", "imports", "priority" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L221-L229
20,721
fastai/fastai
fastai/gen_doc/gen_notebooks.py
update_module_page
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(cells, get_imported_modules(cells, mod.__name__)) type_dict = read_nb_types(cells) gvar_map = get_global_vars(mod) for name in get_exports(mod): if name not in gvar_map: continue code = gvar_map[name] if name in type_dict: cells[type_dict[name]] = get_md_cell(code) else: cells.append(get_md_cell(code)) pos_dict = read_nb_content(cells, strip_name) ft_names = get_ft_names(mod, include_inner=True) new_fts = list(set(ft_names) - set(pos_dict.keys())) if new_fts: print(f'Found new fuctions for {mod}. Please document:\n{new_fts}') existing, undoc_cells, new_cells = parse_sections(cells) for ft_name in new_fts: new_cells.extend([get_doc_cell(ft_name), get_empty_cell()]) if len(new_cells) > 1: nb['cells'] = existing + undoc_cells + new_cells write_nb(nb, doc_path) return doc_path
python
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(cells, get_imported_modules(cells, mod.__name__)) type_dict = read_nb_types(cells) gvar_map = get_global_vars(mod) for name in get_exports(mod): if name not in gvar_map: continue code = gvar_map[name] if name in type_dict: cells[type_dict[name]] = get_md_cell(code) else: cells.append(get_md_cell(code)) pos_dict = read_nb_content(cells, strip_name) ft_names = get_ft_names(mod, include_inner=True) new_fts = list(set(ft_names) - set(pos_dict.keys())) if new_fts: print(f'Found new fuctions for {mod}. Please document:\n{new_fts}') existing, undoc_cells, new_cells = parse_sections(cells) for ft_name in new_fts: new_cells.extend([get_doc_cell(ft_name), get_empty_cell()]) if len(new_cells) > 1: nb['cells'] = existing + undoc_cells + new_cells write_nb(nb, doc_path) return doc_path
[ "def", "update_module_page", "(", "mod", ",", "dest_path", "=", "'.'", ")", ":", "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", "(", "cells", ",", "get_imported_modules", "(", "cells", ",", "mod", ".", "__name__", ")", ")", "type_dict", "=", "read_nb_types", "(", "cells", ")", "gvar_map", "=", "get_global_vars", "(", "mod", ")", "for", "name", "in", "get_exports", "(", "mod", ")", ":", "if", "name", "not", "in", "gvar_map", ":", "continue", "code", "=", "gvar_map", "[", "name", "]", "if", "name", "in", "type_dict", ":", "cells", "[", "type_dict", "[", "name", "]", "]", "=", "get_md_cell", "(", "code", ")", "else", ":", "cells", ".", "append", "(", "get_md_cell", "(", "code", ")", ")", "pos_dict", "=", "read_nb_content", "(", "cells", ",", "strip_name", ")", "ft_names", "=", "get_ft_names", "(", "mod", ",", "include_inner", "=", "True", ")", "new_fts", "=", "list", "(", "set", "(", "ft_names", ")", "-", "set", "(", "pos_dict", ".", "keys", "(", ")", ")", ")", "if", "new_fts", ":", "print", "(", "f'Found new fuctions for {mod}. Please document:\\n{new_fts}'", ")", "existing", ",", "undoc_cells", ",", "new_cells", "=", "parse_sections", "(", "cells", ")", "for", "ft_name", "in", "new_fts", ":", "new_cells", ".", "extend", "(", "[", "get_doc_cell", "(", "ft_name", ")", ",", "get_empty_cell", "(", ")", "]", ")", "if", "len", "(", "new_cells", ")", ">", "1", ":", "nb", "[", "'cells'", "]", "=", "existing", "+", "undoc_cells", "+", "new_cells", "write_nb", "(", "nb", ",", "doc_path", ")", "return", "doc_path" ]
Update the documentation notebook of a given module.
[ "Update", "the", "documentation", "notebook", "of", "a", "given", "module", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L262-L288
20,722
fastai/fastai
fastai/gen_doc/gen_notebooks.py
update_notebooks
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 modules reside in the fastai directory." from .convert2html import convert_nb source_path = Path(source_path) if source_path.is_file(): dest_path = source_path.parent if dest_path is None else Path(dest_path) html_path = dest_path/'..'/'docs' if html_path is None else Path(html_path) doc_path = source_path assert source_path.suffix == '.ipynb', 'Must update from notebook or module' if document_new_fns: mod = import_mod(get_module_from_notebook(source_path)) if not mod: print('Could not find module for path:', source_path) elif mod.__file__.endswith('__init__.py'): pass else: update_module_page(mod, dest_path) generate_missing_metadata(doc_path) if update_nb_links: print(f'Updating notebook {doc_path}. Please wait...') link_nb(doc_path) execute_nb(doc_path, {'metadata': {'path': doc_path.parent}}, show_doc_only=True) if update_html: check_nbconvert_version() html_fn = html_path/doc_path.with_suffix('.html').name if not force and html_fn.is_file(): in_mod = os.path.getmtime(doc_path) out_mod = os.path.getmtime(html_fn) if in_mod < out_mod: return convert_nb(doc_path, html_path) elif (source_path.name.startswith('fastai.')): # Do module update assert dest_path is not None, 'To update a module, you must specify a destination folder for where notebook resides' mod = import_mod(source_path.name) if not mod: return print('Could not find module for:', source_path) doc_path = Path(dest_path)/(strip_fastai(mod.__name__)+'.ipynb') if not doc_path.exists(): print('Notebook does not exist. Creating:', doc_path) create_module_page(mod, dest_path) update_notebooks(doc_path, dest_path=dest_path, update_html=update_html, document_new_fns=document_new_fns, update_nb_links=update_nb_links, html_path=html_path) elif source_path.is_dir(): for f in sorted(Path(source_path).glob('*.ipynb')): update_notebooks(f, dest_path=dest_path, update_html=update_html, document_new_fns=document_new_fns, update_nb_links=update_nb_links, html_path=html_path) else: print('Could not resolve source file:', source_path)
python
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 modules reside in the fastai directory." from .convert2html import convert_nb source_path = Path(source_path) if source_path.is_file(): dest_path = source_path.parent if dest_path is None else Path(dest_path) html_path = dest_path/'..'/'docs' if html_path is None else Path(html_path) doc_path = source_path assert source_path.suffix == '.ipynb', 'Must update from notebook or module' if document_new_fns: mod = import_mod(get_module_from_notebook(source_path)) if not mod: print('Could not find module for path:', source_path) elif mod.__file__.endswith('__init__.py'): pass else: update_module_page(mod, dest_path) generate_missing_metadata(doc_path) if update_nb_links: print(f'Updating notebook {doc_path}. Please wait...') link_nb(doc_path) execute_nb(doc_path, {'metadata': {'path': doc_path.parent}}, show_doc_only=True) if update_html: check_nbconvert_version() html_fn = html_path/doc_path.with_suffix('.html').name if not force and html_fn.is_file(): in_mod = os.path.getmtime(doc_path) out_mod = os.path.getmtime(html_fn) if in_mod < out_mod: return convert_nb(doc_path, html_path) elif (source_path.name.startswith('fastai.')): # Do module update assert dest_path is not None, 'To update a module, you must specify a destination folder for where notebook resides' mod = import_mod(source_path.name) if not mod: return print('Could not find module for:', source_path) doc_path = Path(dest_path)/(strip_fastai(mod.__name__)+'.ipynb') if not doc_path.exists(): print('Notebook does not exist. Creating:', doc_path) create_module_page(mod, dest_path) update_notebooks(doc_path, dest_path=dest_path, update_html=update_html, document_new_fns=document_new_fns, update_nb_links=update_nb_links, html_path=html_path) elif source_path.is_dir(): for f in sorted(Path(source_path).glob('*.ipynb')): update_notebooks(f, dest_path=dest_path, update_html=update_html, document_new_fns=document_new_fns, update_nb_links=update_nb_links, html_path=html_path) else: print('Could not resolve source file:', source_path)
[ "def", "update_notebooks", "(", "source_path", ",", "dest_path", "=", "None", ",", "update_html", "=", "True", ",", "document_new_fns", "=", "False", ",", "update_nb_links", "=", "True", ",", "html_path", "=", "None", ",", "force", "=", "False", ")", ":", "from", ".", "convert2html", "import", "convert_nb", "source_path", "=", "Path", "(", "source_path", ")", "if", "source_path", ".", "is_file", "(", ")", ":", "dest_path", "=", "source_path", ".", "parent", "if", "dest_path", "is", "None", "else", "Path", "(", "dest_path", ")", "html_path", "=", "dest_path", "/", "'..'", "/", "'docs'", "if", "html_path", "is", "None", "else", "Path", "(", "html_path", ")", "doc_path", "=", "source_path", "assert", "source_path", ".", "suffix", "==", "'.ipynb'", ",", "'Must update from notebook or module'", "if", "document_new_fns", ":", "mod", "=", "import_mod", "(", "get_module_from_notebook", "(", "source_path", ")", ")", "if", "not", "mod", ":", "print", "(", "'Could not find module for path:'", ",", "source_path", ")", "elif", "mod", ".", "__file__", ".", "endswith", "(", "'__init__.py'", ")", ":", "pass", "else", ":", "update_module_page", "(", "mod", ",", "dest_path", ")", "generate_missing_metadata", "(", "doc_path", ")", "if", "update_nb_links", ":", "print", "(", "f'Updating notebook {doc_path}. Please wait...'", ")", "link_nb", "(", "doc_path", ")", "execute_nb", "(", "doc_path", ",", "{", "'metadata'", ":", "{", "'path'", ":", "doc_path", ".", "parent", "}", "}", ",", "show_doc_only", "=", "True", ")", "if", "update_html", ":", "check_nbconvert_version", "(", ")", "html_fn", "=", "html_path", "/", "doc_path", ".", "with_suffix", "(", "'.html'", ")", ".", "name", "if", "not", "force", "and", "html_fn", ".", "is_file", "(", ")", ":", "in_mod", "=", "os", ".", "path", ".", "getmtime", "(", "doc_path", ")", "out_mod", "=", "os", ".", "path", ".", "getmtime", "(", "html_fn", ")", "if", "in_mod", "<", "out_mod", ":", "return", "convert_nb", "(", "doc_path", ",", "html_path", ")", "elif", "(", "source_path", ".", "name", ".", "startswith", "(", "'fastai.'", ")", ")", ":", "# Do module update", "assert", "dest_path", "is", "not", "None", ",", "'To update a module, you must specify a destination folder for where notebook resides'", "mod", "=", "import_mod", "(", "source_path", ".", "name", ")", "if", "not", "mod", ":", "return", "print", "(", "'Could not find module for:'", ",", "source_path", ")", "doc_path", "=", "Path", "(", "dest_path", ")", "/", "(", "strip_fastai", "(", "mod", ".", "__name__", ")", "+", "'.ipynb'", ")", "if", "not", "doc_path", ".", "exists", "(", ")", ":", "print", "(", "'Notebook does not exist. Creating:'", ",", "doc_path", ")", "create_module_page", "(", "mod", ",", "dest_path", ")", "update_notebooks", "(", "doc_path", ",", "dest_path", "=", "dest_path", ",", "update_html", "=", "update_html", ",", "document_new_fns", "=", "document_new_fns", ",", "update_nb_links", "=", "update_nb_links", ",", "html_path", "=", "html_path", ")", "elif", "source_path", ".", "is_dir", "(", ")", ":", "for", "f", "in", "sorted", "(", "Path", "(", "source_path", ")", ".", "glob", "(", "'*.ipynb'", ")", ")", ":", "update_notebooks", "(", "f", ",", "dest_path", "=", "dest_path", ",", "update_html", "=", "update_html", ",", "document_new_fns", "=", "document_new_fns", ",", "update_nb_links", "=", "update_nb_links", ",", "html_path", "=", "html_path", ")", "else", ":", "print", "(", "'Could not resolve source file:'", ",", "source_path", ")" ]
`source_path` can be a directory or a file. Assume all modules reside in the fastai directory.
[ "source_path", "can", "be", "a", "directory", "or", "a", "file", ".", "Assume", "all", "modules", "reside", "in", "the", "fastai", "directory", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L305-L350
20,723
fastai/fastai
fastai/text/models/awd_lstm.py
dropout_mask
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)
python
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)
[ "def", "dropout_mask", "(", "x", ":", "Tensor", ",", "sz", ":", "Collection", "[", "int", "]", ",", "p", ":", "float", ")", ":", "return", "x", ".", "new", "(", "*", "sz", ")", ".", "bernoulli_", "(", "1", "-", "p", ")", ".", "div_", "(", "1", "-", "p", ")" ]
Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element.
[ "Return", "a", "dropout", "mask", "of", "the", "same", "type", "as", "x", "size", "sz", "with", "probability", "p", "to", "cancel", "an", "element", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/awd_lstm.py#L13-L15
20,724
fastai/fastai
fastai/text/models/awd_lstm.py
WeightDropout._setweights
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)
python
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)
[ "def", "_setweights", "(", "self", ")", ":", "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", ")" ]
Apply dropout to the raw weights.
[ "Apply", "dropout", "to", "the", "raw", "weights", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/awd_lstm.py#L41-L45
20,725
fastai/fastai
fastai/text/models/awd_lstm.py
AWD_LSTM._one_hidden
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_()
python
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_()
[ "def", "_one_hidden", "(", "self", ",", "l", ":", "int", ")", "->", "Tensor", ":", "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_", "(", ")" ]
Return one hidden state.
[ "Return", "one", "hidden", "state", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/awd_lstm.py#L125-L128
20,726
fastai/fastai
fastai/text/models/awd_lstm.py
AWD_LSTM.reset
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.n_layers)]
python
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.n_layers)]
[ "def", "reset", "(", "self", ")", ":", "[", "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", ".", "n_layers", ")", "]" ]
Reset the hidden states.
[ "Reset", "the", "hidden", "states", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/awd_lstm.py#L135-L139
20,727
fastai/fastai
fastai/text/models/awd_lstm.py
TextClassificationInterpretation.show_top_losses
def show_top_losses(self, k:int, max_len:int=70)->None: """ 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. """ from IPython.display import display, HTML items = [] tl_val,tl_idx = self.top_losses() for i,idx in enumerate(tl_idx): if k <= 0: break k -= 1 tx,cl = self.data.dl(self.ds_type).dataset[idx] cl = cl.data classes = self.data.classes txt = ' '.join(tx.text.split(' ')[:max_len]) if max_len is not None else tx.text tmp = [txt, f'{classes[self.pred_class[idx]]}', f'{classes[cl]}', f'{self.losses[idx]:.2f}', f'{self.probs[idx][cl]:.2f}'] items.append(tmp) items = np.array(items) names = ['Text', 'Prediction', 'Actual', 'Loss', 'Probability'] df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
python
def show_top_losses(self, k:int, max_len:int=70)->None: """ 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. """ from IPython.display import display, HTML items = [] tl_val,tl_idx = self.top_losses() for i,idx in enumerate(tl_idx): if k <= 0: break k -= 1 tx,cl = self.data.dl(self.ds_type).dataset[idx] cl = cl.data classes = self.data.classes txt = ' '.join(tx.text.split(' ')[:max_len]) if max_len is not None else tx.text tmp = [txt, f'{classes[self.pred_class[idx]]}', f'{classes[cl]}', f'{self.losses[idx]:.2f}', f'{self.probs[idx][cl]:.2f}'] items.append(tmp) items = np.array(items) names = ['Text', 'Prediction', 'Actual', 'Loss', 'Probability'] df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
[ "def", "show_top_losses", "(", "self", ",", "k", ":", "int", ",", "max_len", ":", "int", "=", "70", ")", "->", "None", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "items", "=", "[", "]", "tl_val", ",", "tl_idx", "=", "self", ".", "top_losses", "(", ")", "for", "i", ",", "idx", "in", "enumerate", "(", "tl_idx", ")", ":", "if", "k", "<=", "0", ":", "break", "k", "-=", "1", "tx", ",", "cl", "=", "self", ".", "data", ".", "dl", "(", "self", ".", "ds_type", ")", ".", "dataset", "[", "idx", "]", "cl", "=", "cl", ".", "data", "classes", "=", "self", ".", "data", ".", "classes", "txt", "=", "' '", ".", "join", "(", "tx", ".", "text", ".", "split", "(", "' '", ")", "[", ":", "max_len", "]", ")", "if", "max_len", "is", "not", "None", "else", "tx", ".", "text", "tmp", "=", "[", "txt", ",", "f'{classes[self.pred_class[idx]]}'", ",", "f'{classes[cl]}'", ",", "f'{self.losses[idx]:.2f}'", ",", "f'{self.probs[idx][cl]:.2f}'", "]", "items", ".", "append", "(", "tmp", ")", "items", "=", "np", ".", "array", "(", "items", ")", "names", "=", "[", "'Text'", ",", "'Prediction'", ",", "'Actual'", ",", "'Loss'", ",", "'Probability'", "]", "df", "=", "pd", ".", "DataFrame", "(", "{", "n", ":", "items", "[", ":", ",", "i", "]", "for", "i", ",", "n", "in", "enumerate", "(", "names", ")", "}", ",", "columns", "=", "names", ")", "with", "pd", ".", "option_context", "(", "'display.max_colwidth'", ",", "-", "1", ")", ":", "display", "(", "HTML", "(", "df", ".", "to_html", "(", "index", "=", "False", ")", ")", ")" ]
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.
[ "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", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/awd_lstm.py#L246-L268
20,728
fastai/fastai
fastai/callbacks/general_sched.py
GeneralScheduler.on_train_begin
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.scheds for p in self.phases] self.opt = self.learn.opt for k,v in self.scheds[0].items(): v.restart() self.opt.set_stat(k, v.start) self.idx_s = 0 return res
python
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.scheds for p in self.phases] self.opt = self.learn.opt for k,v in self.scheds[0].items(): v.restart() self.opt.set_stat(k, v.start) self.idx_s = 0 return res
[ "def", "on_train_begin", "(", "self", ",", "epoch", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "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", ".", "scheds", "for", "p", "in", "self", ".", "phases", "]", "self", ".", "opt", "=", "self", ".", "learn", ".", "opt", "for", "k", ",", "v", "in", "self", ".", "scheds", "[", "0", "]", ".", "items", "(", ")", ":", "v", ".", "restart", "(", ")", "self", ".", "opt", ".", "set_stat", "(", "k", ",", "v", ".", "start", ")", "self", ".", "idx_s", "=", "0", "return", "res" ]
Initialize the schedulers for training.
[ "Initialize", "the", "schedulers", "for", "training", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/general_sched.py#L24-L34
20,729
fastai/fastai
fastai/callbacks/general_sched.py
GeneralScheduler.on_batch_end
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, 'stop_epoch': True} sched = self.scheds[self.idx_s] for k,v in sched.items(): self.opt.set_stat(k, v.step()) if list(sched.values())[0].is_done: self.idx_s += 1
python
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, 'stop_epoch': True} sched = self.scheds[self.idx_s] for k,v in sched.items(): self.opt.set_stat(k, v.step()) if list(sched.values())[0].is_done: self.idx_s += 1
[ "def", "on_batch_end", "(", "self", ",", "train", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "train", ":", "if", "self", ".", "idx_s", ">=", "len", "(", "self", ".", "scheds", ")", ":", "return", "{", "'stop_training'", ":", "True", ",", "'stop_epoch'", ":", "True", "}", "sched", "=", "self", ".", "scheds", "[", "self", ".", "idx_s", "]", "for", "k", ",", "v", "in", "sched", ".", "items", "(", ")", ":", "self", ".", "opt", ".", "set_stat", "(", "k", ",", "v", ".", "step", "(", ")", ")", "if", "list", "(", "sched", ".", "values", "(", ")", ")", "[", "0", "]", ".", "is_done", ":", "self", ".", "idx_s", "+=", "1" ]
Take a step in lr,mom sched, start next stepper when the current one is complete.
[ "Take", "a", "step", "in", "lr", "mom", "sched", "start", "next", "stepper", "when", "the", "current", "one", "is", "complete", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/general_sched.py#L40-L46
20,730
fastai/fastai
fastai/torch_core.py
tensor
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; TODO: create repro and report if is_listy(x) and len(x)==0: return tensor(0) res = torch.tensor(x) if is_listy(x) else as_tensor(x) if res.dtype is torch.int32: warn('Tensor is int32: upgrading to int64; for better performance use int64 input') return res.long() return res
python
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; TODO: create repro and report if is_listy(x) and len(x)==0: return tensor(0) res = torch.tensor(x) if is_listy(x) else as_tensor(x) if res.dtype is torch.int32: warn('Tensor is int32: upgrading to int64; for better performance use int64 input') return res.long() return res
[ "def", "tensor", "(", "x", ":", "Any", ",", "*", "rest", ")", "->", "Tensor", ":", "if", "len", "(", "rest", ")", ":", "x", "=", "(", "x", ",", ")", "+", "rest", "# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report", "if", "is_listy", "(", "x", ")", "and", "len", "(", "x", ")", "==", "0", ":", "return", "tensor", "(", "0", ")", "res", "=", "torch", ".", "tensor", "(", "x", ")", "if", "is_listy", "(", "x", ")", "else", "as_tensor", "(", "x", ")", "if", "res", ".", "dtype", "is", "torch", ".", "int32", ":", "warn", "(", "'Tensor is int32: upgrading to int64; for better performance use int64 input'", ")", "return", "res", ".", "long", "(", ")", "return", "res" ]
Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly.
[ "Like", "torch", ".", "as_tensor", "but", "handle", "lists", "too", "and", "can", "pass", "multiple", "vector", "elements", "directly", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L76-L85
20,731
fastai/fastai
fastai/torch_core.py
to_detach
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.detach() return b.cpu() if cpu else b
python
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.detach() return b.cpu() if cpu else b
[ "def", "to_detach", "(", "b", ":", "Tensors", ",", "cpu", ":", "bool", "=", "True", ")", ":", "if", "is_listy", "(", "b", ")", ":", "return", "[", "to_detach", "(", "o", ",", "cpu", ")", "for", "o", "in", "b", "]", "if", "not", "isinstance", "(", "b", ",", "Tensor", ")", ":", "return", "b", "b", "=", "b", ".", "detach", "(", ")", "return", "b", ".", "cpu", "(", ")", "if", "cpu", "else", "b" ]
Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`.
[ "Recursively", "detach", "lists", "of", "tensors", "in", "b", ";", "put", "them", "on", "the", "CPU", "if", "cpu", "=", "True", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L91-L96
20,732
fastai/fastai
fastai/torch_core.py
to_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
python
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
[ "def", "to_data", "(", "b", ":", "ItemsList", ")", ":", "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 items in `b ` to their wrapped data.
[ "Recursively", "map", "lists", "of", "items", "in", "b", "to", "their", "wrapped", "data", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L98-L101
20,733
fastai/fastai
fastai/torch_core.py
to_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
python
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
[ "def", "to_cpu", "(", "b", ":", "ItemsList", ")", ":", "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 the cpu.
[ "Recursively", "map", "lists", "of", "tensors", "in", "b", "to", "the", "cpu", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L103-L106
20,734
fastai/fastai
fastai/torch_core.py
to_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(device, non_blocking=True)
python
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(device, non_blocking=True)
[ "def", "to_device", "(", "b", ":", "Tensors", ",", "device", ":", "torch", ".", "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", "(", "device", ",", "non_blocking", "=", "True", ")" ]
Recursively put `b` on `device`.
[ "Recursively", "put", "b", "on", "device", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L118-L123
20,735
fastai/fastai
fastai/torch_core.py
data_collate
def data_collate(batch:ItemsList)->Tensor: "Convert `batch` items to tensor data." return torch.utils.data.dataloader.default_collate(to_data(batch))
python
def data_collate(batch:ItemsList)->Tensor: "Convert `batch` items to tensor data." return torch.utils.data.dataloader.default_collate(to_data(batch))
[ "def", "data_collate", "(", "batch", ":", "ItemsList", ")", "->", "Tensor", ":", "return", "torch", ".", "utils", ".", "data", ".", "dataloader", ".", "default_collate", "(", "to_data", "(", "batch", ")", ")" ]
Convert `batch` items to tensor data.
[ "Convert", "batch", "items", "to", "tensor", "data", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L125-L127
20,736
fastai/fastai
fastai/torch_core.py
requires_grad
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 not ps: return None if b is None: return ps[0].requires_grad for p in ps: p.requires_grad=b
python
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 not ps: return None if b is None: return ps[0].requires_grad for p in ps: p.requires_grad=b
[ "def", "requires_grad", "(", "m", ":", "nn", ".", "Module", ",", "b", ":", "Optional", "[", "bool", "]", "=", "None", ")", "->", "Optional", "[", "bool", "]", ":", "ps", "=", "list", "(", "m", ".", "parameters", "(", ")", ")", "if", "not", "ps", ":", "return", "None", "if", "b", "is", "None", ":", "return", "ps", "[", "0", "]", ".", "requires_grad", "for", "p", "in", "ps", ":", "p", ".", "requires_grad", "=", "b" ]
If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b`
[ "If", "b", "is", "not", "set", "return", "requires_grad", "of", "first", "param", "else", "set", "requires_grad", "on", "all", "params", "as", "b" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L129-L134
20,737
fastai/fastai
fastai/torch_core.py
trainable_params
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
python
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
[ "def", "trainable_params", "(", "m", ":", "nn", ".", "Module", ")", "->", "ParamList", ":", "res", "=", "filter", "(", "lambda", "p", ":", "p", ".", "requires_grad", ",", "m", ".", "parameters", "(", ")", ")", "return", "res" ]
Return list of trainable params in `m`.
[ "Return", "list", "of", "trainable", "params", "in", "m", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L136-L139
20,738
fastai/fastai
fastai/torch_core.py
children_and_parameters
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()],[]) for p in m.parameters(): if id(p) not in children_p: children.append(ParameterModule(p)) return children
python
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()],[]) for p in m.parameters(): if id(p) not in children_p: children.append(ParameterModule(p)) return children
[ "def", "children_and_parameters", "(", "m", ":", "nn", ".", "Module", ")", ":", "children", "=", "list", "(", "m", ".", "children", "(", ")", ")", "children_p", "=", "sum", "(", "[", "[", "id", "(", "p", ")", "for", "p", "in", "c", ".", "parameters", "(", ")", "]", "for", "c", "in", "m", ".", "children", "(", ")", "]", ",", "[", "]", ")", "for", "p", "in", "m", ".", "parameters", "(", ")", ":", "if", "id", "(", "p", ")", "not", "in", "children_p", ":", "children", ".", "append", "(", "ParameterModule", "(", "p", ")", ")", "return", "children" ]
Return the children of `m` and its direct parameters not registered in modules.
[ "Return", "the", "children", "of", "m", "and", "its", "direct", "parameters", "not", "registered", "in", "modules", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L161-L167
20,739
fastai/fastai
fastai/torch_core.py
split_model_idx
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 [nn.Sequential(*layers[i:j]) for i,j in zip(idxs[:-1],idxs[1:])]
python
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 [nn.Sequential(*layers[i:j]) for i,j in zip(idxs[:-1],idxs[1:])]
[ "def", "split_model_idx", "(", "model", ":", "nn", ".", "Module", ",", "idxs", ":", "Collection", "[", "int", "]", ")", "->", "ModuleList", ":", "layers", "=", "flatten_model", "(", "model", ")", "if", "idxs", "[", "0", "]", "!=", "0", ":", "idxs", "=", "[", "0", "]", "+", "idxs", "if", "idxs", "[", "-", "1", "]", "!=", "len", "(", "layers", ")", ":", "idxs", ".", "append", "(", "len", "(", "layers", ")", ")", "return", "[", "nn", ".", "Sequential", "(", "*", "layers", "[", "i", ":", "j", "]", ")", "for", "i", ",", "j", "in", "zip", "(", "idxs", "[", ":", "-", "1", "]", ",", "idxs", "[", "1", ":", "]", ")", "]" ]
Split `model` according to the indexes in `idxs`.
[ "Split", "model", "according", "to", "the", "indexes", "in", "idxs", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L179-L184
20,740
fastai/fastai
fastai/torch_core.py
split_model
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) idxs = [layers.index(first_layer(s)) for s in splits] return split_model_idx(model, idxs) return [nn.Sequential(*s) for s in splits]
python
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) idxs = [layers.index(first_layer(s)) for s in splits] return split_model_idx(model, idxs) return [nn.Sequential(*s) for s in splits]
[ "def", "split_model", "(", "model", ":", "nn", ".", "Module", "=", "None", ",", "splits", ":", "Collection", "[", "Union", "[", "nn", ".", "Module", ",", "ModuleList", "]", "]", "=", "None", ")", ":", "splits", "=", "listify", "(", "splits", ")", "if", "isinstance", "(", "splits", "[", "0", "]", ",", "nn", ".", "Module", ")", ":", "layers", "=", "flatten_model", "(", "model", ")", "idxs", "=", "[", "layers", ".", "index", "(", "first_layer", "(", "s", ")", ")", "for", "s", "in", "splits", "]", "return", "split_model_idx", "(", "model", ",", "idxs", ")", "return", "[", "nn", ".", "Sequential", "(", "*", "s", ")", "for", "s", "in", "splits", "]" ]
Split `model` according to the layers in `splits`.
[ "Split", "model", "according", "to", "the", "layers", "in", "splits", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L186-L193
20,741
fastai/fastai
fastai/torch_core.py
set_bn_eval
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)
python
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)
[ "def", "set_bn_eval", "(", "m", ":", "nn", ".", "Module", ")", "->", "None", ":", "for", "l", "in", "m", ".", "children", "(", ")", ":", "if", "isinstance", "(", "l", ",", "bn_types", ")", "and", "not", "next", "(", "l", ".", "parameters", "(", ")", ")", ".", "requires_grad", ":", "l", ".", "eval", "(", ")", "set_bn_eval", "(", "l", ")" ]
Set bn layers in eval mode for all recursive children of `m`.
[ "Set", "bn", "layers", "in", "eval", "mode", "for", "all", "recursive", "children", "of", "m", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L216-L221
20,742
fastai/fastai
fastai/torch_core.py
bn2float
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
python
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
[ "def", "bn2float", "(", "module", ":", "nn", ".", "Module", ")", "->", "nn", ".", "Module", ":", "if", "isinstance", "(", "module", ",", "torch", ".", "nn", ".", "modules", ".", "batchnorm", ".", "_BatchNorm", ")", ":", "module", ".", "float", "(", ")", "for", "child", "in", "module", ".", "children", "(", ")", ":", "bn2float", "(", "child", ")", "return", "module" ]
If `module` is batchnorm don't use half precision.
[ "If", "module", "is", "batchnorm", "don", "t", "use", "half", "precision", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L227-L231
20,743
fastai/fastai
fastai/torch_core.py
init_default
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.bias.data.fill_(0.) return m
python
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.bias.data.fill_(0.) return m
[ "def", "init_default", "(", "m", ":", "nn", ".", "Module", ",", "func", ":", "LayerFunc", "=", "nn", ".", "init", ".", "kaiming_normal_", ")", "->", "None", ":", "if", "func", ":", "if", "hasattr", "(", "m", ",", "'weight'", ")", ":", "func", "(", "m", ".", "weight", ")", "if", "hasattr", "(", "m", ",", "'bias'", ")", "and", "hasattr", "(", "m", ".", "bias", ",", "'data'", ")", ":", "m", ".", "bias", ".", "data", ".", "fill_", "(", "0.", ")", "return", "m" ]
Initialize `m` weights with `func` and set `bias` to 0.
[ "Initialize", "m", "weights", "with", "func", "and", "set", "bias", "to", "0", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L237-L242
20,744
fastai/fastai
fastai/torch_core.py
cond_init
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)
python
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)
[ "def", "cond_init", "(", "m", ":", "nn", ".", "Module", ",", "init_func", ":", "LayerFunc", ")", ":", "if", "(", "not", "isinstance", "(", "m", ",", "bn_types", ")", ")", "and", "requires_grad", "(", "m", ")", ":", "init_default", "(", "m", ",", "init_func", ")" ]
Initialize the non-batchnorm layers of `m` with `init_func`.
[ "Initialize", "the", "non", "-", "batchnorm", "layers", "of", "m", "with", "init_func", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L244-L246
20,745
fastai/fastai
fastai/torch_core.py
apply_init
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))
python
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))
[ "def", "apply_init", "(", "m", ",", "init_func", ":", "LayerFunc", ")", ":", "apply_leaf", "(", "m", ",", "partial", "(", "cond_init", ",", "init_func", "=", "init_func", ")", ")" ]
Initialize all non-batchnorm layers of `m` with `init_func`.
[ "Initialize", "all", "non", "-", "batchnorm", "layers", "of", "m", "with", "init_func", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L254-L256
20,746
fastai/fastai
fastai/torch_core.py
in_channels
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')
python
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')
[ "def", "in_channels", "(", "m", ":", "nn", ".", "Module", ")", "->", "List", "[", "int", "]", ":", "for", "l", "in", "flatten_model", "(", "m", ")", ":", "if", "hasattr", "(", "l", ",", "'weight'", ")", ":", "return", "l", ".", "weight", ".", "shape", "[", "1", "]", "raise", "Exception", "(", "'No weight layer'", ")" ]
Return the shape of the first weight layer in `m`.
[ "Return", "the", "shape", "of", "the", "first", "weight", "layer", "in", "m", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L258-L262
20,747
fastai/fastai
fastai/torch_core.py
model_type
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)
python
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)
[ "def", "model_type", "(", "dtype", ")", ":", "return", "(", "torch", ".", "float32", "if", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "floating", ")", "else", "torch", ".", "int64", "if", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "integer", ")", "else", "None", ")" ]
Return the torch type corresponding to `dtype`.
[ "Return", "the", "torch", "type", "corresponding", "to", "dtype", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L292-L296
20,748
fastai/fastai
fastai/torch_core.py
np2model_tensor
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)
python
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)
[ "def", "np2model_tensor", "(", "a", ")", ":", "dtype", "=", "model_type", "(", "a", ".", "dtype", ")", "res", "=", "as_tensor", "(", "a", ")", "if", "not", "dtype", ":", "return", "res", "return", "res", ".", "type", "(", "dtype", ")" ]
Tranform numpy array `a` to a tensor of the same type.
[ "Tranform", "numpy", "array", "a", "to", "a", "tensor", "of", "the", "same", "type", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L298-L303
20,749
fastai/fastai
fastai/torch_core.py
_pca
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])
python
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])
[ "def", "_pca", "(", "x", ",", "k", "=", "2", ")", ":", "x", "=", "x", "-", "torch", ".", "mean", "(", "x", ",", "0", ")", "U", ",", "S", ",", "V", "=", "torch", ".", "svd", "(", "x", ".", "t", "(", ")", ")", "return", "torch", ".", "mm", "(", "x", ",", "U", "[", ":", ",", ":", "k", "]", ")" ]
Compute PCA of `x` with `k` dimensions.
[ "Compute", "PCA", "of", "x", "with", "k", "dimensions", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L305-L309
20,750
fastai/fastai
fastai/torch_core.py
grab_idx
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() for o in x] if is_listy(x) else x[:,i].cpu())
python
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() for o in x] if is_listy(x) else x[:,i].cpu())
[ "def", "grab_idx", "(", "x", ",", "i", ",", "batch_first", ":", "bool", "=", "True", ")", ":", "if", "batch_first", ":", "return", "(", "[", "o", "[", "i", "]", ".", "cpu", "(", ")", "for", "o", "in", "x", "]", "if", "is_listy", "(", "x", ")", "else", "x", "[", "i", "]", ".", "cpu", "(", ")", ")", "else", ":", "return", "(", "[", "o", "[", ":", ",", "i", "]", ".", "cpu", "(", ")", "for", "o", "in", "x", "]", "if", "is_listy", "(", "x", ")", "else", "x", "[", ":", ",", "i", "]", ".", "cpu", "(", ")", ")" ]
Grab the `i`-th batch in `x`, `batch_first` stating the batch dimension.
[ "Grab", "the", "i", "-", "th", "batch", "in", "x", "batch_first", "stating", "the", "batch", "dimension", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L328-L331
20,751
fastai/fastai
fastai/torch_core.py
logit_
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_()
python
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_()
[ "def", "logit_", "(", "x", ":", "Tensor", ")", "->", "Tensor", ":", "x", ".", "clamp_", "(", "1e-7", ",", "1", "-", "1e-7", ")", "return", "(", "x", ".", "reciprocal_", "(", ")", ".", "sub_", "(", "1", ")", ")", ".", "log_", "(", ")", ".", "neg_", "(", ")" ]
Inplace logit of `x`, clamped to avoid inf
[ "Inplace", "logit", "of", "x", "clamped", "to", "avoid", "inf" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L338-L341
20,752
fastai/fastai
fastai/torch_core.py
try_int
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) if isinstance(o, collections.Sized) or getattr(o,'__array_interface__',False): return o try: return int(o) except: return o
python
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) if isinstance(o, collections.Sized) or getattr(o,'__array_interface__',False): return o try: return int(o) except: return o
[ "def", "try_int", "(", "o", ":", "Any", ")", "->", "Any", ":", "# 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", ")", "if", "isinstance", "(", "o", ",", "collections", ".", "Sized", ")", "or", "getattr", "(", "o", ",", "'__array_interface__'", ",", "False", ")", ":", "return", "o", "try", ":", "return", "int", "(", "o", ")", "except", ":", "return", "o" ]
Try to convert `o` to int, default to `o` if not possible.
[ "Try", "to", "convert", "o", "to", "int", "default", "to", "o", "if", "not", "possible", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L365-L371
20,753
fastai/fastai
fastai/torch_core.py
get_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
python
def get_model(model:nn.Module): "Return the model maybe wrapped inside `model`." return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model
[ "def", "get_model", "(", "model", ":", "nn", ".", "Module", ")", ":", "return", "model", ".", "module", "if", "isinstance", "(", "model", ",", "(", "DistributedDataParallel", ",", "nn", ".", "DataParallel", ")", ")", "else", "model" ]
Return the model maybe wrapped inside `model`.
[ "Return", "the", "model", "maybe", "wrapped", "inside", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L373-L375
20,754
fastai/fastai
fastai/torch_core.py
flatten_check
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), f"Expected output and target to have the same number of elements but got {len(out)} and {len(targ)}." return out,targ
python
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), f"Expected output and target to have the same number of elements but got {len(out)} and {len(targ)}." return out,targ
[ "def", "flatten_check", "(", "out", ":", "Tensor", ",", "targ", ":", "Tensor", ")", "->", "Tensor", ":", "out", ",", "targ", "=", "out", ".", "contiguous", "(", ")", ".", "view", "(", "-", "1", ")", ",", "targ", ".", "contiguous", "(", ")", ".", "view", "(", "-", "1", ")", "assert", "len", "(", "out", ")", "==", "len", "(", "targ", ")", ",", "f\"Expected output and target to have the same number of elements but got {len(out)} and {len(targ)}.\"", "return", "out", ",", "targ" ]
Check that `out` and `targ` have the same number of elements and flatten them.
[ "Check", "that", "out", "and", "targ", "have", "the", "same", "number", "of", "elements", "and", "flatten", "them", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L377-L381
20,755
fastai/fastai
fastai/torch_core.py
remove_module_load
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
python
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
[ "def", "remove_module_load", "(", "state_dict", ")", ":", "new_state_dict", "=", "OrderedDict", "(", ")", "for", "k", ",", "v", "in", "state_dict", ".", "items", "(", ")", ":", "new_state_dict", "[", "k", "[", "7", ":", "]", "]", "=", "v", "return", "new_state_dict" ]
create new OrderedDict that does not contain `module.`
[ "create", "new", "OrderedDict", "that", "does", "not", "contain", "module", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L388-L392
20,756
fastai/fastai
fastai/torch_core.py
add_metrics
def add_metrics(last_metrics:Collection[Rank0Tensor], mets:Union[Rank0Tensor, Collection[Rank0Tensor]]): "Return a dictionary for updating `last_metrics` with `mets`." last_metrics,mets = listify(last_metrics),listify(mets) return {'last_metrics': last_metrics + mets}
python
def add_metrics(last_metrics:Collection[Rank0Tensor], mets:Union[Rank0Tensor, Collection[Rank0Tensor]]): "Return a dictionary for updating `last_metrics` with `mets`." last_metrics,mets = listify(last_metrics),listify(mets) return {'last_metrics': last_metrics + mets}
[ "def", "add_metrics", "(", "last_metrics", ":", "Collection", "[", "Rank0Tensor", "]", ",", "mets", ":", "Union", "[", "Rank0Tensor", ",", "Collection", "[", "Rank0Tensor", "]", "]", ")", ":", "last_metrics", ",", "mets", "=", "listify", "(", "last_metrics", ")", ",", "listify", "(", "mets", ")", "return", "{", "'last_metrics'", ":", "last_metrics", "+", "mets", "}" ]
Return a dictionary for updating `last_metrics` with `mets`.
[ "Return", "a", "dictionary", "for", "updating", "last_metrics", "with", "mets", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L402-L405
20,757
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._get_new_batch
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]: "Retrieves new batch of DatasetType, and detaches it." return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False)
python
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]: "Retrieves new batch of DatasetType, and detaches it." return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False)
[ "def", "_get_new_batch", "(", "self", ",", "ds_type", ":", "DatasetType", ")", "->", "Collection", "[", "Tensor", "]", ":", "return", "self", ".", "learn", ".", "data", ".", "one_batch", "(", "ds_type", "=", "ds_type", ",", "detach", "=", "True", ",", "denorm", "=", "False", ",", "cpu", "=", "False", ")" ]
Retrieves new batch of DatasetType, and detaches it.
[ "Retrieves", "new", "batch", "of", "DatasetType", "and", "detaches", "it", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L40-L42
20,758
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._update_batches_if_needed
def _update_batches_if_needed(self)->None: "one_batch function is extremely slow with large datasets. This is caching the result as an optimization." if self.learn.data.valid_dl is None: return # Running learning rate finder, so return update_batches = self.data is not self.learn.data if not update_batches: return self.data = self.learn.data self.trn_batch = self._get_new_batch(ds_type=DatasetType.Train) self.val_batch = self._get_new_batch(ds_type=DatasetType.Valid)
python
def _update_batches_if_needed(self)->None: "one_batch function is extremely slow with large datasets. This is caching the result as an optimization." if self.learn.data.valid_dl is None: return # Running learning rate finder, so return update_batches = self.data is not self.learn.data if not update_batches: return self.data = self.learn.data self.trn_batch = self._get_new_batch(ds_type=DatasetType.Train) self.val_batch = self._get_new_batch(ds_type=DatasetType.Valid)
[ "def", "_update_batches_if_needed", "(", "self", ")", "->", "None", ":", "if", "self", ".", "learn", ".", "data", ".", "valid_dl", "is", "None", ":", "return", "# Running learning rate finder, so return", "update_batches", "=", "self", ".", "data", "is", "not", "self", ".", "learn", ".", "data", "if", "not", "update_batches", ":", "return", "self", ".", "data", "=", "self", ".", "learn", ".", "data", "self", ".", "trn_batch", "=", "self", ".", "_get_new_batch", "(", "ds_type", "=", "DatasetType", ".", "Train", ")", "self", ".", "val_batch", "=", "self", ".", "_get_new_batch", "(", "ds_type", "=", "DatasetType", ".", "Valid", ")" ]
one_batch function is extremely slow with large datasets. This is caching the result as an optimization.
[ "one_batch", "function", "is", "extremely", "slow", "with", "large", "datasets", ".", "This", "is", "caching", "the", "result", "as", "an", "optimization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L44-L51
20,759
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_scalar
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
python
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
[ "def", "_write_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ",", "iteration", ":", "int", ")", "->", "None", ":", "tag", "=", "self", ".", "metrics_root", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", "tag", ",", "scalar_value", "=", "scalar_value", ",", "global_step", "=", "iteration", ")" ]
Writes single scalar value to Tensorboard.
[ "Writes", "single", "scalar", "value", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L67-L70
20,760
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_metrics
def _write_metrics(self, iteration:int, last_metrics:MetricsList, start_idx:int=2)->None: "Writes training metrics to Tensorboard." recorder = self.learn.recorder for i, name in enumerate(recorder.names[start_idx:]): if last_metrics is None or len(last_metrics) < i+1: return scalar_value = last_metrics[i] self._write_scalar(name=name, scalar_value=scalar_value, iteration=iteration)
python
def _write_metrics(self, iteration:int, last_metrics:MetricsList, start_idx:int=2)->None: "Writes training metrics to Tensorboard." recorder = self.learn.recorder for i, name in enumerate(recorder.names[start_idx:]): if last_metrics is None or len(last_metrics) < i+1: return scalar_value = last_metrics[i] self._write_scalar(name=name, scalar_value=scalar_value, iteration=iteration)
[ "def", "_write_metrics", "(", "self", ",", "iteration", ":", "int", ",", "last_metrics", ":", "MetricsList", ",", "start_idx", ":", "int", "=", "2", ")", "->", "None", ":", "recorder", "=", "self", ".", "learn", ".", "recorder", "for", "i", ",", "name", "in", "enumerate", "(", "recorder", ".", "names", "[", "start_idx", ":", "]", ")", ":", "if", "last_metrics", "is", "None", "or", "len", "(", "last_metrics", ")", "<", "i", "+", "1", ":", "return", "scalar_value", "=", "last_metrics", "[", "i", "]", "self", ".", "_write_scalar", "(", "name", "=", "name", ",", "scalar_value", "=", "scalar_value", ",", "iteration", "=", "iteration", ")" ]
Writes training metrics to Tensorboard.
[ "Writes", "training", "metrics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L73-L79
20,761
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter.on_epoch_end
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None: "Callback function that writes epoch end appropriate data to Tensorboard." self._write_metrics(iteration=iteration, last_metrics=last_metrics)
python
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None: "Callback function that writes epoch end appropriate data to Tensorboard." self._write_metrics(iteration=iteration, last_metrics=last_metrics)
[ "def", "on_epoch_end", "(", "self", ",", "last_metrics", ":", "MetricsList", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "_write_metrics", "(", "iteration", "=", "iteration", ",", "last_metrics", "=", "last_metrics", ")" ]
Callback function that writes epoch end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "epoch", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L99-L101
20,762
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_gen_model_stats
def _write_gen_model_stats(self, iteration:int)->None: "Writes gradient statistics for generator to Tensorboard." generator = self.learn.gan_trainer.generator self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats') self.gen_stats_updated = True
python
def _write_gen_model_stats(self, iteration:int)->None: "Writes gradient statistics for generator to Tensorboard." generator = self.learn.gan_trainer.generator self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats') self.gen_stats_updated = True
[ "def", "_write_gen_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "generator", "=", "self", ".", "learn", ".", "gan_trainer", ".", "generator", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "generator", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "self", ".", "tbwriter", ",", "name", "=", "'gen_model_stats'", ")", "self", ".", "gen_stats_updated", "=", "True" ]
Writes gradient statistics for generator to Tensorboard.
[ "Writes", "gradient", "statistics", "for", "generator", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L120-L124
20,763
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_critic_model_stats
def _write_critic_model_stats(self, iteration:int)->None: "Writes gradient statistics for critic to Tensorboard." critic = self.learn.gan_trainer.critic self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats') self.crit_stats_updated = True
python
def _write_critic_model_stats(self, iteration:int)->None: "Writes gradient statistics for critic to Tensorboard." critic = self.learn.gan_trainer.critic self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats') self.crit_stats_updated = True
[ "def", "_write_critic_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "critic", "=", "self", ".", "learn", ".", "gan_trainer", ".", "critic", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "critic", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "self", ".", "tbwriter", ",", "name", "=", "'crit_model_stats'", ")", "self", ".", "crit_stats_updated", "=", "True" ]
Writes gradient statistics for critic to Tensorboard.
[ "Writes", "gradient", "statistics", "for", "critic", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L126-L130
20,764
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_images
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard." trainer = self.learn.gan_trainer #TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way? gen_mode = trainer.gen_mode try: trainer.switch(gen_mode=True) self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter) finally: trainer.switch(gen_mode=gen_mode)
python
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard." trainer = self.learn.gan_trainer #TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way? gen_mode = trainer.gen_mode try: trainer.switch(gen_mode=True) self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter) finally: trainer.switch(gen_mode=gen_mode)
[ "def", "_write_images", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "trainer", "=", "self", ".", "learn", ".", "gan_trainer", "#TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way?", "gen_mode", "=", "trainer", ".", "gen_mode", "try", ":", "trainer", ".", "switch", "(", "gen_mode", "=", "True", ")", "self", ".", "img_gen_vis", ".", "write", "(", "learn", "=", "self", ".", "learn", ",", "trn_batch", "=", "self", ".", "trn_batch", ",", "val_batch", "=", "self", ".", "val_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "self", ".", "tbwriter", ")", "finally", ":", "trainer", ".", "switch", "(", "gen_mode", "=", "gen_mode", ")" ]
Writes model generated, original and real images to Tensorboard.
[ "Writes", "model", "generated", "original", "and", "real", "images", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L147-L156
20,765
fastai/fastai
fastai/callbacks/tensorboard.py
ImageGenTensorboardWriter._write_images
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard" self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter)
python
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard" self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter)
[ "def", "_write_images", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "self", ".", "img_gen_vis", ".", "write", "(", "learn", "=", "self", ".", "learn", ",", "trn_batch", "=", "self", ".", "trn_batch", ",", "val_batch", "=", "self", ".", "val_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "self", ".", "tbwriter", ")" ]
Writes model generated, original and real images to Tensorboard
[ "Writes", "model", "generated", "original", "and", "real", "images", "to", "Tensorboard" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L182-L185
20,766
fastai/fastai
fastai/callbacks/tensorboard.py
AsyncTBWriter.request_write
def request_write(self, request: TBWriteRequest)->None: "Queues up an asynchronous write request to Tensorboard." if self.stop_request.isSet(): return self.queue.put(request)
python
def request_write(self, request: TBWriteRequest)->None: "Queues up an asynchronous write request to Tensorboard." if self.stop_request.isSet(): return self.queue.put(request)
[ "def", "request_write", "(", "self", ",", "request", ":", "TBWriteRequest", ")", "->", "None", ":", "if", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "return", "self", ".", "queue", ".", "put", "(", "request", ")" ]
Queues up an asynchronous write request to Tensorboard.
[ "Queues", "up", "an", "asynchronous", "write", "request", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L216-L219
20,767
fastai/fastai
fastai/callbacks/tensorboard.py
AsyncTBWriter._queue_processor
def _queue_processor(self)->None: "Processes queued up write requests asynchronously to Tensorboard." while not self.stop_request.isSet(): while not self.queue.empty(): if self.stop_request.isSet(): return request = self.queue.get() request.write() sleep(0.2)
python
def _queue_processor(self)->None: "Processes queued up write requests asynchronously to Tensorboard." while not self.stop_request.isSet(): while not self.queue.empty(): if self.stop_request.isSet(): return request = self.queue.get() request.write() sleep(0.2)
[ "def", "_queue_processor", "(", "self", ")", "->", "None", ":", "while", "not", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "while", "not", "self", ".", "queue", ".", "empty", "(", ")", ":", "if", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "return", "request", "=", "self", ".", "queue", ".", "get", "(", ")", "request", ".", "write", "(", ")", "sleep", "(", "0.2", ")" ]
Processes queued up write requests asynchronously to Tensorboard.
[ "Processes", "queued", "up", "write", "requests", "asynchronously", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L221-L228
20,768
fastai/fastai
fastai/callbacks/tensorboard.py
ModelImageSet.get_list_from_model
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]: "Factory method to convert a batch of model images to a list of ModelImageSet." image_sets = [] x,y = batch[0],batch[1] preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True) for orig_px, real_px, gen in zip(x,y,preds): orig, real = Image(px=orig_px), Image(px=real_px) image_set = ModelImageSet(orig=orig, real=real, gen=gen) image_sets.append(image_set) return image_sets
python
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]: "Factory method to convert a batch of model images to a list of ModelImageSet." image_sets = [] x,y = batch[0],batch[1] preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True) for orig_px, real_px, gen in zip(x,y,preds): orig, real = Image(px=orig_px), Image(px=real_px) image_set = ModelImageSet(orig=orig, real=real, gen=gen) image_sets.append(image_set) return image_sets
[ "def", "get_list_from_model", "(", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", ",", "batch", ":", "Tuple", ")", "->", "[", "]", ":", "image_sets", "=", "[", "]", "x", ",", "y", "=", "batch", "[", "0", "]", ",", "batch", "[", "1", "]", "preds", "=", "learn", ".", "pred_batch", "(", "ds_type", "=", "ds_type", ",", "batch", "=", "(", "x", ",", "y", ")", ",", "reconstruct", "=", "True", ")", "for", "orig_px", ",", "real_px", ",", "gen", "in", "zip", "(", "x", ",", "y", ",", "preds", ")", ":", "orig", ",", "real", "=", "Image", "(", "px", "=", "orig_px", ")", ",", "Image", "(", "px", "=", "real_px", ")", "image_set", "=", "ModelImageSet", "(", "orig", "=", "orig", ",", "real", "=", "real", ",", "gen", "=", "gen", ")", "image_sets", ".", "append", "(", "image_set", ")", "return", "image_sets" ]
Factory method to convert a batch of model images to a list of ModelImageSet.
[ "Factory", "method", "to", "convert", "a", "batch", "of", "model", "images", "to", "a", "list", "of", "ModelImageSet", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L248-L257
20,769
fastai/fastai
fastai/callbacks/tensorboard.py
HistogramTBRequest._write_histogram
def _write_histogram(self, param_name:str, values)->None: "Writes single model histogram to Tensorboard." tag = self.name + '/weights/' + param_name self.tbwriter.add_histogram(tag=tag, values=values, global_step=self.iteration)
python
def _write_histogram(self, param_name:str, values)->None: "Writes single model histogram to Tensorboard." tag = self.name + '/weights/' + param_name self.tbwriter.add_histogram(tag=tag, values=values, global_step=self.iteration)
[ "def", "_write_histogram", "(", "self", ",", "param_name", ":", "str", ",", "values", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/weights/'", "+", "param_name", "self", ".", "tbwriter", ".", "add_histogram", "(", "tag", "=", "tag", ",", "values", "=", "values", ",", "global_step", "=", "self", ".", "iteration", ")" ]
Writes single model histogram to Tensorboard.
[ "Writes", "single", "model", "histogram", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L268-L271
20,770
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._add_gradient_scalar
def _add_gradient_scalar(self, name:str, scalar_value)->None: "Writes a single scalar value for a gradient statistic to Tensorboard." tag = self.name + '/gradients/' + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration)
python
def _add_gradient_scalar(self, name:str, scalar_value)->None: "Writes a single scalar value for a gradient statistic to Tensorboard." tag = self.name + '/gradients/' + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration)
[ "def", "_add_gradient_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/gradients/'", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", "tag", ",", "scalar_value", "=", "scalar_value", ",", "global_step", "=", "self", ".", "iteration", ")" ]
Writes a single scalar value for a gradient statistic to Tensorboard.
[ "Writes", "a", "single", "scalar", "value", "for", "a", "gradient", "statistic", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L294-L297
20,771
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_avg_norm
def _write_avg_norm(self, norms:[])->None: "Writes the average norm of the gradients to Tensorboard." avg_norm = sum(norms)/len(self.gradients) self._add_gradient_scalar('avg_norm', scalar_value=avg_norm)
python
def _write_avg_norm(self, norms:[])->None: "Writes the average norm of the gradients to Tensorboard." avg_norm = sum(norms)/len(self.gradients) self._add_gradient_scalar('avg_norm', scalar_value=avg_norm)
[ "def", "_write_avg_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "avg_norm", "=", "sum", "(", "norms", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'avg_norm'", ",", "scalar_value", "=", "avg_norm", ")" ]
Writes the average norm of the gradients to Tensorboard.
[ "Writes", "the", "average", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L299-L302
20,772
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_median_norm
def _write_median_norm(self, norms:[])->None: "Writes the median norm of the gradients to Tensorboard." median_norm = statistics.median(norms) self._add_gradient_scalar('median_norm', scalar_value=median_norm)
python
def _write_median_norm(self, norms:[])->None: "Writes the median norm of the gradients to Tensorboard." median_norm = statistics.median(norms) self._add_gradient_scalar('median_norm', scalar_value=median_norm)
[ "def", "_write_median_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "median_norm", "=", "statistics", ".", "median", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'median_norm'", ",", "scalar_value", "=", "median_norm", ")" ]
Writes the median norm of the gradients to Tensorboard.
[ "Writes", "the", "median", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L304-L307
20,773
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_max_norm
def _write_max_norm(self, norms:[])->None: "Writes the maximum norm of the gradients to Tensorboard." max_norm = max(norms) self._add_gradient_scalar('max_norm', scalar_value=max_norm)
python
def _write_max_norm(self, norms:[])->None: "Writes the maximum norm of the gradients to Tensorboard." max_norm = max(norms) self._add_gradient_scalar('max_norm', scalar_value=max_norm)
[ "def", "_write_max_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "max_norm", "=", "max", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'max_norm'", ",", "scalar_value", "=", "max_norm", ")" ]
Writes the maximum norm of the gradients to Tensorboard.
[ "Writes", "the", "maximum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L309-L312
20,774
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_min_norm
def _write_min_norm(self, norms:[])->None: "Writes the minimum norm of the gradients to Tensorboard." min_norm = min(norms) self._add_gradient_scalar('min_norm', scalar_value=min_norm)
python
def _write_min_norm(self, norms:[])->None: "Writes the minimum norm of the gradients to Tensorboard." min_norm = min(norms) self._add_gradient_scalar('min_norm', scalar_value=min_norm)
[ "def", "_write_min_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "min_norm", "=", "min", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'min_norm'", ",", "scalar_value", "=", "min_norm", ")" ]
Writes the minimum norm of the gradients to Tensorboard.
[ "Writes", "the", "minimum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L314-L317
20,775
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_num_zeros
def _write_num_zeros(self)->None: "Writes the number of zeroes in the gradients to Tensorboard." gradient_nps = [to_np(x.data) for x in self.gradients] num_zeros = sum((np.asarray(x) == 0.0).sum() for x in gradient_nps) self._add_gradient_scalar('num_zeros', scalar_value=num_zeros)
python
def _write_num_zeros(self)->None: "Writes the number of zeroes in the gradients to Tensorboard." gradient_nps = [to_np(x.data) for x in self.gradients] num_zeros = sum((np.asarray(x) == 0.0).sum() for x in gradient_nps) self._add_gradient_scalar('num_zeros', scalar_value=num_zeros)
[ "def", "_write_num_zeros", "(", "self", ")", "->", "None", ":", "gradient_nps", "=", "[", "to_np", "(", "x", ".", "data", ")", "for", "x", "in", "self", ".", "gradients", "]", "num_zeros", "=", "sum", "(", "(", "np", ".", "asarray", "(", "x", ")", "==", "0.0", ")", ".", "sum", "(", ")", "for", "x", "in", "gradient_nps", ")", "self", ".", "_add_gradient_scalar", "(", "'num_zeros'", ",", "scalar_value", "=", "num_zeros", ")" ]
Writes the number of zeroes in the gradients to Tensorboard.
[ "Writes", "the", "number", "of", "zeroes", "in", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L319-L323
20,776
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_avg_gradient
def _write_avg_gradient(self)->None: "Writes the average of the gradients to Tensorboard." avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients) self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient)
python
def _write_avg_gradient(self)->None: "Writes the average of the gradients to Tensorboard." avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients) self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient)
[ "def", "_write_avg_gradient", "(", "self", ")", "->", "None", ":", "avg_gradient", "=", "sum", "(", "x", ".", "data", ".", "mean", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'avg_gradient'", ",", "scalar_value", "=", "avg_gradient", ")" ]
Writes the average of the gradients to Tensorboard.
[ "Writes", "the", "average", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L325-L328
20,777
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_median_gradient
def _write_median_gradient(self)->None: "Writes the median of the gradients to Tensorboard." median_gradient = statistics.median(x.data.median() for x in self.gradients) self._add_gradient_scalar('median_gradient', scalar_value=median_gradient)
python
def _write_median_gradient(self)->None: "Writes the median of the gradients to Tensorboard." median_gradient = statistics.median(x.data.median() for x in self.gradients) self._add_gradient_scalar('median_gradient', scalar_value=median_gradient)
[ "def", "_write_median_gradient", "(", "self", ")", "->", "None", ":", "median_gradient", "=", "statistics", ".", "median", "(", "x", ".", "data", ".", "median", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'median_gradient'", ",", "scalar_value", "=", "median_gradient", ")" ]
Writes the median of the gradients to Tensorboard.
[ "Writes", "the", "median", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L330-L333
20,778
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_max_gradient
def _write_max_gradient(self)->None: "Writes the maximum of the gradients to Tensorboard." max_gradient = max(x.data.max() for x in self.gradients) self._add_gradient_scalar('max_gradient', scalar_value=max_gradient)
python
def _write_max_gradient(self)->None: "Writes the maximum of the gradients to Tensorboard." max_gradient = max(x.data.max() for x in self.gradients) self._add_gradient_scalar('max_gradient', scalar_value=max_gradient)
[ "def", "_write_max_gradient", "(", "self", ")", "->", "None", ":", "max_gradient", "=", "max", "(", "x", ".", "data", ".", "max", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'max_gradient'", ",", "scalar_value", "=", "max_gradient", ")" ]
Writes the maximum of the gradients to Tensorboard.
[ "Writes", "the", "maximum", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L335-L338
20,779
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_min_gradient
def _write_min_gradient(self)->None: "Writes the minimum of the gradients to Tensorboard." min_gradient = min(x.data.min() for x in self.gradients) self._add_gradient_scalar('min_gradient', scalar_value=min_gradient)
python
def _write_min_gradient(self)->None: "Writes the minimum of the gradients to Tensorboard." min_gradient = min(x.data.min() for x in self.gradients) self._add_gradient_scalar('min_gradient', scalar_value=min_gradient)
[ "def", "_write_min_gradient", "(", "self", ")", "->", "None", ":", "min_gradient", "=", "min", "(", "x", ".", "data", ".", "min", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'min_gradient'", ",", "scalar_value", "=", "min_gradient", ")" ]
Writes the minimum of the gradients to Tensorboard.
[ "Writes", "the", "minimum", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L340-L343
20,780
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest.write
def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] self._write_avg_norm(norms=norms) self._write_median_norm(norms=norms) self._write_max_norm(norms=norms) self._write_min_norm(norms=norms) self._write_num_zeros() self._write_avg_gradient() self._write_median_gradient() self._write_max_gradient() self._write_min_gradient()
python
def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] self._write_avg_norm(norms=norms) self._write_median_norm(norms=norms) self._write_max_norm(norms=norms) self._write_min_norm(norms=norms) self._write_num_zeros() self._write_avg_gradient() self._write_median_gradient() self._write_max_gradient() self._write_min_gradient()
[ "def", "write", "(", "self", ")", "->", "None", ":", "if", "len", "(", "self", ".", "gradients", ")", "==", "0", ":", "return", "norms", "=", "[", "x", ".", "data", ".", "norm", "(", ")", "for", "x", "in", "self", ".", "gradients", "]", "self", ".", "_write_avg_norm", "(", "norms", "=", "norms", ")", "self", ".", "_write_median_norm", "(", "norms", "=", "norms", ")", "self", ".", "_write_max_norm", "(", "norms", "=", "norms", ")", "self", ".", "_write_min_norm", "(", "norms", "=", "norms", ")", "self", ".", "_write_num_zeros", "(", ")", "self", ".", "_write_avg_gradient", "(", ")", "self", ".", "_write_median_gradient", "(", ")", "self", ".", "_write_max_gradient", "(", ")", "self", ".", "_write_min_gradient", "(", ")" ]
Writes model gradient statistics to Tensorboard.
[ "Writes", "model", "gradient", "statistics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L345-L357
20,781
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBRequest._write_images
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + ' ' + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
python
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + ' ' + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
[ "def", "_write_images", "(", "self", ",", "name", ":", "str", ",", "images", ":", "[", "Tensor", "]", ")", "->", "None", ":", "tag", "=", "self", ".", "ds_type", ".", "name", "+", "' '", "+", "name", "self", ".", "tbwriter", ".", "add_image", "(", "tag", "=", "tag", ",", "img_tensor", "=", "vutils", ".", "make_grid", "(", "images", ",", "normalize", "=", "True", ")", ",", "global_step", "=", "self", ".", "iteration", ")" ]
Writes list of images as tensors to Tensorboard.
[ "Writes", "list", "of", "images", "as", "tensors", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L373-L376
20,782
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBWriter.write
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
python
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
[ "def", "write", "(", "self", ",", "learn", ":", "Learner", ",", "trn_batch", ":", "Tuple", ",", "val_batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ")", "->", "None", ":", "self", ".", "_write_for_dstype", "(", "learn", "=", "learn", ",", "batch", "=", "val_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "DatasetType", ".", "Valid", ")", "self", ".", "_write_for_dstype", "(", "learn", "=", "learn", ",", "batch", "=", "trn_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "DatasetType", ".", "Train", ")" ]
Writes training and validation batch images to Tensorboard.
[ "Writes", "training", "and", "validation", "batch", "images", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L399-L402
20,783
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBWriter._write_for_dstype
def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetType to Tensorboard." request = ImageTBRequest(learn=learn, batch=batch, iteration=iteration, tbwriter=tbwriter, ds_type=ds_type) asyncTBWriter.request_write(request)
python
def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetType to Tensorboard." request = ImageTBRequest(learn=learn, batch=batch, iteration=iteration, tbwriter=tbwriter, ds_type=ds_type) asyncTBWriter.request_write(request)
[ "def", "_write_for_dstype", "(", "self", ",", "learn", ":", "Learner", ",", "batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ",", "ds_type", ":", "DatasetType", ")", "->", "None", ":", "request", "=", "ImageTBRequest", "(", "learn", "=", "learn", ",", "batch", "=", "batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "ds_type", ")", "asyncTBWriter", ".", "request_write", "(", "request", ")" ]
Writes batch images of specified DatasetType to Tensorboard.
[ "Writes", "batch", "images", "of", "specified", "DatasetType", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L404-L407
20,784
fastai/fastai
fastai/callbacks/tensorboard.py
GraphTBRequest.write
def write(self)->None: "Writes single model graph to Tensorboard." self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
python
def write(self)->None: "Writes single model graph to Tensorboard." self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
[ "def", "write", "(", "self", ")", "->", "None", ":", "self", ".", "tbwriter", ".", "add_graph", "(", "model", "=", "self", ".", "model", ",", "input_to_model", "=", "self", ".", "input_to_model", ")" ]
Writes single model graph to Tensorboard.
[ "Writes", "single", "model", "graph", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L415-L417
20,785
fastai/fastai
fastai/callbacks/tensorboard.py
GraphTBWriter.write
def write(self, model:nn.Module, tbwriter:SummaryWriter, input_to_model:torch.Tensor)->None: "Writes model graph to Tensorboard." request = GraphTBRequest(model=model, tbwriter=tbwriter, input_to_model=input_to_model) asyncTBWriter.request_write(request)
python
def write(self, model:nn.Module, tbwriter:SummaryWriter, input_to_model:torch.Tensor)->None: "Writes model graph to Tensorboard." request = GraphTBRequest(model=model, tbwriter=tbwriter, input_to_model=input_to_model) asyncTBWriter.request_write(request)
[ "def", "write", "(", "self", ",", "model", ":", "nn", ".", "Module", ",", "tbwriter", ":", "SummaryWriter", ",", "input_to_model", ":", "torch", ".", "Tensor", ")", "->", "None", ":", "request", "=", "GraphTBRequest", "(", "model", "=", "model", ",", "tbwriter", "=", "tbwriter", ",", "input_to_model", "=", "input_to_model", ")", "asyncTBWriter", ".", "request_write", "(", "request", ")" ]
Writes model graph to Tensorboard.
[ "Writes", "model", "graph", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L421-L424
20,786
fastai/fastai
old/fastai/lm_rnn.py
repackage_var
def repackage_var(h): """Wraps h in new Variables, to detach them from their history.""" if IS_TORCH_04: return h.detach() if type(h) == torch.Tensor else tuple(repackage_var(v) for v in h) else: return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)
python
def repackage_var(h): """Wraps h in new Variables, to detach them from their history.""" if IS_TORCH_04: return h.detach() if type(h) == torch.Tensor else tuple(repackage_var(v) for v in h) else: return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)
[ "def", "repackage_var", "(", "h", ")", ":", "if", "IS_TORCH_04", ":", "return", "h", ".", "detach", "(", ")", "if", "type", "(", "h", ")", "==", "torch", ".", "Tensor", "else", "tuple", "(", "repackage_var", "(", "v", ")", "for", "v", "in", "h", ")", "else", ":", "return", "Variable", "(", "h", ".", "data", ")", "if", "type", "(", "h", ")", "==", "Variable", "else", "tuple", "(", "repackage_var", "(", "v", ")", "for", "v", "in", "h", ")" ]
Wraps h in new Variables, to detach them from their history.
[ "Wraps", "h", "in", "new", "Variables", "to", "detach", "them", "from", "their", "history", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L20-L23
20,787
fastai/fastai
old/fastai/lm_rnn.py
get_language_model
def get_language_model(n_tok, emb_sz, n_hid, n_layers, pad_token, dropout=0.4, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5, tie_weights=True, qrnn=False, bias=False): """Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN_Encoder is used to instantiate the weights for the LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model """ rnn_enc = RNN_Encoder(n_tok, emb_sz, n_hid=n_hid, n_layers=n_layers, pad_token=pad_token, dropouth=dropouth, dropouti=dropouti, dropoute=dropoute, wdrop=wdrop, qrnn=qrnn) enc = rnn_enc.encoder if tie_weights else None return SequentialRNN(rnn_enc, LinearDecoder(n_tok, emb_sz, dropout, tie_encoder=enc, bias=bias))
python
def get_language_model(n_tok, emb_sz, n_hid, n_layers, pad_token, dropout=0.4, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5, tie_weights=True, qrnn=False, bias=False): """Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN_Encoder is used to instantiate the weights for the LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model """ rnn_enc = RNN_Encoder(n_tok, emb_sz, n_hid=n_hid, n_layers=n_layers, pad_token=pad_token, dropouth=dropouth, dropouti=dropouti, dropoute=dropoute, wdrop=wdrop, qrnn=qrnn) enc = rnn_enc.encoder if tie_weights else None return SequentialRNN(rnn_enc, LinearDecoder(n_tok, emb_sz, dropout, tie_encoder=enc, bias=bias))
[ "def", "get_language_model", "(", "n_tok", ",", "emb_sz", ",", "n_hid", ",", "n_layers", ",", "pad_token", ",", "dropout", "=", "0.4", ",", "dropouth", "=", "0.3", ",", "dropouti", "=", "0.5", ",", "dropoute", "=", "0.1", ",", "wdrop", "=", "0.5", ",", "tie_weights", "=", "True", ",", "qrnn", "=", "False", ",", "bias", "=", "False", ")", ":", "rnn_enc", "=", "RNN_Encoder", "(", "n_tok", ",", "emb_sz", ",", "n_hid", "=", "n_hid", ",", "n_layers", "=", "n_layers", ",", "pad_token", "=", "pad_token", ",", "dropouth", "=", "dropouth", ",", "dropouti", "=", "dropouti", ",", "dropoute", "=", "dropoute", ",", "wdrop", "=", "wdrop", ",", "qrnn", "=", "qrnn", ")", "enc", "=", "rnn_enc", ".", "encoder", "if", "tie_weights", "else", "None", "return", "SequentialRNN", "(", "rnn_enc", ",", "LinearDecoder", "(", "n_tok", ",", "emb_sz", ",", "dropout", ",", "tie_encoder", "=", "enc", ",", "bias", "=", "bias", ")", ")" ]
Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN_Encoder is used to instantiate the weights for the LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model
[ "Returns", "a", "SequentialRNN", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L204-L238
20,788
fastai/fastai
fastai/text/transform.py
replace_rep
def replace_rep(t:str) -> str: "Replace repetitions at the character level in `t`." def _replace_rep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' re_rep = re.compile(r'(\S)(\1{3,})') return re_rep.sub(_replace_rep, t)
python
def replace_rep(t:str) -> str: "Replace repetitions at the character level in `t`." def _replace_rep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' re_rep = re.compile(r'(\S)(\1{3,})') return re_rep.sub(_replace_rep, t)
[ "def", "replace_rep", "(", "t", ":", "str", ")", "->", "str", ":", "def", "_replace_rep", "(", "m", ":", "Collection", "[", "str", "]", ")", "->", "str", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f' {TK_REP} {len(cc)+1} {c} '", "re_rep", "=", "re", ".", "compile", "(", "r'(\\S)(\\1{3,})'", ")", "return", "re_rep", ".", "sub", "(", "_replace_rep", ",", "t", ")" ]
Replace repetitions at the character level in `t`.
[ "Replace", "repetitions", "at", "the", "character", "level", "in", "t", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L42-L48
20,789
fastai/fastai
fastai/text/transform.py
replace_wrep
def replace_wrep(t:str) -> str: "Replace word repetitions in `t`." def _replace_wrep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_WREP} {len(cc.split())+1} {c} ' re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})') return re_wrep.sub(_replace_wrep, t)
python
def replace_wrep(t:str) -> str: "Replace word repetitions in `t`." def _replace_wrep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_WREP} {len(cc.split())+1} {c} ' re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})') return re_wrep.sub(_replace_wrep, t)
[ "def", "replace_wrep", "(", "t", ":", "str", ")", "->", "str", ":", "def", "_replace_wrep", "(", "m", ":", "Collection", "[", "str", "]", ")", "->", "str", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f' {TK_WREP} {len(cc.split())+1} {c} '", "re_wrep", "=", "re", ".", "compile", "(", "r'(\\b\\w+\\W+)(\\1{3,})'", ")", "return", "re_wrep", ".", "sub", "(", "_replace_wrep", ",", "t", ")" ]
Replace word repetitions in `t`.
[ "Replace", "word", "repetitions", "in", "t", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L50-L56
20,790
fastai/fastai
fastai/text/transform.py
fix_html
def fix_html(x:str) -> str: "List of replacements from html strings in `x`." re1 = re.compile(r' +') x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace( 'nbsp;', ' ').replace('#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace( '<br />', "\n").replace('\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace( ' @-@ ','-').replace(' @,@ ',',').replace('\\', ' \\ ') return re1.sub(' ', html.unescape(x))
python
def fix_html(x:str) -> str: "List of replacements from html strings in `x`." re1 = re.compile(r' +') x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace( 'nbsp;', ' ').replace('#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace( '<br />', "\n").replace('\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace( ' @-@ ','-').replace(' @,@ ',',').replace('\\', ' \\ ') return re1.sub(' ', html.unescape(x))
[ "def", "fix_html", "(", "x", ":", "str", ")", "->", "str", ":", "re1", "=", "re", ".", "compile", "(", "r' +'", ")", "x", "=", "x", ".", "replace", "(", "'#39;'", ",", "\"'\"", ")", ".", "replace", "(", "'amp;'", ",", "'&'", ")", ".", "replace", "(", "'#146;'", ",", "\"'\"", ")", ".", "replace", "(", "'nbsp;'", ",", "' '", ")", ".", "replace", "(", "'#36;'", ",", "'$'", ")", ".", "replace", "(", "'\\\\n'", ",", "\"\\n\"", ")", ".", "replace", "(", "'quot;'", ",", "\"'\"", ")", ".", "replace", "(", "'<br />'", ",", "\"\\n\"", ")", ".", "replace", "(", "'\\\\\"'", ",", "'\"'", ")", ".", "replace", "(", "'<unk>'", ",", "UNK", ")", ".", "replace", "(", "' @.@ '", ",", "'.'", ")", ".", "replace", "(", "' @-@ '", ",", "'-'", ")", ".", "replace", "(", "' @,@ '", ",", "','", ")", ".", "replace", "(", "'\\\\'", ",", "' \\\\ '", ")", "return", "re1", ".", "sub", "(", "' '", ",", "html", ".", "unescape", "(", "x", ")", ")" ]
List of replacements from html strings in `x`.
[ "List", "of", "replacements", "from", "html", "strings", "in", "x", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L58-L65
20,791
fastai/fastai
fastai/text/transform.py
replace_all_caps
def replace_all_caps(x:Collection[str]) -> Collection[str]: "Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before." res = [] for t in x: if t.isupper() and len(t) > 1: res.append(TK_UP); res.append(t.lower()) else: res.append(t) return res
python
def replace_all_caps(x:Collection[str]) -> Collection[str]: "Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before." res = [] for t in x: if t.isupper() and len(t) > 1: res.append(TK_UP); res.append(t.lower()) else: res.append(t) return res
[ "def", "replace_all_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "res", "=", "[", "]", "for", "t", "in", "x", ":", "if", "t", ".", "isupper", "(", ")", "and", "len", "(", "t", ")", ">", "1", ":", "res", ".", "append", "(", "TK_UP", ")", "res", ".", "append", "(", "t", ".", "lower", "(", ")", ")", "else", ":", "res", ".", "append", "(", "t", ")", "return", "res" ]
Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before.
[ "Replace", "tokens", "in", "ALL", "CAPS", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_UP", "before", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L67-L73
20,792
fastai/fastai
fastai/text/transform.py
deal_caps
def deal_caps(x:Collection[str]) -> Collection[str]: "Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before." res = [] for t in x: if t == '': continue if t[0].isupper() and len(t) > 1 and t[1:].islower(): res.append(TK_MAJ) res.append(t.lower()) return res
python
def deal_caps(x:Collection[str]) -> Collection[str]: "Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before." res = [] for t in x: if t == '': continue if t[0].isupper() and len(t) > 1 and t[1:].islower(): res.append(TK_MAJ) res.append(t.lower()) return res
[ "def", "deal_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "res", "=", "[", "]", "for", "t", "in", "x", ":", "if", "t", "==", "''", ":", "continue", "if", "t", "[", "0", "]", ".", "isupper", "(", ")", "and", "len", "(", "t", ")", ">", "1", "and", "t", "[", "1", ":", "]", ".", "islower", "(", ")", ":", "res", ".", "append", "(", "TK_MAJ", ")", "res", ".", "append", "(", "t", ".", "lower", "(", ")", ")", "return", "res" ]
Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before.
[ "Replace", "all", "Capitalized", "tokens", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_MAJ", "before", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L75-L82
20,793
fastai/fastai
fastai/text/transform.py
Tokenizer.process_text
def process_text(self, t:str, tok:BaseTokenizer) -> List[str]: "Process one text `t` with tokenizer `tok`." for rule in self.pre_rules: t = rule(t) toks = tok.tokenizer(t) for rule in self.post_rules: toks = rule(toks) return toks
python
def process_text(self, t:str, tok:BaseTokenizer) -> List[str]: "Process one text `t` with tokenizer `tok`." for rule in self.pre_rules: t = rule(t) toks = tok.tokenizer(t) for rule in self.post_rules: toks = rule(toks) return toks
[ "def", "process_text", "(", "self", ",", "t", ":", "str", ",", "tok", ":", "BaseTokenizer", ")", "->", "List", "[", "str", "]", ":", "for", "rule", "in", "self", ".", "pre_rules", ":", "t", "=", "rule", "(", "t", ")", "toks", "=", "tok", ".", "tokenizer", "(", "t", ")", "for", "rule", "in", "self", ".", "post_rules", ":", "toks", "=", "rule", "(", "toks", ")", "return", "toks" ]
Process one text `t` with tokenizer `tok`.
[ "Process", "one", "text", "t", "with", "tokenizer", "tok", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L103-L108
20,794
fastai/fastai
fastai/text/transform.py
Tokenizer._process_all_1
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts` in one process." tok = self.tok_func(self.lang) if self.special_cases: tok.add_special_cases(self.special_cases) return [self.process_text(str(t), tok) for t in texts]
python
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts` in one process." tok = self.tok_func(self.lang) if self.special_cases: tok.add_special_cases(self.special_cases) return [self.process_text(str(t), tok) for t in texts]
[ "def", "_process_all_1", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "tok", "=", "self", ".", "tok_func", "(", "self", ".", "lang", ")", "if", "self", ".", "special_cases", ":", "tok", ".", "add_special_cases", "(", "self", ".", "special_cases", ")", "return", "[", "self", ".", "process_text", "(", "str", "(", "t", ")", ",", "tok", ")", "for", "t", "in", "texts", "]" ]
Process a list of `texts` in one process.
[ "Process", "a", "list", "of", "texts", "in", "one", "process", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L110-L114
20,795
fastai/fastai
fastai/text/transform.py
Tokenizer.process_all
def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus) as e: return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), [])
python
def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus) as e: return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), [])
[ "def", "process_all", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "if", "self", ".", "n_cpus", "<=", "1", ":", "return", "self", ".", "_process_all_1", "(", "texts", ")", "with", "ProcessPoolExecutor", "(", "self", ".", "n_cpus", ")", "as", "e", ":", "return", "sum", "(", "e", ".", "map", "(", "self", ".", "_process_all_1", ",", "partition_by_cores", "(", "texts", ",", "self", ".", "n_cpus", ")", ")", ",", "[", "]", ")" ]
Process a list of `texts`.
[ "Process", "a", "list", "of", "texts", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L116-L120
20,796
fastai/fastai
fastai/text/transform.py
Vocab.numericalize
def numericalize(self, t:Collection[str]) -> List[int]: "Convert a list of tokens `t` to their ids." return [self.stoi[w] for w in t]
python
def numericalize(self, t:Collection[str]) -> List[int]: "Convert a list of tokens `t` to their ids." return [self.stoi[w] for w in t]
[ "def", "numericalize", "(", "self", ",", "t", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "self", ".", "stoi", "[", "w", "]", "for", "w", "in", "t", "]" ]
Convert a list of tokens `t` to their ids.
[ "Convert", "a", "list", "of", "tokens", "t", "to", "their", "ids", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L128-L130
20,797
fastai/fastai
fastai/text/transform.py
Vocab.textify
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
python
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
[ "def", "textify", "(", "self", ",", "nums", ":", "Collection", "[", "int", "]", ",", "sep", "=", "' '", ")", "->", "List", "[", "str", "]", ":", "return", "sep", ".", "join", "(", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nums", "]", ")", "if", "sep", "is", "not", "None", "else", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nums", "]" ]
Convert a list of `nums` to their tokens.
[ "Convert", "a", "list", "of", "nums", "to", "their", "tokens", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L132-L134
20,798
fastai/fastai
fastai/text/transform.py
Vocab.create
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab': "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if o in itos: itos.remove(o) itos.insert(0, o) return cls(itos)
python
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab': "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if o in itos: itos.remove(o) itos.insert(0, o) return cls(itos)
[ "def", "create", "(", "cls", ",", "tokens", ":", "Tokens", ",", "max_vocab", ":", "int", ",", "min_freq", ":", "int", ")", "->", "'Vocab'", ":", "freq", "=", "Counter", "(", "p", "for", "o", "in", "tokens", "for", "p", "in", "o", ")", "itos", "=", "[", "o", "for", "o", ",", "c", "in", "freq", ".", "most_common", "(", "max_vocab", ")", "if", "c", ">=", "min_freq", "]", "for", "o", "in", "reversed", "(", "defaults", ".", "text_spec_tok", ")", ":", "if", "o", "in", "itos", ":", "itos", ".", "remove", "(", "o", ")", "itos", ".", "insert", "(", "0", ",", "o", ")", "return", "cls", "(", "itos", ")" ]
Create a vocabulary from a set of `tokens`.
[ "Create", "a", "vocabulary", "from", "a", "set", "of", "tokens", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L148-L155
20,799
fastai/fastai
fastai/text/transform.py
Vocab.load
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
python
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
[ "def", "load", "(", "cls", ",", "path", ")", ":", "itos", "=", "pickle", ".", "load", "(", "open", "(", "path", ",", "'rb'", ")", ")", "return", "cls", "(", "itos", ")" ]
Load the `Vocab` contained in `path`
[ "Load", "the", "Vocab", "contained", "in", "path" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L158-L161