Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
RemoveLocations | (test_output) | Removes all file location info from a Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
'FILE... | Removes all file location info from a Google Test program's output. | def RemoveLocations(test_output):
"""Removes all file location info from a Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\FILE_NAME(LI... | [
"def",
"RemoveLocations",
"(",
"test_output",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'.*[/\\\\](.+)(\\:\\d+|\\(\\d+\\))\\: '",
",",
"r'\\1:#: '",
",",
"test_output",
")"
] | [
88,
0
] | [
101,
73
] | python | en | ['en', 'en', 'en'] | True |
RemoveStackTraceDetails | (output) | Removes all stack traces from a Google Test program's output. | Removes all stack traces from a Google Test program's output. | def RemoveStackTraceDetails(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n',
'Stack trace: (omitted)\n\n', output) | [
"def",
"RemoveStackTraceDetails",
"(",
"output",
")",
":",
"# *? means \"find the shortest string that matches\".",
"return",
"re",
".",
"sub",
"(",
"r'Stack trace:(.|\\n)*?\\n\\n'",
",",
"'Stack trace: (omitted)\\n\\n'",
",",
"output",
")"
] | [
104,
0
] | [
109,
53
] | python | en | ['en', 'en', 'en'] | True |
RemoveStackTraces | (output) | Removes all traces of stack traces from a Google Test program's output. | Removes all traces of stack traces from a Google Test program's output. | def RemoveStackTraces(output):
"""Removes all traces of stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output) | [
"def",
"RemoveStackTraces",
"(",
"output",
")",
":",
"# *? means \"find the shortest string that matches\".",
"return",
"re",
".",
"sub",
"(",
"r'Stack trace:(.|\\n)*?\\n\\n'",
",",
"''",
",",
"output",
")"
] | [
112,
0
] | [
116,
56
] | python | en | ['en', 'en', 'en'] | True |
RemoveTime | (output) | Removes all time information from a Google Test program's output. | Removes all time information from a Google Test program's output. | def RemoveTime(output):
"""Removes all time information from a Google Test program's output."""
return re.sub(r'\(\d+ ms', '(? ms', output) | [
"def",
"RemoveTime",
"(",
"output",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\(\\d+ ms'",
",",
"'(? ms'",
",",
"output",
")"
] | [
119,
0
] | [
122,
45
] | python | en | ['en', 'en', 'en'] | True |
RemoveTypeInfoDetails | (test_output) | Removes compiler-specific type info from Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with type information normalized to canonical form.
| Removes compiler-specific type info from Google Test program's output. | def RemoveTypeInfoDetails(test_output):
"""Removes compiler-specific type info from Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with type information normalized to canonical form.
"""
# some compilers output the name of type 'unsigned... | [
"def",
"RemoveTypeInfoDetails",
"(",
"test_output",
")",
":",
"# some compilers output the name of type 'unsigned int' as 'unsigned'",
"return",
"re",
".",
"sub",
"(",
"r'unsigned int'",
",",
"'unsigned'",
",",
"test_output",
")"
] | [
125,
0
] | [
136,
57
] | python | en | ['en', 'en', 'en'] | True |
NormalizeToCurrentPlatform | (test_output) | Normalizes platform specific output details for easier comparison. | Normalizes platform specific output details for easier comparison. | def NormalizeToCurrentPlatform(test_output):
"""Normalizes platform specific output details for easier comparison."""
if IS_WINDOWS:
# Removes the color information that is not present on Windows.
test_output = re.sub('\x1b\\[(0;3\d)?m', '', test_output)
# Changes failure message headers into the Windo... | [
"def",
"NormalizeToCurrentPlatform",
"(",
"test_output",
")",
":",
"if",
"IS_WINDOWS",
":",
"# Removes the color information that is not present on Windows.",
"test_output",
"=",
"re",
".",
"sub",
"(",
"'\\x1b\\\\[(0;3\\d)?m'",
",",
"''",
",",
"test_output",
")",
"# Chang... | [
139,
0
] | [
150,
20
] | python | en | ['en', 'fr', 'en'] | True |
RemoveTestCounts | (output) | Removes test counts from a Google Test program's output. | Removes test counts from a Google Test program's output. | def RemoveTestCounts(output):
"""Removes test counts from a Google Test program's output."""
output = re.sub(r'\d+ tests?, listed below',
'? tests, listed below', output)
output = re.sub(r'\d+ FAILED TESTS',
'? FAILED TESTS', output)
output = re.sub(r'\d+ tests? from \d+ tes... | [
"def",
"RemoveTestCounts",
"(",
"output",
")",
":",
"output",
"=",
"re",
".",
"sub",
"(",
"r'\\d+ tests?, listed below'",
",",
"'? tests, listed below'",
",",
"output",
")",
"output",
"=",
"re",
".",
"sub",
"(",
"r'\\d+ FAILED TESTS'",
",",
"'? FAILED TESTS'",
"... | [
153,
0
] | [
164,
52
] | python | en | ['en', 'en', 'en'] | True |
RemoveMatchingTests | (test_output, pattern) | Removes output of specified tests from a Google Test program's output.
This function strips not only the beginning and the end of a test but also
all output in between.
Args:
test_output: A string containing the test output.
pattern: A regex string that matches names of test cases or
... | Removes output of specified tests from a Google Test program's output. | def RemoveMatchingTests(test_output, pattern):
"""Removes output of specified tests from a Google Test program's output.
This function strips not only the beginning and the end of a test but also
all output in between.
Args:
test_output: A string containing the test output.
pattern: A ... | [
"def",
"RemoveMatchingTests",
"(",
"test_output",
",",
"pattern",
")",
":",
"test_output",
"=",
"re",
".",
"sub",
"(",
"r'.*\\[ RUN \\] .*%s(.|\\n)*?\\[( FAILED | OK )\\] .*%s.*\\n'",
"%",
"(",
"pattern",
",",
"pattern",
")",
",",
"''",
",",
"test_output"... | [
167,
0
] | [
187,
55
] | python | en | ['en', 'en', 'en'] | True |
NormalizeOutput | (output) | Normalizes output (the output of gtest_output_test_.exe). | Normalizes output (the output of gtest_output_test_.exe). | def NormalizeOutput(output):
"""Normalizes output (the output of gtest_output_test_.exe)."""
output = ToUnixLineEnding(output)
output = RemoveLocations(output)
output = RemoveStackTraceDetails(output)
output = RemoveTime(output)
return output | [
"def",
"NormalizeOutput",
"(",
"output",
")",
":",
"output",
"=",
"ToUnixLineEnding",
"(",
"output",
")",
"output",
"=",
"RemoveLocations",
"(",
"output",
")",
"output",
"=",
"RemoveStackTraceDetails",
"(",
"output",
")",
"output",
"=",
"RemoveTime",
"(",
"out... | [
190,
0
] | [
197,
15
] | python | en | ['en', 'en', 'en'] | True |
GetShellCommandOutput | (env_cmd) | Runs a command in a sub-process, and returns its output in a string.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
Returns:
A string with the command's combine... | Runs a command in a sub-process, and returns its output in a string. | def GetShellCommandOutput(env_cmd):
"""Runs a command in a sub-process, and returns its output in a string.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
Returns... | [
"def",
"GetShellCommandOutput",
"(",
"env_cmd",
")",
":",
"# Spawns cmd in a sub-process, and gets its standard I/O file objects.",
"# Set and save the environment properly.",
"environ",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"environ",
".",
"update",
"(",
"env_c... | [
200,
0
] | [
218,
17
] | python | en | ['en', 'en', 'en'] | True |
GetCommandOutput | (env_cmd) | Runs a command and returns its output with all file location
info stripped off.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.
| Runs a command and returns its output with all file location
info stripped off. | def GetCommandOutput(env_cmd):
"""Runs a command and returns its output with all file location
info stripped off.
Args:
env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
environment variables to set, and element 1 is a string with
the command and any flags.... | [
"def",
"GetCommandOutput",
"(",
"env_cmd",
")",
":",
"# Disables exception pop-ups on Windows.",
"environ",
",",
"cmdline",
"=",
"env_cmd",
"environ",
"=",
"dict",
"(",
"environ",
")",
"# Ensures we are modifying a copy.",
"environ",
"[",
"CATCH_EXCEPTIONS_ENV_VAR_NAME",
... | [
221,
0
] | [
235,
67
] | python | en | ['en', 'en', 'en'] | True |
GetOutputOfAllCommands | () | Returns concatenated output from several representative commands. | Returns concatenated output from several representative commands. | def GetOutputOfAllCommands():
"""Returns concatenated output from several representative commands."""
return (GetCommandOutput(COMMAND_WITH_COLOR) +
GetCommandOutput(COMMAND_WITH_TIME) +
GetCommandOutput(COMMAND_WITH_DISABLED) +
GetCommandOutput(COMMAND_WITH_SHARDING)) | [
"def",
"GetOutputOfAllCommands",
"(",
")",
":",
"return",
"(",
"GetCommandOutput",
"(",
"COMMAND_WITH_COLOR",
")",
"+",
"GetCommandOutput",
"(",
"COMMAND_WITH_TIME",
")",
"+",
"GetCommandOutput",
"(",
"COMMAND_WITH_DISABLED",
")",
"+",
"GetCommandOutput",
"(",
"COMMAN... | [
238,
0
] | [
244,
50
] | python | en | ['en', 'en', 'en'] | True |
Stream.maxpoints | (self) |
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]... |
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000] | def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or ... | [
"def",
"maxpoints",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"maxpoints\"",
"]"
] | [
15,
4
] | [
28,
32
] | python | en | ['en', 'error', 'th'] | False |
Stream.token | (self) |
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string | def token(self):
"""
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
... | [
"def",
"token",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"token\"",
"]"
] | [
37,
4
] | [
50,
28
] | python | en | ['en', 'error', 'th'] | False |
Stream.__init__ | (self, arg=None, maxpoints=None, token=None, **kwargs) |
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.choroplethmapbox.Stream`
maxpoints
Sets the maximum number of points t... |
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.choroplethmapbox.Stream`
maxpoints
Sets the maximum number of points t... | def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.choroplethm... | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"maxpoints",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Stream",
",",
"self",
")",
".",
"__init__",
"(",
"\"stream\"",
")",
"if",
"\"_paren... | [
72,
4
] | [
140,
34
] | python | en | ['en', 'error', 'th'] | False |
get_keywords | () | Get the keywords needed to look up the version information. | Get the keywords needed to look up the version information. | def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, so they must
# each be defined on a line of their own. _version.py will just call
# get_keyword... | [
"def",
"get_keywords",
"(",
")",
":",
"# these strings will be replaced by git during git-archive.",
"# setup.py/versioneer.py will grep for the variable names, so they must",
"# each be defined on a line of their own. _version.py will just call",
"# get_keywords().",
"git_refnames",
"=",
"\"$... | [
18,
0
] | [
28,
19
] | python | en | ['en', 'en', 'en'] | True |
get_config | () | Create, populate and return the VersioneerConfig() object. | Create, populate and return the VersioneerConfig() object. | def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440"
cfg.tag_prefix = "v"
cfg.parentdir_prefix = "plotly-"
cfg.ve... | [
"def",
"get_config",
"(",
")",
":",
"# these strings are filled in when 'setup.py versioneer' creates",
"# _version.py",
"cfg",
"=",
"VersioneerConfig",
"(",
")",
"cfg",
".",
"VCS",
"=",
"\"git\"",
"cfg",
".",
"style",
"=",
"\"pep440\"",
"cfg",
".",
"tag_prefix",
"=... | [
35,
0
] | [
46,
14
] | python | en | ['en', 'en', 'en'] | True |
register_vcs_handler | (vcs, method) | Decorator to mark a method as the handler for a particular VCS. | Decorator to mark a method as the handler for a particular VCS. | def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
retur... | [
"def",
"register_vcs_handler",
"(",
"vcs",
",",
"method",
")",
":",
"# decorator",
"def",
"decorate",
"(",
"f",
")",
":",
"\"\"\"Store f in HANDLERS[vcs][method].\"\"\"",
"if",
"vcs",
"not",
"in",
"HANDLERS",
":",
"HANDLERS",
"[",
"vcs",
"]",
"=",
"{",
"}",
... | [
57,
0
] | [
67,
19
] | python | en | ['en', 'en', 'en'] | True |
run_command | (commands, args, cwd=None, verbose=False, hide_stderr=False, env=None) | Call the given command(s). | Call the given command(s). | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just... | [
"def",
"run_command",
"(",
"commands",
",",
"args",
",",
"cwd",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"hide_stderr",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"commands",
",",
"list",
")",
"p",
"=",
"None... | [
70,
0
] | [
106,
31
] | python | en | ['en', 'en', 'en'] | True |
versions_from_parentdir | (parentdir_prefix, root, verbose) | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory
| Try to determine the version from the parent directory name. | def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an ap... | [
"def",
"versions_from_parentdir",
"(",
"parentdir_prefix",
",",
"root",
",",
"verbose",
")",
":",
"rootdirs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"if",
"d... | [
109,
0
] | [
137,
70
] | python | en | ['en', 'en', 'en'] | True |
git_get_keywords | (versionfile_abs) | Extract version information from the given file. | Extract version information from the given file. | def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from... | [
"def",
"git_get_keywords",
"(",
"versionfile_abs",
")",
":",
"# the code embedded in _version.py can just fetch the value of these",
"# keywords. When used from setup.py, we don't want to import _version.py,",
"# so we do it with a regexp instead. This function is not used from",
"# _version.py.",... | [
141,
0
] | [
166,
19
] | python | en | ['en', 'en', 'en'] | True |
git_versions_from_keywords | (keywords, tag_prefix, verbose) | Get version information from git keywords. | Get version information from git keywords. | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compli... | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",... | [
170,
0
] | [
228,
5
] | python | en | ['en', 'da', 'en'] | True |
git_pieces_from_vcs | (tag_prefix, root, verbose, run_command=run_command) | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
| Get version from 'git describe' in the root of the source tree. | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meani... | [
"def",
"git_pieces_from_vcs",
"(",
"tag_prefix",
",",
"root",
",",
"verbose",
",",
"run_command",
"=",
"run_command",
")",
":",
"GITS",
"=",
"[",
"\"git\"",
"]",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"GITS",
"=",
"[",
"\"git.cmd\"",
",",
... | [
232,
0
] | [
329,
17
] | python | en | ['en', 'en', 'en'] | True |
plus_or_dot | (pieces) | Return a + if we don't already have one, else return a . | Return a + if we don't already have one, else return a . | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+" | [
"def",
"plus_or_dot",
"(",
"pieces",
")",
":",
"if",
"\"+\"",
"in",
"pieces",
".",
"get",
"(",
"\"closest-tag\"",
",",
"\"\"",
")",
":",
"return",
"\".\"",
"return",
"\"+\""
] | [
332,
0
] | [
336,
14
] | python | en | ['en', 'en', 'en'] | True |
render_pep440 | (pieces) | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
| Build up version string, with post-release "local version identifier". | def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHE... | [
"def",
"render_pep440",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
"+=... | [
339,
0
] | [
360,
19
] | python | en | ['en', 'en', 'en'] | True |
render_pep440_pre | (pieces) | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
| TAG[.post.devDISTANCE] -- No -dirty. | def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exce... | [
"def",
"render_pep440_pre",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\".post.dev%d\"",
"%",
"pieces",
... | [
363,
0
] | [
376,
19
] | python | en | ['en', 'en', 'pt'] | True |
render_pep440_post | (pieces) | TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
| TAG[.postDISTANCE[.dev0]+gHEX] . | def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[... | [
"def",
"render_pep440_post",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
... | [
379,
0
] | [
403,
19
] | python | cy | ['en', 'cy', 'hi'] | False |
render_pep440_old | (pieces) | TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
| TAG[.postDISTANCE[.dev0]] . | def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pie... | [
"def",
"render_pep440_old",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
... | [
406,
0
] | [
425,
19
] | python | en | ['en', 'mt', 'hi'] | False |
render_git_describe | (pieces) | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
| TAG[-DISTANCE-gHEX][-dirty]. | def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered +=... | [
"def",
"render_git_describe",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces... | [
428,
0
] | [
445,
19
] | python | en | ['en', 'en', 'en'] | False |
render_git_describe_long | (pieces) | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
| TAG-DISTANCE-gHEX[-dirty]. | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
... | [
"def",
"render_git_describe_long",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces",
"[",
"\"distance\"",
"]",
",",
"pieces",
... | [
448,
0
] | [
465,
19
] | python | en | ['en', 'en', 'pt'] | False |
render | (pieces, style) | Render the given version pieces into the requested style. | Render the given version pieces into the requested style. | def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None,
... | [
"def",
"render",
"(",
"pieces",
",",
"style",
")",
":",
"if",
"pieces",
"[",
"\"error\"",
"]",
":",
"return",
"{",
"\"version\"",
":",
"\"unknown\"",
",",
"\"full-revisionid\"",
":",
"pieces",
".",
"get",
"(",
"\"long\"",
")",
",",
"\"dirty\"",
":",
"Non... | [
468,
0
] | [
503,
5
] | python | en | ['en', 'en', 'en'] | True |
get_versions | () | Get version information or return default if unable to do so. | Get version information or return default if unable to do so. | def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
#... | [
"def",
"get_versions",
"(",
")",
":",
"# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have",
"# __file__, we can work backwards from there to the root. Some",
"# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which",
"# case we can only use expanded keywords.... | [
506,
0
] | [
555,
5
] | python | en | ['it', 'en', 'en'] | True |
History.parse | (self, text) |
Tokenize text with the given dictionary.
|
Tokenize text with the given dictionary.
| def parse(self, text):
"""
Tokenize text with the given dictionary.
"""
return self.dict.txt2vec(text) | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"dict",
".",
"txt2vec",
"(",
"text",
")"
] | [
222,
4
] | [
226,
38
] | python | en | ['en', 'error', 'th'] | False |
History.reset | (self) |
Clear the history.
|
Clear the history.
| def reset(self):
"""
Clear the history.
"""
self.history_raw_strings = []
self.history_strings = []
self.history_vecs = [] | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"history_raw_strings",
"=",
"[",
"]",
"self",
".",
"history_strings",
"=",
"[",
"]",
"self",
".",
"history_vecs",
"=",
"[",
"]"
] | [
228,
4
] | [
234,
30
] | python | en | ['en', 'error', 'th'] | False |
History.add_reply | (self, text) |
Add your own response to the history.
|
Add your own response to the history.
| def add_reply(self, text):
"""
Add your own response to the history.
"""
self._update_raw_strings(text)
if self.add_person_tokens:
text = self._add_person_tokens(text, self.p2_token)
# update history string
self._update_strings(text)
# update h... | [
"def",
"add_reply",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"_update_raw_strings",
"(",
"text",
")",
"if",
"self",
".",
"add_person_tokens",
":",
"text",
"=",
"self",
".",
"_add_person_tokens",
"(",
"text",
",",
"self",
".",
"p2_token",
")",
"# ... | [
254,
4
] | [
264,
31
] | python | en | ['en', 'error', 'th'] | False |
History.update_history | (self, obs: Message, temp_history: Optional[str] = None) |
Update the history with the given observation.
:param obs:
Observation used to update the history.
:param temp_history:
Optional temporary string. If it is not None, this string will be
appended to the end of the history. It will not be in the history
... |
Update the history with the given observation. | def update_history(self, obs: Message, temp_history: Optional[str] = None):
"""
Update the history with the given observation.
:param obs:
Observation used to update the history.
:param temp_history:
Optional temporary string. If it is not None, this string will ... | [
"def",
"update_history",
"(",
"self",
",",
"obs",
":",
"Message",
",",
"temp_history",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"if",
"self",
".",
"field",
"in",
"obs",
"and",
"obs",
"[",
"self",
".",
"field",
"]",
"is",
"not",
"Non... | [
266,
4
] | [
294,
40
] | python | en | ['en', 'error', 'th'] | False |
History.get_history_str | (self) |
Return the string version of the history.
|
Return the string version of the history.
| def get_history_str(self):
"""
Return the string version of the history.
"""
if len(self.history_strings) > 0:
history = self.history_strings[:]
history = self.delimiter.join(history)
if self.temp_history is not None:
history += self.te... | [
"def",
"get_history_str",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"history_strings",
")",
">",
"0",
":",
"history",
"=",
"self",
".",
"history_strings",
"[",
":",
"]",
"history",
"=",
"self",
".",
"delimiter",
".",
"join",
"(",
"history",... | [
296,
4
] | [
307,
19
] | python | en | ['en', 'error', 'th'] | False |
History.get_history_vec | (self) |
Return a vectorized version of the history.
|
Return a vectorized version of the history.
| def get_history_vec(self):
"""
Return a vectorized version of the history.
"""
if len(self.history_vecs) == 0:
return None
# vec type is a list
history = []
for vec in self.history_vecs[:-1]:
history += [vec]
history += [self.d... | [
"def",
"get_history_vec",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"history_vecs",
")",
"==",
"0",
":",
"return",
"None",
"# vec type is a list",
"history",
"=",
"[",
"]",
"for",
"vec",
"in",
"self",
".",
"history_vecs",
"[",
":",
"-",
"1"... | [
309,
4
] | [
331,
22
] | python | en | ['en', 'error', 'th'] | False |
History.get_history_vec_list | (self) |
Return a list of history vecs.
|
Return a list of history vecs.
| def get_history_vec_list(self):
"""
Return a list of history vecs.
"""
return self.history_vecs | [
"def",
"get_history_vec_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"history_vecs"
] | [
333,
4
] | [
337,
32
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.optim_opts | (cls) |
Fetch optimizer selection.
By default, collects everything in torch.optim, as well as importing:
- qhm / qhmadam if installed from github.com/facebookresearch/qhoptim
Override this (and probably call super()) to add your own optimizers.
|
Fetch optimizer selection. | def optim_opts(cls):
"""
Fetch optimizer selection.
By default, collects everything in torch.optim, as well as importing:
- qhm / qhmadam if installed from github.com/facebookresearch/qhoptim
Override this (and probably call super()) to add your own optimizers.
"""
... | [
"def",
"optim_opts",
"(",
"cls",
")",
":",
"# first pull torch.optim in",
"optims",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"optim",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
... | [
368,
4
] | [
406,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.dictionary_class | () |
Return the dictionary class that this agent expects to use.
Can be overriden if a more complex dictionary is required.
|
Return the dictionary class that this agent expects to use. | def dictionary_class():
"""
Return the dictionary class that this agent expects to use.
Can be overriden if a more complex dictionary is required.
"""
return DictionaryAgent | [
"def",
"dictionary_class",
"(",
")",
":",
"return",
"DictionaryAgent"
] | [
409,
4
] | [
415,
30
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.history_class | (cls) |
Return the history class that this agent expects to use.
Can be overriden if a more complex history is required.
|
Return the history class that this agent expects to use. | def history_class(cls):
"""
Return the history class that this agent expects to use.
Can be overriden if a more complex history is required.
"""
return History | [
"def",
"history_class",
"(",
"cls",
")",
":",
"return",
"History"
] | [
418,
4
] | [
424,
22
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.add_cmdline_args | (
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) |
Add the default commandline args we expect most agents to want.
|
Add the default commandline args we expect most agents to want.
| def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
"""
Add the default commandline args we expect most agents to want.
"""
agent = parser.add_argument_group('TorchAgent Arguments')
agent.add_argument(
'-i'... | [
"def",
"add_cmdline_args",
"(",
"cls",
",",
"parser",
":",
"ParlaiParser",
",",
"partial_opt",
":",
"Optional",
"[",
"Opt",
"]",
"=",
"None",
")",
"->",
"ParlaiParser",
":",
"agent",
"=",
"parser",
".",
"add_argument_group",
"(",
"'TorchAgent Arguments'",
")",... | [
427,
4
] | [
680,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.__init__ | (self, opt: Opt, shared=None) |
Initialize agent.
|
Initialize agent.
| def __init__(self, opt: Opt, shared=None):
"""
Initialize agent.
"""
super().__init__(opt, shared)
opt = self.opt
# Safety checkers to ensure TorchAgent assumptions aren't being violated.
self.__expecting_clear_history = False
self.__expecting_to_reply = ... | [
"def",
"__init__",
"(",
"self",
",",
"opt",
":",
"Opt",
",",
"shared",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"opt",
",",
"shared",
")",
"opt",
"=",
"self",
".",
"opt",
"# Safety checkers to ensure TorchAgent assumptions aren't being... | [
682,
4
] | [
784,
77
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.build_history | (self) |
Return the constructed history object.
|
Return the constructed history object.
| def build_history(self):
"""
Return the constructed history object.
"""
return self.history_class()(
self.opt,
maxlen=self.text_truncate,
size=self.histsz,
p1_token=self.P1_TOKEN,
p2_token=self.P2_TOKEN,
dict_agent=s... | [
"def",
"build_history",
"(",
"self",
")",
":",
"return",
"self",
".",
"history_class",
"(",
")",
"(",
"self",
".",
"opt",
",",
"maxlen",
"=",
"self",
".",
"text_truncate",
",",
"size",
"=",
"self",
".",
"histsz",
",",
"p1_token",
"=",
"self",
".",
"P... | [
786,
4
] | [
797,
9
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.build_dictionary | (self) |
Return the constructed dictionary, which will be set to self.dict.
If you need to add additional tokens to the dictionary, this is likely the right
place to do it.
|
Return the constructed dictionary, which will be set to self.dict. | def build_dictionary(self):
"""
Return the constructed dictionary, which will be set to self.dict.
If you need to add additional tokens to the dictionary, this is likely the right
place to do it.
"""
d = self.dictionary_class()(self.opt)
self.special_toks = self.... | [
"def",
"build_dictionary",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"dictionary_class",
"(",
")",
"(",
"self",
".",
"opt",
")",
"self",
".",
"special_toks",
"=",
"self",
".",
"_get_special_tokens",
"(",
")",
"if",
"self",
".",
"special_toks",
":",
... | [
799,
4
] | [
814,
16
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._resize_token_embeddings | (self, state_dict, msg=None) |
Must define this for your agent if you wish to add additional special tokens.
Must make a call to resize the token embeddings and load the model state dict
with the resized token embeddings.
|
Must define this for your agent if you wish to add additional special tokens. | def _resize_token_embeddings(self, state_dict, msg=None):
"""
Must define this for your agent if you wish to add additional special tokens.
Must make a call to resize the token embeddings and load the model state dict
with the resized token embeddings.
"""
raise NotImple... | [
"def",
"_resize_token_embeddings",
"(",
"self",
",",
"state_dict",
",",
"msg",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'If you are intending to add special tokens to an already pretrained model, '",
"'you must write the function `_resize_token_embeddings` for you... | [
816,
4
] | [
827,
9
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._get_init_model | (self, opt: Opt, shared) |
Get model file to initialize with.
If `init_model` exits, we will return the path to that file and maybe
load dict file from that path. Otherwise, use `model_file.`
:return: path to load model from, whether we loaded from `init_model`
or not
|
Get model file to initialize with. | def _get_init_model(self, opt: Opt, shared):
"""
Get model file to initialize with.
If `init_model` exits, we will return the path to that file and maybe
load dict file from that path. Otherwise, use `model_file.`
:return: path to load model from, whether we loaded from `init_... | [
"def",
"_get_init_model",
"(",
"self",
",",
"opt",
":",
"Opt",
",",
"shared",
")",
":",
"init_model",
"=",
"None",
"is_finetune",
"=",
"False",
"if",
"not",
"shared",
":",
"# only do this on first setup",
"# first check load path in case we need to override paths",
"i... | [
829,
4
] | [
866,
38
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._get_special_tokens | (self) |
Return list of special tokens.
Made easily overridable for special cases.
Note that in the case of ambiguity of special-token parsing, the
precedence is set by the ordering returned in this method. For
example, if special tokens are ["OHB", "BOY"], parsing "OHBOY" will
... |
Return list of special tokens. | def _get_special_tokens(self) -> List[str]:
"""
Return list of special tokens.
Made easily overridable for special cases.
Note that in the case of ambiguity of special-token parsing, the
precedence is set by the ordering returned in this method. For
example, if special... | [
"def",
"_get_special_tokens",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"self",
".",
"opt",
".",
"get",
"(",
"'special_tok_lst'",
")",
":",
"return",
"self",
".",
"opt",
"[",
"'special_tok_lst'",
"]",
".",
"split",
"(",
"','",
")",
... | [
868,
4
] | [
882,
17
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.build_model | (self) |
Construct the model and return it.
|
Construct the model and return it.
| def build_model(self):
"""
Construct the model and return it.
"""
raise NotImplementedError('not implemented for this class') | [
"def",
"build_model",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'not implemented for this class'",
")"
] | [
885,
4
] | [
889,
67
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._should_initialize_optimizer | (self) |
Used to indicate whether we should initialize an optimizer.
When this is off, we can save memory and use larger batches.
|
Used to indicate whether we should initialize an optimizer. | def _should_initialize_optimizer(self) -> bool:
"""
Used to indicate whether we should initialize an optimizer.
When this is off, we can save memory and use larger batches.
"""
if self.opt.get('interactive_mode'):
return False
datatype = self.opt.get('datatyp... | [
"def",
"_should_initialize_optimizer",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"opt",
".",
"get",
"(",
"'interactive_mode'",
")",
":",
"return",
"False",
"datatype",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'datatype'",
",",
"''",
")",
... | [
891,
4
] | [
901,
23
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.init_optim | (self, params, optim_states=None, saved_optim_type=None) |
Initialize optimizer with model parameters.
:param params:
parameters from the model
:param optim_states:
optional argument providing states of optimizer to load
:param saved_optim_type:
type of optimizer being loaded, if changed will skip loading
... |
Initialize optimizer with model parameters. | def init_optim(self, params, optim_states=None, saved_optim_type=None):
"""
Initialize optimizer with model parameters.
:param params:
parameters from the model
:param optim_states:
optional argument providing states of optimizer to load
:param saved_op... | [
"def",
"init_optim",
"(",
"self",
",",
"params",
",",
"optim_states",
"=",
"None",
",",
"saved_optim_type",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'resized_embeddings'",
")",
"and",
"self",
".",
"resized_embeddings",
":",
"optim_states",
... | [
903,
4
] | [
1042,
17
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.build_lr_scheduler | (self, states=None, hard_reset=False) |
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate.
:param state_dict states: Possible state_dict provided by model
checkpoint, for restori... |
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate. | def build_lr_scheduler(self, states=None, hard_reset=False):
"""
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate.
:param state_dict states: P... | [
"def",
"build_lr_scheduler",
"(",
"self",
",",
"states",
"=",
"None",
",",
"hard_reset",
"=",
"False",
")",
":",
"if",
"states",
"is",
"None",
":",
"states",
"=",
"{",
"}",
"optimizer",
"=",
"self",
".",
"optimizer",
"if",
"self",
".",
"fp16",
":",
"... | [
1044,
4
] | [
1067,
13
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._control_local_metrics | (self, enabled: bool = False, disabled: bool = False) |
Used to temporarily disable local metrics.
This is useful for things like when you need to call super(), but
prevent the parent from recording some metric. For example, if you're
forwarding a dummy batch or calling super() but still want to modify
the output.
You can c... |
Used to temporarily disable local metrics. | def _control_local_metrics(self, enabled: bool = False, disabled: bool = False):
"""
Used to temporarily disable local metrics.
This is useful for things like when you need to call super(), but
prevent the parent from recording some metric. For example, if you're
forwarding a du... | [
"def",
"_control_local_metrics",
"(",
"self",
",",
"enabled",
":",
"bool",
"=",
"False",
",",
"disabled",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"(",
"enabled",
"^",
"disabled",
")",
":",
"raise",
"ValueError",
"(",
"'You must provide exactly one ... | [
1069,
4
] | [
1085,
46
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.record_local_metric | (self, keyname: str, values: List[Metric]) |
Record an example-level metric for all items in the batch.
Local metrics are maybe recorded anywhere within batch act. They will
automatically be collated and returned at the end of batch_act. The
beginning of batch_act resets these, so you may not use them during
observe.
... |
Record an example-level metric for all items in the batch. | def record_local_metric(self, keyname: str, values: List[Metric]):
"""
Record an example-level metric for all items in the batch.
Local metrics are maybe recorded anywhere within batch act. They will
automatically be collated and returned at the end of batch_act. The
beginning o... | [
"def",
"record_local_metric",
"(",
"self",
",",
"keyname",
":",
"str",
",",
"values",
":",
"List",
"[",
"Metric",
"]",
")",
":",
"if",
"not",
"self",
".",
"__local_metrics_enabled",
":",
"return",
"if",
"keyname",
"in",
"self",
".",
"_local_metrics",
":",
... | [
1087,
4
] | [
1104,
45
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.report | (self) |
Report metrics.
Report includes learning rate and number of training updates.
|
Report metrics. | def report(self):
"""
Report metrics.
Report includes learning rate and number of training updates.
"""
report = self.global_metrics.report()
# only report LR if we have a scheduler
if hasattr(self, 'scheduler') and self.scheduler is not None:
report... | [
"def",
"report",
"(",
"self",
")",
":",
"report",
"=",
"self",
".",
"global_metrics",
".",
"report",
"(",
")",
"# only report LR if we have a scheduler",
"if",
"hasattr",
"(",
"self",
",",
"'scheduler'",
")",
"and",
"self",
".",
"scheduler",
"is",
"not",
"No... | [
1106,
4
] | [
1128,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._gpu_usage | (self) |
Compute GPU memory usage.
Includes both allocated and cached memory; this should be close to the
output of nvidia-smi, but not reflect of how much is currently demanded
by the program. It may be viewed as a rough approximation of
worst-case-until-now.
:return: Percent ... |
Compute GPU memory usage. | def _gpu_usage(self):
"""
Compute GPU memory usage.
Includes both allocated and cached memory; this should be close to the
output of nvidia-smi, but not reflect of how much is currently demanded
by the program. It may be viewed as a rough approximation of
worst-case-unti... | [
"def",
"_gpu_usage",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"use_cuda",
":",
"return",
"None",
"if",
"self",
".",
"opt",
"[",
"'gpu'",
"]",
"==",
"-",
"1",
":",
"# use all gpus available locally",
"devices",
"=",
"range",
"(",
"torch",
".",
"... | [
1130,
4
] | [
1155,
41
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._project_vec | (self, vec, target_dim, method='random') |
If needed, project vector to target dimensionality.
Projection methods implemented are the following:
random - random gaussian matrix multiplication of input vector
:param vec:
one-dimensional vector
:param target_dim:
dimension of returned vector
... |
If needed, project vector to target dimensionality. | def _project_vec(self, vec, target_dim, method='random'):
"""
If needed, project vector to target dimensionality.
Projection methods implemented are the following:
random - random gaussian matrix multiplication of input vector
:param vec:
one-dimensional vector
... | [
"def",
"_project_vec",
"(",
"self",
",",
"vec",
",",
"target_dim",
",",
"method",
"=",
"'random'",
")",
":",
"pre_dim",
"=",
"vec",
".",
"size",
"(",
"0",
")",
"if",
"pre_dim",
"!=",
"target_dim",
"or",
"method",
".",
"endswith",
"(",
"'force'",
")",
... | [
1187,
4
] | [
1223,
22
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._copy_embeddings | (self, weight, emb_type, log=True) |
Copy embeddings from the pretrained embeddings to the lookuptable.
:param weight:
weights of lookup table (nn.Embedding/nn.EmbeddingBag)
:param emb_type:
pretrained embedding type
|
Copy embeddings from the pretrained embeddings to the lookuptable. | def _copy_embeddings(self, weight, emb_type, log=True):
"""
Copy embeddings from the pretrained embeddings to the lookuptable.
:param weight:
weights of lookup table (nn.Embedding/nn.EmbeddingBag)
:param emb_type:
pretrained embedding type
"""
if... | [
"def",
"_copy_embeddings",
"(",
"self",
",",
"weight",
",",
"emb_type",
",",
"log",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"opt",
"[",
"'embedding_type'",
"]",
"==",
"'random'",
"or",
"not",
"self",
".",
"_should_initialize_optimizer",
"(",
")",
... | [
1225,
4
] | [
1254,
13
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.share | (self) |
Share fields from parent as well as useful objects in this class.
Subclasses will likely want to share their model as well.
|
Share fields from parent as well as useful objects in this class. | def share(self):
"""
Share fields from parent as well as useful objects in this class.
Subclasses will likely want to share their model as well.
"""
shared = super().share()
shared['metrics'] = self.metrics
shared['global_metrics'] = self.global_metrics.share()
... | [
"def",
"share",
"(",
"self",
")",
":",
"shared",
"=",
"super",
"(",
")",
".",
"share",
"(",
")",
"shared",
"[",
"'metrics'",
"]",
"=",
"self",
".",
"metrics",
"shared",
"[",
"'global_metrics'",
"]",
"=",
"self",
".",
"global_metrics",
".",
"share",
"... | [
1256,
4
] | [
1269,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._add_start_end_tokens | (self, vec, add_start=False, add_end=False) |
Add start and end tokens to a list or tensor.
|
Add start and end tokens to a list or tensor.
| def _add_start_end_tokens(self, vec, add_start=False, add_end=False):
"""
Add start and end tokens to a list or tensor.
"""
if isinstance(vec, torch.Tensor):
if len(vec.shape) != 1:
raise Exception('_add_start_end_tokens expects a 1D tensor')
tenso... | [
"def",
"_add_start_end_tokens",
"(",
"self",
",",
"vec",
",",
"add_start",
"=",
"False",
",",
"add_end",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"vec",
",",
"torch",
".",
"Tensor",
")",
":",
"if",
"len",
"(",
"vec",
".",
"shape",
")",
"!=",
... | [
1271,
4
] | [
1288,
18
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._v2t | (self, vec) |
Convert token indices to string of tokens.
|
Convert token indices to string of tokens.
| def _v2t(self, vec):
"""
Convert token indices to string of tokens.
"""
new_vec = []
if hasattr(vec, 'cpu'):
vec = vec.cpu()
for i in vec:
if i == self.END_IDX:
break
new_vec.append(i)
return self.dict.vec2txt(ne... | [
"def",
"_v2t",
"(",
"self",
",",
"vec",
")",
":",
"new_vec",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"vec",
",",
"'cpu'",
")",
":",
"vec",
"=",
"vec",
".",
"cpu",
"(",
")",
"for",
"i",
"in",
"vec",
":",
"if",
"i",
"==",
"self",
".",
"END_IDX",
... | [
1290,
4
] | [
1301,
41
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._vectorize_text | (
self, text, add_start=False, add_end=False, truncate=None, truncate_left=True
) |
Return vector from text.
:param text:
String to vectorize.
:param add_start:
Add the start token to the front of the tensor.
:param add_end:
Add the end token to the end of the tensor.
:param truncate:
Truncate to this many tok... |
Return vector from text. | def _vectorize_text(
self, text, add_start=False, add_end=False, truncate=None, truncate_left=True
):
"""
Return vector from text.
:param text:
String to vectorize.
:param add_start:
Add the start token to the front of the tensor.
:param add... | [
"def",
"_vectorize_text",
"(",
"self",
",",
"text",
",",
"add_start",
"=",
"False",
",",
"add_end",
"=",
"False",
",",
"truncate",
"=",
"None",
",",
"truncate_left",
"=",
"True",
")",
":",
"vec",
"=",
"self",
".",
"dict",
".",
"txt2vec",
"(",
"text",
... | [
1303,
4
] | [
1329,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._check_truncate | (self, vec, truncate, truncate_left=False) |
Check that vector is truncated correctly.
|
Check that vector is truncated correctly.
| def _check_truncate(self, vec, truncate, truncate_left=False):
"""
Check that vector is truncated correctly.
"""
if truncate is None:
return vec
if len(vec) <= truncate:
return vec
if truncate_left:
return vec[-truncate:]
else:
... | [
"def",
"_check_truncate",
"(",
"self",
",",
"vec",
",",
"truncate",
",",
"truncate_left",
"=",
"False",
")",
":",
"if",
"truncate",
"is",
"None",
":",
"return",
"vec",
"if",
"len",
"(",
"vec",
")",
"<=",
"truncate",
":",
"return",
"vec",
"if",
"truncat... | [
1331,
4
] | [
1342,
33
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._set_text_vec | (self, obs, history, truncate) |
Set the 'text_vec' field in the observation.
Useful to override to change vectorization behavior
|
Set the 'text_vec' field in the observation. | def _set_text_vec(self, obs, history, truncate):
"""
Set the 'text_vec' field in the observation.
Useful to override to change vectorization behavior
"""
if 'text' not in obs:
return obs
if 'text_vec' not in obs:
# text vec is not precomputed, s... | [
"def",
"_set_text_vec",
"(",
"self",
",",
"obs",
",",
"history",
",",
"truncate",
")",
":",
"if",
"'text'",
"not",
"in",
"obs",
":",
"return",
"obs",
"if",
"'text_vec'",
"not",
"in",
"obs",
":",
"# text vec is not precomputed, so we set it using the history",
"h... | [
1344,
4
] | [
1375,
18
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._set_label_vec | (self, obs, add_start, add_end, truncate) |
Set the 'labels_vec' field in the observation.
Useful to override to change vectorization behavior
|
Set the 'labels_vec' field in the observation. | def _set_label_vec(self, obs, add_start, add_end, truncate):
"""
Set the 'labels_vec' field in the observation.
Useful to override to change vectorization behavior
"""
# convert 'labels' or 'eval_labels' into vectors
if 'labels' in obs:
label_type = 'labels'
... | [
"def",
"_set_label_vec",
"(",
"self",
",",
"obs",
",",
"add_start",
",",
"add_end",
",",
"truncate",
")",
":",
"# convert 'labels' or 'eval_labels' into vectors",
"if",
"'labels'",
"in",
"obs",
":",
"label_type",
"=",
"'labels'",
"elif",
"'eval_labels'",
"in",
"ob... | [
1377,
4
] | [
1406,
18
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._set_label_cands_vec | (self, obs, add_start, add_end, truncate) |
Set the 'label_candidates_vec' field in the observation.
Useful to override to change vectorization behavior
|
Set the 'label_candidates_vec' field in the observation. | def _set_label_cands_vec(self, obs, add_start, add_end, truncate):
"""
Set the 'label_candidates_vec' field in the observation.
Useful to override to change vectorization behavior
"""
if 'label_candidates_vecs' in obs:
if truncate is not None:
# check... | [
"def",
"_set_label_cands_vec",
"(",
"self",
",",
"obs",
",",
"add_start",
",",
"add_end",
",",
"truncate",
")",
":",
"if",
"'label_candidates_vecs'",
"in",
"obs",
":",
"if",
"truncate",
"is",
"not",
"None",
":",
"# check truncation of pre-computed vectors",
"vecs"... | [
1408,
4
] | [
1426,
18
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.vectorize | (
self,
obs,
history,
add_start=True,
add_end=True,
text_truncate=None,
label_truncate=None,
) |
Make vectors out of observation fields and store in the observation.
In particular, the 'text' and 'labels'/'eval_labels' fields are
processed and a new field is added to the observation with the suffix
'_vec'.
If you want to use additional fields on your subclass, you can ove... |
Make vectors out of observation fields and store in the observation. | def vectorize(
self,
obs,
history,
add_start=True,
add_end=True,
text_truncate=None,
label_truncate=None,
):
"""
Make vectors out of observation fields and store in the observation.
In particular, the 'text' and 'labels'/'eval_labels' ... | [
"def",
"vectorize",
"(",
"self",
",",
"obs",
",",
"history",
",",
"add_start",
"=",
"True",
",",
"add_end",
"=",
"True",
",",
"text_truncate",
"=",
"None",
",",
"label_truncate",
"=",
"None",
",",
")",
":",
"self",
".",
"_set_text_vec",
"(",
"obs",
","... | [
1428,
4
] | [
1482,
18
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._pad_tensor | (
self, items: List[Union[List[int], torch.LongTensor]]
) |
Create a right padded matrix from an uneven list of lists.
Returns (padded, lengths), where padded is the padded matrix, and lengths
is a list containing the lengths of each row.
:param list[iter[int]] items: List of items
:returns: (padded, lengths) tuple
:rtype: (Ten... |
Create a right padded matrix from an uneven list of lists. | def _pad_tensor(
self, items: List[Union[List[int], torch.LongTensor]]
) -> Tuple[torch.LongTensor, List[int]]:
"""
Create a right padded matrix from an uneven list of lists.
Returns (padded, lengths), where padded is the padded matrix, and lengths
is a list containing the l... | [
"def",
"_pad_tensor",
"(",
"self",
",",
"items",
":",
"List",
"[",
"Union",
"[",
"List",
"[",
"int",
"]",
",",
"torch",
".",
"LongTensor",
"]",
"]",
")",
"->",
"Tuple",
"[",
"torch",
".",
"LongTensor",
",",
"List",
"[",
"int",
"]",
"]",
":",
"ret... | [
1484,
4
] | [
1506,
9
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.is_valid | (self, obs) |
Determine if an observation is valid or not.
|
Determine if an observation is valid or not.
| def is_valid(self, obs):
"""
Determine if an observation is valid or not.
"""
return 'text_vec' in obs or 'image' in obs | [
"def",
"is_valid",
"(",
"self",
",",
"obs",
")",
":",
"return",
"'text_vec'",
"in",
"obs",
"or",
"'image'",
"in",
"obs"
] | [
1508,
4
] | [
1512,
50
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.batchify | (self, obs_batch, sort=False) |
Create a batch of valid observations from an unchecked batch.
A valid observation is one that passes the lambda provided to the
function, which defaults to checking if the preprocessed 'text_vec'
field is present which would have been set by this agent's 'vectorize'
function.
... |
Create a batch of valid observations from an unchecked batch. | def batchify(self, obs_batch, sort=False):
"""
Create a batch of valid observations from an unchecked batch.
A valid observation is one that passes the lambda provided to the
function, which defaults to checking if the preprocessed 'text_vec'
field is present which would have be... | [
"def",
"batchify",
"(",
"self",
",",
"obs_batch",
",",
"sort",
"=",
"False",
")",
":",
"if",
"len",
"(",
"obs_batch",
")",
"==",
"0",
":",
"return",
"Batch",
"(",
"batchsize",
"=",
"0",
")",
"valid_obs",
"=",
"[",
"(",
"i",
",",
"ex",
")",
"for",... | [
1514,
4
] | [
1604,
9
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.match_batch | (self, batch_reply, valid_inds, output=None) |
Match sub-batch of predictions to the original batch indices.
Batches may be only partially filled (i.e when completing the remainder
at the end of the validation or test set), or we may want to sort by
e.g the length of the input sequences if using pack_padded_sequence.
This ... |
Match sub-batch of predictions to the original batch indices. | def match_batch(self, batch_reply, valid_inds, output=None):
"""
Match sub-batch of predictions to the original batch indices.
Batches may be only partially filled (i.e when completing the remainder
at the end of the validation or test set), or we may want to sort by
e.g the len... | [
"def",
"match_batch",
"(",
"self",
",",
"batch_reply",
",",
"valid_inds",
",",
"output",
"=",
"None",
")",
":",
"if",
"output",
"is",
"None",
":",
"return",
"batch_reply",
"for",
"k",
",",
"v",
"in",
"output",
".",
"items",
"(",
")",
":",
"if",
"v",
... | [
1606,
4
] | [
1645,
26
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.get_temp_history | (self, observation) |
Return a string to temporarily insert into history.
Intentionally overrideable so more complex models can insert temporary history
strings, i.e. strings that are removed from the history after a single turn.
|
Return a string to temporarily insert into history. | def get_temp_history(self, observation) -> Optional[str]:
"""
Return a string to temporarily insert into history.
Intentionally overrideable so more complex models can insert temporary history
strings, i.e. strings that are removed from the history after a single turn.
"""
... | [
"def",
"get_temp_history",
"(",
"self",
",",
"observation",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"None"
] | [
1647,
4
] | [
1654,
19
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.observe | (self, observation) |
Process incoming message in preparation for producing a response.
This includes remembering the past history of the conversation.
|
Process incoming message in preparation for producing a response. | def observe(self, observation):
"""
Process incoming message in preparation for producing a response.
This includes remembering the past history of the conversation.
"""
# TODO: Migration plan: TorchAgent currently supports being passed
# observations as vanilla dicts fo... | [
"def",
"observe",
"(",
"self",
",",
"observation",
")",
":",
"# TODO: Migration plan: TorchAgent currently supports being passed",
"# observations as vanilla dicts for legacy interop; eventually we",
"# want to remove this behavior and demand that teachers return Messages",
"observation",
"=... | [
1656,
4
] | [
1707,
9
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.self_observe | (self, self_message: Message) |
Observe one's own utterance.
This is used so that the agent can incorporate its own response into
the dialogue history after a batch_act. Failure to implement this will
result in an agent that cannot hear itself speak.
:param self_message:
The message corresponding... |
Observe one's own utterance. | def self_observe(self, self_message: Message) -> None:
"""
Observe one's own utterance.
This is used so that the agent can incorporate its own response into
the dialogue history after a batch_act. Failure to implement this will
result in an agent that cannot hear itself speak.
... | [
"def",
"self_observe",
"(",
"self",
",",
"self_message",
":",
"Message",
")",
"->",
"None",
":",
"use_reply",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'use_reply'",
",",
"'label'",
")",
"# quick check everything is in order",
"self",
".",
"_validate_self_obser... | [
1709,
4
] | [
1765,
62
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._validate_observe_invariants | (self) |
Check that we properly called self_observe after the last batch_act.
|
Check that we properly called self_observe after the last batch_act.
| def _validate_observe_invariants(self):
"""
Check that we properly called self_observe after the last batch_act.
"""
if self.__expecting_to_reply:
raise RuntimeError(
"Last observe() had a label, but no call to self_observe ever "
"happened. Yo... | [
"def",
"_validate_observe_invariants",
"(",
"self",
")",
":",
"if",
"self",
".",
"__expecting_to_reply",
":",
"raise",
"RuntimeError",
"(",
"\"Last observe() had a label, but no call to self_observe ever \"",
"\"happened. You are likely making multiple observe() calls without \"",
"\... | [
1767,
4
] | [
1785,
13
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent._validate_self_observe_invariants | (self) |
Check some invariant conditions for self_observe.
Goal is to catch potential places where we forget to call self_observe.
|
Check some invariant conditions for self_observe. | def _validate_self_observe_invariants(self):
"""
Check some invariant conditions for self_observe.
Goal is to catch potential places where we forget to call self_observe.
"""
if self.observation is None:
raise RuntimeError(
"You're self_observing with... | [
"def",
"_validate_self_observe_invariants",
"(",
"self",
")",
":",
"if",
"self",
".",
"observation",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"You're self_observing without having observed something. Check if \"",
"\"you're missing a step in your observe/act/self_observe ... | [
1787,
4
] | [
1806,
17
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.state_dict | (self) |
Get the state dict for saving.
Override this method for more specific saving.
|
Get the state dict for saving. | def state_dict(self):
"""
Get the state dict for saving.
Override this method for more specific saving.
"""
states = {}
if hasattr(self, 'model'): # save model params
if hasattr(self.model, 'module'):
# did we wrap in a DistributedDataParalle... | [
"def",
"state_dict",
"(",
"self",
")",
":",
"states",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'model'",
")",
":",
"# save model params",
"if",
"hasattr",
"(",
"self",
".",
"model",
",",
"'module'",
")",
":",
"# did we wrap in a DistributedDataPara... | [
1808,
4
] | [
1834,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.save | (self, path=None) |
Save model parameters to path (or default to model_file arg).
Please try to refrain from overriding this function, and instead override
`state_dict(self)` for more specific saving.
|
Save model parameters to path (or default to model_file arg). | def save(self, path=None):
"""
Save model parameters to path (or default to model_file arg).
Please try to refrain from overriding this function, and instead override
`state_dict(self)` for more specific saving.
"""
path = self.opt.get('model_file', None) if path is None... | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'model_file'",
",",
"None",
")",
"if",
"path",
"is",
"None",
"else",
"path",
"if",
"path",
":",
"model_dict_path",
"=",
"path",
"+",
... | [
1836,
4
] | [
1857,
44
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.load_state_dict | (self, state_dict) |
Load the state dict into model.
This is easily overridable to facilitate transfer of state dicts.
|
Load the state dict into model. | def load_state_dict(self, state_dict):
"""
Load the state dict into model.
This is easily overridable to facilitate transfer of state dicts.
"""
try:
self.model.load_state_dict(state_dict)
except RuntimeError as msg:
msg_ = str(msg)
if... | [
"def",
"load_state_dict",
"(",
"self",
",",
"state_dict",
")",
":",
"try",
":",
"self",
".",
"model",
".",
"load_state_dict",
"(",
"state_dict",
")",
"except",
"RuntimeError",
"as",
"msg",
":",
"msg_",
"=",
"str",
"(",
"msg",
")",
"if",
"'size mismatch'",
... | [
1859,
4
] | [
1884,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.load | (self, path: str) |
Return opt and model states.
Override this method for more specific loading.
|
Return opt and model states. | def load(self, path: str) -> Dict[str, Any]:
"""
Return opt and model states.
Override this method for more specific loading.
"""
import parlai.utils.pickle
with PathManager.open(path, 'rb') as f:
states = torch.load(
f, map_location=lambda c... | [
"def",
"load",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"import",
"parlai",
".",
"utils",
".",
"pickle",
"with",
"PathManager",
".",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"states"... | [
1886,
4
] | [
1902,
21
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.reset | (self) |
Clear internal states.
|
Clear internal states.
| def reset(self):
"""
Clear internal states.
"""
# assumption violation trackers
self.__expecting_clear_history = False
self.__expecting_to_reply = False
self.observation = None
self.history.reset()
self.reset_metrics() | [
"def",
"reset",
"(",
"self",
")",
":",
"# assumption violation trackers",
"self",
".",
"__expecting_clear_history",
"=",
"False",
"self",
".",
"__expecting_to_reply",
"=",
"False",
"self",
".",
"observation",
"=",
"None",
"self",
".",
"history",
".",
"reset",
"(... | [
1934,
4
] | [
1944,
28
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.reset_metrics | (self) |
Reset all TorchAgentMetrics.
|
Reset all TorchAgentMetrics.
| def reset_metrics(self):
"""
Reset all TorchAgentMetrics.
"""
super().reset_metrics()
self.global_metrics.clear() | [
"def",
"reset_metrics",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"reset_metrics",
"(",
")",
"self",
".",
"global_metrics",
".",
"clear",
"(",
")"
] | [
1946,
4
] | [
1951,
35
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.act | (self) |
Call batch_act with the singleton batch.
|
Call batch_act with the singleton batch.
| def act(self):
"""
Call batch_act with the singleton batch.
"""
# BatchWorld handles calling self_observe, but we're in a Hogwild or Interactive
# world, so we need to handle this ourselves.
response = self.batch_act([self.observation])[0]
self.self_observe(respon... | [
"def",
"act",
"(",
"self",
")",
":",
"# BatchWorld handles calling self_observe, but we're in a Hogwild or Interactive",
"# world, so we need to handle this ourselves.",
"response",
"=",
"self",
".",
"batch_act",
"(",
"[",
"self",
".",
"observation",
"]",
")",
"[",
"0",
"... | [
1953,
4
] | [
1961,
23
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.batch_act | (self, observations) |
Process a batch of observations (batchsize list of message dicts).
These observations have been preprocessed by the observe method.
Subclasses can override this for special functionality, but if the
default behaviors are fine then just override the ``train_step`` and
``eval_st... |
Process a batch of observations (batchsize list of message dicts). | def batch_act(self, observations):
"""
Process a batch of observations (batchsize list of message dicts).
These observations have been preprocessed by the observe method.
Subclasses can override this for special functionality, but if the
default behaviors are fine then just ove... | [
"def",
"batch_act",
"(",
"self",
",",
"observations",
")",
":",
"# clear local metrics before anything else",
"self",
".",
"_local_metrics",
".",
"clear",
"(",
")",
"# initialize a list of replies with this agent's id",
"batch_reply",
"=",
"[",
"Message",
"(",
"{",
"'id... | [
1963,
4
] | [
2051,
26
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.train_step | (self, batch) |
[Abstract] Process one batch with training labels.
|
[Abstract] Process one batch with training labels.
| def train_step(self, batch):
"""
[Abstract] Process one batch with training labels.
"""
pass | [
"def",
"train_step",
"(",
"self",
",",
"batch",
")",
":",
"pass"
] | [
2054,
4
] | [
2058,
12
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.eval_step | (self, batch) |
[Abstract] Process one batch but do not train on it.
|
[Abstract] Process one batch but do not train on it.
| def eval_step(self, batch):
"""
[Abstract] Process one batch but do not train on it.
"""
pass | [
"def",
"eval_step",
"(",
"self",
",",
"batch",
")",
":",
"pass"
] | [
2061,
4
] | [
2065,
12
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.set_interactive_mode | (self, mode, shared) |
Set interactive mode on or off.
|
Set interactive mode on or off.
| def set_interactive_mode(self, mode, shared):
"""
Set interactive mode on or off.
"""
if shared is None and mode:
# Only print in the non-shared version.
logging.info(f'{self.id}: full interactive mode on.') | [
"def",
"set_interactive_mode",
"(",
"self",
",",
"mode",
",",
"shared",
")",
":",
"if",
"shared",
"is",
"None",
"and",
"mode",
":",
"# Only print in the non-shared version.",
"logging",
".",
"info",
"(",
"f'{self.id}: full interactive mode on.'",
")"
] | [
2067,
4
] | [
2073,
65
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.backward | (self, loss) |
Perform a backward pass.
It is recommended you use this instead of loss.backward(), for integration with
distributed training and FP16 training.
|
Perform a backward pass. | def backward(self, loss):
"""
Perform a backward pass.
It is recommended you use this instead of loss.backward(), for integration with
distributed training and FP16 training.
"""
update_freq = self.opt.get('update_freq', 1)
if update_freq > 1:
# grad... | [
"def",
"backward",
"(",
"self",
",",
"loss",
")",
":",
"update_freq",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'update_freq'",
",",
"1",
")",
"if",
"update_freq",
">",
"1",
":",
"# gradient accumulation, but still need to average across the minibatches",
"loss",... | [
2075,
4
] | [
2103,
27
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.update_params | (self) |
Perform step of optimization.
Handles clipping gradients and adjusting LR schedule if needed.
Gradient accumulation is also performed if agent is called with
--update-freq.
It is recommended (but not forced) that you call this in train_step.
|
Perform step of optimization. | def update_params(self):
"""
Perform step of optimization.
Handles clipping gradients and adjusting LR schedule if needed.
Gradient accumulation is also performed if agent is called with
--update-freq.
It is recommended (but not forced) that you call this in train_step.... | [
"def",
"update_params",
"(",
"self",
")",
":",
"update_freq",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'update_freq'",
",",
"1",
")",
"if",
"update_freq",
">",
"1",
":",
"# we're doing gradient accumulation, so we don't only want to step",
"# every N updates instead... | [
2105,
4
] | [
2161,
62
] | python | en | ['en', 'error', 'th'] | False |
TorchAgent.zero_grad | (self) |
Zero out optimizer.
It is recommended you call this in train_step. It automatically handles gradient
accumulation if agent is called with --update-freq.
|
Zero out optimizer. | def zero_grad(self):
"""
Zero out optimizer.
It is recommended you call this in train_step. It automatically handles gradient
accumulation if agent is called with --update-freq.
"""
if self._number_grad_accum != 0:
# if we're accumulating gradients, don't act... | [
"def",
"zero_grad",
"(",
"self",
")",
":",
"if",
"self",
".",
"_number_grad_accum",
"!=",
"0",
":",
"# if we're accumulating gradients, don't actually zero things out yet.",
"return",
"self",
".",
"optimizer",
".",
"zero_grad",
"(",
")"
] | [
2163,
4
] | [
2174,
34
] | python | en | ['en', 'error', 'th'] | False |
AuditedServerSession.audit | (self, **kwargs) |
Extracts messages and system data from a Session object upon message
send or receive.
Kwargs:
src (str): Source of data; 'client' or 'server'. Indicates direction.
text (str or list): Client sends messages to server in the form of
lists. Server sends mes... |
Extracts messages and system data from a Session object upon message
send or receive. | def audit(self, **kwargs):
"""
Extracts messages and system data from a Session object upon message
send or receive.
Kwargs:
src (str): Source of data; 'client' or 'server'. Indicates direction.
text (str or list): Client sends messages to server in the form of
... | [
"def",
"audit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get time at start of processing",
"time_obj",
"=",
"timezone",
".",
"now",
"(",
")",
"time_str",
"=",
"str",
"(",
"time_obj",
")",
"session",
"=",
"self",
"src",
"=",
"kwargs",
".",
"pop"... | [
61,
4
] | [
161,
18
] | python | en | ['en', 'error', 'th'] | False |
AuditedServerSession.mask | (self, msg) |
Masks potentially sensitive user information within messages before
writing to log. Recording cleartext password attempts is bad policy.
Args:
msg (str): Raw text string sent from client <-> server
Returns:
msg (str): Text string with sensitive information mask... |
Masks potentially sensitive user information within messages before
writing to log. Recording cleartext password attempts is bad policy. | def mask(self, msg):
"""
Masks potentially sensitive user information within messages before
writing to log. Recording cleartext password attempts is bad policy.
Args:
msg (str): Raw text string sent from client <-> server
Returns:
msg (str): Text string... | [
"def",
"mask",
"(",
"self",
",",
"msg",
")",
":",
"# Check to see if the command is embedded within server output",
"_msg",
"=",
"msg",
"is_embedded",
"=",
"False",
"match",
"=",
"re",
".",
"match",
"(",
"\".*Command.*'(.+)'.*is not available.*\"",
",",
"msg",
",",
... | [
163,
4
] | [
204,
19
] | python | en | ['en', 'error', 'th'] | False |
AuditedServerSession.data_out | (self, **kwargs) |
Generic hook for sending data out through the protocol.
Kwargs:
kwargs (any): Other data to the protocol.
|
Generic hook for sending data out through the protocol. | def data_out(self, **kwargs):
"""
Generic hook for sending data out through the protocol.
Kwargs:
kwargs (any): Other data to the protocol.
"""
if AUDIT_CALLBACK and AUDIT_OUT:
try:
log = self.audit(src='server', **kwargs)
... | [
"def",
"data_out",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"AUDIT_CALLBACK",
"and",
"AUDIT_OUT",
":",
"try",
":",
"log",
"=",
"self",
".",
"audit",
"(",
"src",
"=",
"'server'",
",",
"*",
"*",
"kwargs",
")",
"if",
"log",
":",
"AUDIT_CA... | [
206,
4
] | [
222,
60
] | python | en | ['en', 'error', 'th'] | False |
AuditedServerSession.data_in | (self, **kwargs) |
Hook for protocols to send incoming data to the engine.
Kwargs:
kwargs (any): Other data from the protocol.
|
Hook for protocols to send incoming data to the engine. | def data_in(self, **kwargs):
"""
Hook for protocols to send incoming data to the engine.
Kwargs:
kwargs (any): Other data from the protocol.
"""
if AUDIT_CALLBACK and AUDIT_IN:
try:
log = self.audit(src='client', **kwargs)
... | [
"def",
"data_in",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"AUDIT_CALLBACK",
"and",
"AUDIT_IN",
":",
"try",
":",
"log",
"=",
"self",
".",
"audit",
"(",
"src",
"=",
"'client'",
",",
"*",
"*",
"kwargs",
")",
"if",
"log",
":",
"AUDIT_CALL... | [
224,
4
] | [
240,
59
] | python | en | ['en', 'error', 'th'] | False |
_transpose_hidden_state | (hidden_state) |
Transpose the hidden state so that batch is the first dimension.
RNN modules produce (num_layers x batchsize x dim) hidden state, but DataParallel
expects batch size to be first. This helper is used to ensure that we're always
outputting batch-first, in case DataParallel tries to stitch things back to... |
Transpose the hidden state so that batch is the first dimension. | def _transpose_hidden_state(hidden_state):
"""
Transpose the hidden state so that batch is the first dimension.
RNN modules produce (num_layers x batchsize x dim) hidden state, but DataParallel
expects batch size to be first. This helper is used to ensure that we're always
outputting batch-first, i... | [
"def",
"_transpose_hidden_state",
"(",
"hidden_state",
")",
":",
"if",
"isinstance",
"(",
"hidden_state",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"map",
"(",
"_transpose_hidden_state",
",",
"hidden_state",
")",
")",
"elif",
"torch",
".",
"is_tensor",
"... | [
21,
0
] | [
34,
79
] | python | en | ['en', 'error', 'th'] | False |
opt_to_kwargs | (opt) |
Get kwargs for seq2seq from opt.
|
Get kwargs for seq2seq from opt.
| def opt_to_kwargs(opt):
"""
Get kwargs for seq2seq from opt.
"""
kwargs = {}
for k in [
'numlayers',
'dropout',
'bidirectional',
'rnn_class',
'lookuptable',
'decoder',
'numsoftmax',
'attention',
'attention_length',
'atte... | [
"def",
"opt_to_kwargs",
"(",
"opt",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"k",
"in",
"[",
"'numlayers'",
",",
"'dropout'",
",",
"'bidirectional'",
",",
"'rnn_class'",
",",
"'lookuptable'",
",",
"'decoder'",
",",
"'numsoftmax'",
",",
"'attention'",
",",
... | [
37,
0
] | [
57,
17
] | python | en | ['en', 'error', 'th'] | False |
Seq2seq.__init__ | (
self,
num_features,
embeddingsize,
hiddensize,
numlayers=2,
dropout=0,
bidirectional=False,
rnn_class='lstm',
lookuptable='unique',
decoder='same',
numsoftmax=1,
attention='none',
attention_length=48,
atten... |
Initialize seq2seq model.
See cmdline args in Seq2seqAgent for description of arguments.
|
Initialize seq2seq model. | def __init__(
self,
num_features,
embeddingsize,
hiddensize,
numlayers=2,
dropout=0,
bidirectional=False,
rnn_class='lstm',
lookuptable='unique',
decoder='same',
numsoftmax=1,
attention='none',
attention_length=48,
... | [
"def",
"__init__",
"(",
"self",
",",
"num_features",
",",
"embeddingsize",
",",
"hiddensize",
",",
"numlayers",
"=",
"2",
",",
"dropout",
"=",
"0",
",",
"bidirectional",
"=",
"False",
",",
"rnn_class",
"=",
"'lstm'",
",",
"lookuptable",
"=",
"'unique'",
",... | [
67,
4
] | [
153,
9
] | python | en | ['en', 'error', 'th'] | False |
Seq2seq.reorder_encoder_states | (self, encoder_states, indices) |
Reorder encoder states according to a new set of indices.
|
Reorder encoder states according to a new set of indices.
| def reorder_encoder_states(self, encoder_states, indices):
"""
Reorder encoder states according to a new set of indices.
"""
enc_out, hidden, attn_mask = encoder_states
# make sure we swap the hidden state around, apropos multigpu settings
hidden = _transpose_hidden_stat... | [
"def",
"reorder_encoder_states",
"(",
"self",
",",
"encoder_states",
",",
"indices",
")",
":",
"enc_out",
",",
"hidden",
",",
"attn_mask",
"=",
"encoder_states",
"# make sure we swap the hidden state around, apropos multigpu settings",
"hidden",
"=",
"_transpose_hidden_state"... | [
155,
4
] | [
188,
41
] | python | en | ['en', 'error', 'th'] | False |
UnknownDropout.__init__ | (self, unknown_idx, probability) |
Initialize layer.
:param unknown_idx: index of unknown token, replace tokens with this
:param probability: during training, replaces tokens with unknown token
at this rate.
|
Initialize layer. | def __init__(self, unknown_idx, probability):
"""
Initialize layer.
:param unknown_idx: index of unknown token, replace tokens with this
:param probability: during training, replaces tokens with unknown token
at this rate.
"""
super().__init__... | [
"def",
"__init__",
"(",
"self",
",",
"unknown_idx",
",",
"probability",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"unknown_idx",
"=",
"unknown_idx",
"self",
".",
"prob",
"=",
"probability"
] | [
209,
4
] | [
219,
31
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.