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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,700 | NetEaseGame/ATX | atx/base.py | list_images | def list_images(path=['.']):
""" Return list of image files """
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | python | def list_images(path=['.']):
""" Return list of image files """
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | [
"def",
"list_images",
"(",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"for",
"image_dir",
"in",
"set",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"image_dir",
")",
":",
"continue",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"image_dir",
")",
":",
"bname",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
".",
"lower",
"(",
")",
"not",
"in",
"VALID_IMAGE_EXTS",
":",
"continue",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"filename",
")",
"yield",
"strutils",
".",
"decode",
"(",
"filepath",
")"
] | Return list of image files | [
"Return",
"list",
"of",
"image",
"files"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L94-L105 |
227,701 | NetEaseGame/ATX | atx/base.py | list_all_image | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
"""List all images under path
@return unicode list
"""
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | python | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
"""List all images under path
@return unicode list
"""
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | [
"def",
"list_all_image",
"(",
"path",
",",
"valid_exts",
"=",
"VALID_IMAGE_EXTS",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"bname",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
".",
"lower",
"(",
")",
"not",
"in",
"VALID_IMAGE_EXTS",
":",
"continue",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"yield",
"strutils",
".",
"decode",
"(",
"filepath",
")"
] | List all images under path
@return unicode list | [
"List",
"all",
"images",
"under",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L108-L118 |
227,702 | NetEaseGame/ATX | atx/base.py | search_image | def search_image(name=None, path=['.']):
"""
look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired.
"""
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | python | def search_image(name=None, path=['.']):
"""
look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired.
"""
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | [
"def",
"search_image",
"(",
"name",
"=",
"None",
",",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"name",
"=",
"strutils",
".",
"decode",
"(",
"name",
")",
"for",
"image_dir",
"in",
"path",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"image_dir",
")",
":",
"continue",
"image_dir",
"=",
"strutils",
".",
"decode",
"(",
"image_dir",
")",
"image_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"image_path",
")",
":",
"return",
"strutils",
".",
"encode",
"(",
"image_path",
")",
"for",
"image_path",
"in",
"list_all_image",
"(",
"image_dir",
")",
":",
"if",
"not",
"image_name_match",
"(",
"name",
",",
"image_path",
")",
":",
"continue",
"return",
"strutils",
".",
"encode",
"(",
"image_path",
")",
"return",
"None"
] | look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired. | [
"look",
"for",
"the",
"image",
"real",
"path",
"if",
"name",
"is",
"None",
"then",
"return",
"all",
"images",
"under",
"path",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L145-L165 |
227,703 | NetEaseGame/ATX | atx/adbkit/device.py | Device.run_cmd | def run_cmd(self, *args, **kwargs):
"""
Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec
"""
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | python | def run_cmd(self, *args, **kwargs):
"""
Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec
"""
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | [
"def",
"run_cmd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"None",
")",
"p",
"=",
"self",
".",
"raw_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"p",
".",
"communicate",
"(",
"timeout",
"=",
"timeout",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")"
] | Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec | [
"Unix",
"style",
"output",
"already",
"replace",
"\\",
"r",
"\\",
"n",
"to",
"\\",
"n"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L47-L56 |
227,704 | NetEaseGame/ATX | atx/adbkit/device.py | Device.shell | def shell(self, *args, **kwargs):
"""
Run command `adb shell`
"""
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | python | def shell(self, *args, **kwargs):
"""
Run command `adb shell`
"""
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | [
"def",
"shell",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'shell'",
"]",
"+",
"list",
"(",
"args",
")",
"return",
"self",
".",
"run_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Run command `adb shell` | [
"Run",
"command",
"adb",
"shell"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L58-L63 |
227,705 | NetEaseGame/ATX | atx/adbkit/device.py | Device.remove | def remove(self, filename):
"""
Remove file from device
"""
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | python | def remove(self, filename):
"""
Remove file from device
"""
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | [
"def",
"remove",
"(",
"self",
",",
"filename",
")",
":",
"output",
"=",
"self",
".",
"shell",
"(",
"'rm'",
",",
"filename",
")",
"# any output means rm failed.",
"return",
"False",
"if",
"output",
"else",
"True"
] | Remove file from device | [
"Remove",
"file",
"from",
"device"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L69-L75 |
227,706 | NetEaseGame/ATX | atx/adbkit/device.py | Device.display | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | python | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"(",
"0",
",",
"0",
")",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'dumpsys'",
",",
"'display'",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_DISPLAY_RE",
".",
"search",
"(",
"line",
",",
"0",
")",
"if",
"not",
"m",
":",
"continue",
"w",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"'width'",
")",
")",
"h",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"'height'",
")",
")",
"o",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"'orientation'",
")",
")",
"w",
",",
"h",
"=",
"min",
"(",
"w",
",",
"h",
")",
",",
"max",
"(",
"w",
",",
"h",
")",
"return",
"self",
".",
"Display",
"(",
"w",
",",
"h",
",",
"o",
")",
"output",
"=",
"self",
".",
"shell",
"(",
"'LD_LIBRARY_PATH=/data/local/tmp'",
",",
"self",
".",
"__minicap",
",",
"'-i'",
")",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"output",
")",
"(",
"w",
",",
"h",
",",
"o",
")",
"=",
"(",
"data",
"[",
"'width'",
"]",
",",
"data",
"[",
"'height'",
"]",
",",
"data",
"[",
"'rotation'",
"]",
"/",
"90",
")",
"return",
"self",
".",
"Display",
"(",
"w",
",",
"h",
",",
"o",
")",
"except",
"ValueError",
":",
"pass"
] | Return device width, height, rotation | [
"Return",
"device",
"width",
"height",
"rotation"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L105-L126 |
227,707 | NetEaseGame/ATX | atx/adbkit/device.py | Device.packages | def packages(self):
"""
Show all packages
"""
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | python | def packages(self):
"""
Show all packages
"""
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | [
"def",
"packages",
"(",
"self",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'package:(/[^=]+\\.apk)=([^\\s]+)'",
")",
"packages",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'pm'",
",",
"'list'",
",",
"'packages'",
",",
"'-f'",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"pattern",
".",
"match",
"(",
"line",
")",
"if",
"not",
"m",
":",
"continue",
"path",
",",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
",",
"m",
".",
"group",
"(",
"2",
")",
"packages",
".",
"append",
"(",
"self",
".",
"Package",
"(",
"name",
",",
"path",
")",
")",
"return",
"packages"
] | Show all packages | [
"Show",
"all",
"packages"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L153-L165 |
227,708 | NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_screencap | def _adb_screencap(self, scale=1.0):
"""
capture screen with adb shell screencap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_screencap(self, scale=1.0):
"""
capture screen with adb shell screencap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_screencap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'screencap-'",
",",
"suffix",
"=",
"'.png'",
")",
"local_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"prefix",
"=",
"'atx-screencap-'",
",",
"suffix",
"=",
"'.png'",
")",
"self",
".",
"shell",
"(",
"'screencap'",
",",
"'-p'",
",",
"remote_file",
")",
"try",
":",
"self",
".",
"pull",
"(",
"remote_file",
",",
"local_file",
")",
"image",
"=",
"imutils",
".",
"open_as_pillow",
"(",
"local_file",
")",
"if",
"scale",
"is",
"not",
"None",
"and",
"scale",
"!=",
"1.0",
":",
"image",
"=",
"image",
".",
"resize",
"(",
"[",
"int",
"(",
"scale",
"*",
"s",
")",
"for",
"s",
"in",
"image",
".",
"size",
"]",
",",
"Image",
".",
"BICUBIC",
")",
"rotation",
"=",
"self",
".",
"rotation",
"(",
")",
"if",
"rotation",
":",
"method",
"=",
"getattr",
"(",
"Image",
",",
"'ROTATE_{}'",
".",
"format",
"(",
"rotation",
"*",
"90",
")",
")",
"image",
"=",
"image",
".",
"transpose",
"(",
"method",
")",
"return",
"image",
"finally",
":",
"self",
".",
"remove",
"(",
"remote_file",
")",
"os",
".",
"unlink",
"(",
"local_file",
")"
] | capture screen with adb shell screencap | [
"capture",
"screen",
"with",
"adb",
"shell",
"screencap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L167-L186 |
227,709 | NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_minicap | def _adb_minicap(self, scale=1.0):
"""
capture screen with minicap
https://github.com/openstf/minicap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_minicap(self, scale=1.0):
"""
capture screen with minicap
https://github.com/openstf/minicap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_minicap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'minicap-'",
",",
"suffix",
"=",
"'.jpg'",
")",
"local_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"prefix",
"=",
"'atx-minicap-'",
",",
"suffix",
"=",
"'.jpg'",
")",
"(",
"w",
",",
"h",
",",
"r",
")",
"=",
"self",
".",
"display",
"params",
"=",
"'{x}x{y}@{rx}x{ry}/{r}'",
".",
"format",
"(",
"x",
"=",
"w",
",",
"y",
"=",
"h",
",",
"rx",
"=",
"int",
"(",
"w",
"*",
"scale",
")",
",",
"ry",
"=",
"int",
"(",
"h",
"*",
"scale",
")",
",",
"r",
"=",
"r",
"*",
"90",
")",
"try",
":",
"self",
".",
"shell",
"(",
"'LD_LIBRARY_PATH=/data/local/tmp'",
",",
"self",
".",
"__minicap",
",",
"'-s'",
",",
"'-P'",
",",
"params",
",",
"'>'",
",",
"remote_file",
")",
"self",
".",
"pull",
"(",
"remote_file",
",",
"local_file",
")",
"image",
"=",
"imutils",
".",
"open_as_pillow",
"(",
"local_file",
")",
"return",
"image",
"finally",
":",
"self",
".",
"remove",
"(",
"remote_file",
")",
"os",
".",
"unlink",
"(",
"local_file",
")"
] | capture screen with minicap
https://github.com/openstf/minicap | [
"capture",
"screen",
"with",
"minicap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L188-L205 |
227,710 | NetEaseGame/ATX | atx/adbkit/device.py | Device.screenshot | def screenshot(self, filename=None, scale=1.0, method=None):
"""
Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image
"""
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | python | def screenshot(self, filename=None, scale=1.0, method=None):
"""
Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image
"""
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"method",
"=",
"None",
")",
":",
"image",
"=",
"None",
"method",
"=",
"method",
"or",
"self",
".",
"_screenshot_method",
"if",
"method",
"==",
"'minicap'",
":",
"try",
":",
"image",
"=",
"self",
".",
"_adb_minicap",
"(",
"scale",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"\"use minicap failed, fallback to screencap. error detail: %s\"",
",",
"e",
")",
"self",
".",
"_screenshot_method",
"=",
"'screencap'",
"return",
"self",
".",
"screenshot",
"(",
"filename",
"=",
"filename",
",",
"scale",
"=",
"scale",
")",
"elif",
"method",
"==",
"'screencap'",
":",
"image",
"=",
"self",
".",
"_adb_screencap",
"(",
"scale",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No such method(%s)\"",
"%",
"method",
")",
"if",
"filename",
":",
"image",
".",
"save",
"(",
"filename",
")",
"return",
"image"
] | Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image | [
"Take",
"device",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L207-L235 |
227,711 | NetEaseGame/ATX | atx/record/android_layout.py | AndroidLayout.get_index_node | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | python | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | [
"def",
"get_index_node",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"self",
".",
"node_index",
".",
"index",
"(",
"idx",
")",
"return",
"self",
".",
"nodes",
"[",
"idx",
"]"
] | get node with iterindex `idx` | [
"get",
"node",
"with",
"iterindex",
"idx"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_layout.py#L178-L181 |
227,712 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.start | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | python | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"update_device_info",
"(",
")",
"self",
".",
"get_device_status",
"(",
"0",
")",
"# start addons.\r",
"self",
".",
"hook",
"(",
")",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_run",
")",
"self",
".",
"thread",
".",
"start",
"(",
")",
"self",
".",
"running",
"=",
"True"
] | start running in background. | [
"start",
"running",
"in",
"background",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L66-L73 |
227,713 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.analyze_frames | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | python | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | [
"def",
"analyze_frames",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",
")",
")",
"as",
"f",
":",
"obj",
"=",
"json",
".",
"load",
"(",
"f",
")",
"record",
".",
"device_info",
"=",
"obj",
"[",
"'device'",
"]",
"record",
".",
"frames",
"=",
"obj",
"[",
"'frames'",
"]",
"record",
".",
"analyze_all",
"(",
")",
"record",
".",
"save",
"(",
")"
] | generate draft from recorded frames | [
"generate",
"draft",
"from",
"recorded",
"frames"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L180-L189 |
227,714 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.process_casefile | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | python | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | [
"def",
"process_casefile",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",
")",
")",
"as",
"f",
":",
"obj",
"=",
"json",
".",
"load",
"(",
"f",
")",
"record",
".",
"device_info",
"=",
"obj",
"[",
"'device'",
"]",
"record",
".",
"frames",
"=",
"obj",
"[",
"'frames'",
"]",
"casedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'case'",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"casedir",
",",
"'case.json'",
")",
")",
"as",
"f",
":",
"record",
".",
"case_draft",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# remove old files\r",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"casedir",
")",
":",
"if",
"f",
"!=",
"'case.json'",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"casedir",
",",
"f",
")",
")",
"record",
".",
"generate_script",
"(",
")"
] | generate code from case.json | [
"generate",
"code",
"from",
"case",
".",
"json"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L192-L210 |
227,715 | NetEaseGame/ATX | atx/adbkit/client.py | Client.adb_path | def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | python | def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | [
"def",
"adb_path",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__adb_cmd",
"is",
"None",
":",
"if",
"\"ANDROID_HOME\"",
"in",
"os",
".",
"environ",
":",
"filename",
"=",
"\"adb.exe\"",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"\"adb\"",
"adb_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"\"ANDROID_HOME\"",
"]",
",",
"\"platform-tools\"",
")",
"adb_cmd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"adb_dir",
",",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"adb_cmd",
")",
":",
"raise",
"EnvironmentError",
"(",
"\"Adb not found in $ANDROID_HOME/platform-tools path: %s.\"",
"%",
"adb_dir",
")",
"else",
":",
"import",
"distutils",
"if",
"\"spawn\"",
"not",
"in",
"dir",
"(",
"distutils",
")",
":",
"import",
"distutils",
".",
"spawn",
"adb_cmd",
"=",
"distutils",
".",
"spawn",
".",
"find_executable",
"(",
"\"adb\"",
")",
"if",
"adb_cmd",
":",
"adb_cmd",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"adb_cmd",
")",
"else",
":",
"raise",
"EnvironmentError",
"(",
"\"$ANDROID_HOME environment not set.\"",
")",
"cls",
".",
"__adb_cmd",
"=",
"adb_cmd",
"return",
"cls",
".",
"__adb_cmd"
] | return adb binary full path | [
"return",
"adb",
"binary",
"full",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L52-L72 |
227,716 | NetEaseGame/ATX | atx/adbkit/client.py | Client.connect | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | python | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | [
"def",
"connect",
"(",
"self",
",",
"addr",
")",
":",
"if",
"addr",
".",
"find",
"(",
"':'",
")",
"==",
"-",
"1",
":",
"addr",
"+=",
"':5555'",
"output",
"=",
"self",
".",
"run_cmd",
"(",
"'connect'",
",",
"addr",
")",
"return",
"'unable to connect'",
"not",
"in",
"output"
] | Call adb connect
Return true when connect success | [
"Call",
"adb",
"connect",
"Return",
"true",
"when",
"connect",
"success"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L137-L145 |
227,717 | NetEaseGame/ATX | atx/cmds/screencap.py | main | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
"""
If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial
"""
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | python | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
"""
If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial
"""
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | [
"def",
"main",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"out",
"=",
"'screenshot.png'",
",",
"method",
"=",
"'minicap'",
")",
":",
"print",
"(",
"'Started screencap'",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"client",
"=",
"adbkit",
".",
"Client",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"device",
"=",
"client",
".",
"device",
"(",
"serial",
")",
"im",
"=",
"device",
".",
"screenshot",
"(",
"scale",
"=",
"scale",
")",
"im",
".",
"save",
"(",
"out",
")",
"print",
"(",
"'Time spend: %.2fs'",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
")",
"print",
"(",
"'File saved to \"%s\"'",
"%",
"out",
")",
"try",
":",
"import",
"win32clipboard",
"output",
"=",
"StringIO",
"(",
")",
"im",
".",
"convert",
"(",
"\"RGB\"",
")",
".",
"save",
"(",
"output",
",",
"\"BMP\"",
")",
"data",
"=",
"output",
".",
"getvalue",
"(",
")",
"[",
"14",
":",
"]",
"output",
".",
"close",
"(",
")",
"win32clipboard",
".",
"OpenClipboard",
"(",
")",
"win32clipboard",
".",
"EmptyClipboard",
"(",
")",
"win32clipboard",
".",
"SetClipboardData",
"(",
"win32clipboard",
".",
"CF_DIB",
",",
"data",
")",
"win32clipboard",
".",
"CloseClipboard",
"(",
")",
"print",
"(",
"'Copied to clipboard'",
")",
"except",
":",
"pass"
] | If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial | [
"If",
"minicap",
"not",
"avaliable",
"then",
"use",
"uiautomator",
"instead",
"Disable",
"scale",
"for",
"now",
".",
"Because",
"-",
"s",
"scale",
"is",
"conflict",
"of",
"-",
"s",
"serial"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/screencap.py#L14-L45 |
227,718 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.rotation | def rotation(self):
"""
Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left
"""
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | python | def rotation(self):
"""
Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left
"""
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | [
"def",
"rotation",
"(",
"self",
")",
":",
"if",
"self",
".",
"screen_rotation",
"in",
"range",
"(",
"4",
")",
":",
"return",
"self",
".",
"screen_rotation",
"return",
"self",
".",
"adb_device",
".",
"rotation",
"(",
")",
"or",
"self",
".",
"info",
"[",
"'displayRotation'",
"]"
] | Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left | [
"Rotaion",
"of",
"the",
"phone"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L192-L203 |
227,719 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.properties | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | python | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | [
"def",
"properties",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'getprop'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_PROP_PATTERN",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"props",
"[",
"m",
".",
"group",
"(",
"'key'",
")",
"]",
"=",
"m",
".",
"group",
"(",
"'value'",
")",
"return",
"props"
] | Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'} | [
"Android",
"Properties",
"extracted",
"from",
"adb",
"shell",
"getprop"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L265-L280 |
227,720 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.type | def type(self, s, enter=False, clear=False):
"""Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode
"""
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | python | def type(self, s, enter=False, clear=False):
"""Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode
"""
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | [
"def",
"type",
"(",
"self",
",",
"s",
",",
"enter",
"=",
"False",
",",
"clear",
"=",
"False",
")",
":",
"if",
"clear",
":",
"self",
".",
"clear_text",
"(",
")",
"self",
".",
"_uiauto",
".",
"send_keys",
"(",
"s",
")",
"if",
"enter",
":",
"self",
".",
"keyevent",
"(",
"'KEYCODE_ENTER'",
")"
] | Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode | [
"Input",
"some",
"text",
"this",
"method",
"has",
"been",
"tested",
"not",
"very",
"stable",
"on",
"some",
"device",
".",
"Hi",
"world",
"maybe",
"spell",
"into",
"H",
"iworld"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L436-L461 |
227,721 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.input_methods | def input_methods(self):
"""
Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService']
"""
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | python | def input_methods(self):
"""
Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService']
"""
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | [
"def",
"input_methods",
"(",
"self",
")",
":",
"imes",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'ime'",
",",
"'list'",
",",
"'-s'",
",",
"'-a'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"re",
".",
"match",
"(",
"'^.+/.+$'",
",",
"line",
")",
":",
"imes",
".",
"append",
"(",
"line",
")",
"return",
"imes"
] | Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService'] | [
"Get",
"all",
"input",
"methods"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L473-L484 |
227,722 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.current_ime | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | python | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | [
"def",
"current_ime",
"(",
"self",
")",
":",
"dumpout",
"=",
"self",
".",
"adb_shell",
"(",
"[",
"'dumpsys'",
",",
"'input_method'",
"]",
")",
"m",
"=",
"_INPUT_METHOD_RE",
".",
"search",
"(",
"dumpout",
")",
"if",
"m",
":",
"return",
"m",
".",
"group",
"(",
"1",
")"
] | Get current input method | [
"Get",
"current",
"input",
"method"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L486-L491 |
227,723 | NetEaseGame/ATX | atx/imutils.py | open_as_pillow | def open_as_pillow(filename):
""" This way can delete file immediately """
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | python | def open_as_pillow(filename):
""" This way can delete file immediately """
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | [
"def",
"open_as_pillow",
"(",
"filename",
")",
":",
"with",
"__sys_open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"BytesIO",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"Image",
".",
"open",
"(",
"data",
")"
] | This way can delete file immediately | [
"This",
"way",
"can",
"delete",
"file",
"immediately"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L71-L75 |
227,724 | NetEaseGame/ATX | atx/imutils.py | from_pillow | def from_pillow(pil_image):
""" Convert from pillow image to opencv """
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | python | def from_pillow(pil_image):
""" Convert from pillow image to opencv """
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | [
"def",
"from_pillow",
"(",
"pil_image",
")",
":",
"# convert PIL to OpenCV",
"pil_image",
"=",
"pil_image",
".",
"convert",
"(",
"'RGB'",
")",
"cv2_image",
"=",
"np",
".",
"array",
"(",
"pil_image",
")",
"# Convert RGB to BGR ",
"cv2_image",
"=",
"cv2_image",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
".",
"copy",
"(",
")",
"return",
"cv2_image"
] | Convert from pillow image to opencv | [
"Convert",
"from",
"pillow",
"image",
"to",
"opencv"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L81-L88 |
227,725 | NetEaseGame/ATX | atx/imutils.py | url_to_image | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | python | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | [
"def",
"url_to_image",
"(",
"url",
",",
"flag",
"=",
"cv2",
".",
"IMREAD_COLOR",
")",
":",
"resp",
"=",
"urlopen",
"(",
"url",
")",
"image",
"=",
"np",
".",
"asarray",
"(",
"bytearray",
"(",
"resp",
".",
"read",
"(",
")",
")",
",",
"dtype",
"=",
"\"uint8\"",
")",
"image",
"=",
"cv2",
".",
"imdecode",
"(",
"image",
",",
"flag",
")",
"return",
"image"
] | download the image, convert it to a NumPy array, and then read
it into OpenCV format | [
"download",
"the",
"image",
"convert",
"it",
"to",
"a",
"NumPy",
"array",
"and",
"then",
"read",
"it",
"into",
"OpenCV",
"format"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L97-L103 |
227,726 | NetEaseGame/ATX | atx/imutils.py | mark_point | def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | python | def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | [
"def",
"mark_point",
"(",
"img",
",",
"x",
",",
"y",
")",
":",
"overlay",
"=",
"img",
".",
"copy",
"(",
")",
"output",
"=",
"img",
".",
"copy",
"(",
")",
"alpha",
"=",
"0.5",
"radius",
"=",
"max",
"(",
"5",
",",
"min",
"(",
"img",
".",
"shape",
"[",
":",
"2",
"]",
")",
"//",
"15",
")",
"center",
"=",
"int",
"(",
"x",
")",
",",
"int",
"(",
"y",
")",
"color",
"=",
"(",
"0",
",",
"0",
",",
"255",
")",
"cv2",
".",
"circle",
"(",
"overlay",
",",
"center",
",",
"radius",
",",
"color",
",",
"-",
"1",
")",
"cv2",
".",
"addWeighted",
"(",
"overlay",
",",
"alpha",
",",
"output",
",",
"1",
"-",
"alpha",
",",
"0",
",",
"output",
")",
"return",
"output"
] | Mark a point
Args:
- img(numpy): the source image
- x, y(int): position | [
"Mark",
"a",
"point"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L139-L157 |
227,727 | NetEaseGame/ATX | atx/drivers/ios_webdriveragent.py | IOSDevice.display | def display(self):
""" Get screen width and height """
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | python | def display(self):
""" Get screen width and height """
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"session",
".",
"window_size",
"(",
")",
"return",
"Display",
"(",
"w",
"*",
"self",
".",
"scale",
",",
"h",
"*",
"self",
".",
"scale",
")"
] | Get screen width and height | [
"Get",
"screen",
"width",
"and",
"height"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/ios_webdriveragent.py#L99-L102 |
227,728 | NetEaseGame/ATX | scripts/adb_old.py | Adb.forward | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | python | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | [
"def",
"forward",
"(",
"self",
",",
"device_port",
",",
"local_port",
"=",
"None",
")",
":",
"if",
"local_port",
"is",
"None",
":",
"for",
"s",
",",
"lp",
",",
"rp",
"in",
"self",
".",
"forward_list",
"(",
")",
":",
"if",
"s",
"==",
"self",
".",
"device_serial",
"(",
")",
"and",
"rp",
"==",
"'tcp:%d'",
"%",
"device_port",
":",
"return",
"int",
"(",
"lp",
"[",
"4",
":",
"]",
")",
"return",
"self",
".",
"forward",
"(",
"device_port",
",",
"next_local_port",
"(",
"self",
".",
"server_host",
")",
")",
"else",
":",
"self",
".",
"cmd",
"(",
"\"forward\"",
",",
"\"tcp:%d\"",
"%",
"local_port",
",",
"\"tcp:%d\"",
"%",
"device_port",
")",
".",
"wait",
"(",
")",
"return",
"local_port"
] | adb port forward. return local_port | [
"adb",
"port",
"forward",
".",
"return",
"local_port"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/adb_old.py#L178-L187 |
227,729 | NetEaseGame/ATX | atx/record/android.py | touch2screen | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | python | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | [
"def",
"touch2screen",
"(",
"w",
",",
"h",
",",
"o",
",",
"x",
",",
"y",
")",
":",
"if",
"o",
"==",
"0",
":",
"return",
"x",
",",
"y",
"elif",
"o",
"==",
"1",
":",
"# landscape-right\r",
"return",
"y",
",",
"w",
"-",
"x",
"elif",
"o",
"==",
"2",
":",
"# upsidedown\r",
"return",
"w",
"-",
"x",
",",
"h",
"-",
"y",
"elif",
"o",
"==",
"3",
":",
"# landscape-left\r",
"return",
"h",
"-",
"y",
",",
"x",
"return",
"x",
",",
"y"
] | convert touch position | [
"convert",
"touch",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android.py#L342-L352 |
227,730 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report.patch_wda | def patch_wda(self):
"""
Record steps of WebDriverAgent
"""
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | python | def patch_wda(self):
"""
Record steps of WebDriverAgent
"""
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | [
"def",
"patch_wda",
"(",
"self",
")",
":",
"import",
"wda",
"def",
"_click",
"(",
"that",
")",
":",
"rawx",
",",
"rawy",
"=",
"that",
".",
"bounds",
".",
"center",
"x",
",",
"y",
"=",
"self",
".",
"d",
".",
"scale",
"*",
"rawx",
",",
"self",
".",
"d",
".",
"scale",
"*",
"rawy",
"screen_before",
"=",
"self",
".",
"_save_screenshot",
"(",
")",
"orig_click",
"=",
"pt",
".",
"get_original",
"(",
"wda",
".",
"Selector",
",",
"'click'",
")",
"screen_after",
"=",
"self",
".",
"_save_screenshot",
"(",
")",
"self",
".",
"add_step",
"(",
"'click'",
",",
"screen_before",
"=",
"screen_before",
",",
"screen_after",
"=",
"screen_after",
",",
"position",
"=",
"{",
"'x'",
":",
"x",
",",
"'y'",
":",
"y",
"}",
")",
"return",
"orig_click",
"(",
"that",
")",
"pt",
".",
"patch_item",
"(",
"wda",
".",
"Selector",
",",
"'click'",
",",
"_click",
")"
] | Record steps of WebDriverAgent | [
"Record",
"steps",
"of",
"WebDriverAgent"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L109-L127 |
227,731 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report._take_screenshot | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
"""
This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image
"""
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | python | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
"""
This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image
"""
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | [
"def",
"_take_screenshot",
"(",
"self",
",",
"screenshot",
"=",
"False",
",",
"name_prefix",
"=",
"'unknown'",
")",
":",
"if",
"isinstance",
"(",
"screenshot",
",",
"bool",
")",
":",
"if",
"not",
"screenshot",
":",
"return",
"return",
"self",
".",
"_save_screenshot",
"(",
"name_prefix",
"=",
"name_prefix",
")",
"if",
"isinstance",
"(",
"screenshot",
",",
"Image",
".",
"Image",
")",
":",
"return",
"self",
".",
"_save_screenshot",
"(",
"screen",
"=",
"screenshot",
",",
"name_prefix",
"=",
"name_prefix",
")",
"raise",
"TypeError",
"(",
"\"invalid type for func _take_screenshot: \"",
"+",
"type",
"(",
"screenshot",
")",
")"
] | This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image | [
"This",
"is",
"different",
"from",
"_save_screenshot",
".",
"The",
"return",
"value",
"maybe",
"None",
"or",
"the",
"screenshot",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L223-L238 |
227,732 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report._add_assert | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | python | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | [
"def",
"_add_assert",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# convert screenshot to relative path from <None|True|False|PIL.Image>",
"screenshot",
"=",
"kwargs",
".",
"get",
"(",
"'screenshot'",
")",
"is_success",
"=",
"kwargs",
".",
"get",
"(",
"'success'",
")",
"screenshot",
"=",
"(",
"not",
"is_success",
")",
"if",
"screenshot",
"is",
"None",
"else",
"screenshot",
"kwargs",
"[",
"'screenshot'",
"]",
"=",
"self",
".",
"_take_screenshot",
"(",
"screenshot",
"=",
"screenshot",
",",
"name_prefix",
"=",
"'assert'",
")",
"action",
"=",
"kwargs",
".",
"pop",
"(",
"'action'",
",",
"'assert'",
")",
"self",
".",
"add_step",
"(",
"action",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"is_success",
":",
"message",
"=",
"kwargs",
".",
"get",
"(",
"'message'",
")",
"frame",
",",
"filename",
",",
"line_number",
",",
"function_name",
",",
"lines",
",",
"index",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"print",
"(",
"'Assert [%s: %d] WARN: %s'",
"%",
"(",
"filename",
",",
"line_number",
",",
"message",
")",
")",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'safe'",
",",
"False",
")",
":",
"raise",
"AssertionError",
"(",
"message",
")"
] | if screenshot is None, only failed case will take screenshot | [
"if",
"screenshot",
"is",
"None",
"only",
"failed",
"case",
"will",
"take",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L251-L267 |
227,733 | Phylliade/ikpy | src/ikpy/plot_utils.py | plot_chain | def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | python | def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | [
"def",
"plot_chain",
"(",
"chain",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"# LIst of nodes and orientations",
"nodes",
"=",
"[",
"]",
"axes",
"=",
"[",
"]",
"transformation_matrixes",
"=",
"chain",
".",
"forward_kinematics",
"(",
"joints",
",",
"full_kinematics",
"=",
"True",
")",
"# Get the nodes and the orientation from the tranformation matrix",
"for",
"(",
"index",
",",
"link",
")",
"in",
"enumerate",
"(",
"chain",
".",
"links",
")",
":",
"(",
"node",
",",
"rotation",
")",
"=",
"geometry_utils",
".",
"from_transformation_matrix",
"(",
"transformation_matrixes",
"[",
"index",
"]",
")",
"nodes",
".",
"append",
"(",
"node",
")",
"rotation_axis",
"=",
"link",
".",
"_get_rotation_axis",
"(",
")",
"if",
"index",
"==",
"0",
":",
"axes",
".",
"append",
"(",
"rotation_axis",
")",
"else",
":",
"axes",
".",
"append",
"(",
"geometry_utils",
".",
"homogeneous_to_cartesian_vectors",
"(",
"np",
".",
"dot",
"(",
"transformation_matrixes",
"[",
"index",
"-",
"1",
"]",
",",
"rotation_axis",
")",
")",
")",
"# Plot the chain",
"ax",
".",
"plot",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"nodes",
"]",
",",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"nodes",
"]",
",",
"[",
"x",
"[",
"2",
"]",
"for",
"x",
"in",
"nodes",
"]",
")",
"# Plot of the nodes of the chain",
"ax",
".",
"scatter",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"nodes",
"]",
",",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"nodes",
"]",
",",
"[",
"x",
"[",
"2",
"]",
"for",
"x",
"in",
"nodes",
"]",
")",
"# Plot rotation axes",
"for",
"index",
",",
"axe",
"in",
"enumerate",
"(",
"axes",
")",
":",
"ax",
".",
"plot",
"(",
"[",
"nodes",
"[",
"index",
"]",
"[",
"0",
"]",
",",
"axe",
"[",
"0",
"]",
"]",
",",
"[",
"nodes",
"[",
"index",
"]",
"[",
"1",
"]",
",",
"axe",
"[",
"1",
"]",
"]",
",",
"[",
"nodes",
"[",
"index",
"]",
"[",
"2",
"]",
",",
"axe",
"[",
"2",
"]",
"]",
")"
] | Plots the chain | [
"Plots",
"the",
"chain"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L29-L54 |
227,734 | Phylliade/ikpy | src/ikpy/plot_utils.py | plot_target | def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | python | def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | [
"def",
"plot_target",
"(",
"target",
",",
"ax",
")",
":",
"ax",
".",
"scatter",
"(",
"target",
"[",
"0",
"]",
",",
"target",
"[",
"1",
"]",
",",
"target",
"[",
"2",
"]",
",",
"c",
"=",
"\"red\"",
",",
"s",
"=",
"80",
")"
] | Ajoute la target au plot | [
"Ajoute",
"la",
"target",
"au",
"plot"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L57-L59 |
227,735 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Rx_matrix | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | python | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | [
"def",
"Rx_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"0",
",",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"np",
".",
"cos",
"(",
"theta",
")",
"]",
"]",
")"
] | Rotation matrix around the X axis | [
"Rotation",
"matrix",
"around",
"the",
"X",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L10-L16 |
227,736 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Rz_matrix | def Rz_matrix(theta):
"""Rotation matrix around the Z axis"""
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | python | def Rz_matrix(theta):
"""Rotation matrix around the Z axis"""
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | [
"def",
"Rz_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")"
] | Rotation matrix around the Z axis | [
"Rotation",
"matrix",
"around",
"the",
"Z",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L19-L25 |
227,737 | Phylliade/ikpy | src/ikpy/geometry_utils.py | symbolic_Rz_matrix | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | python | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | [
"def",
"symbolic_Rz_matrix",
"(",
"symbolic_theta",
")",
":",
"return",
"sympy",
".",
"Matrix",
"(",
"[",
"[",
"sympy",
".",
"cos",
"(",
"symbolic_theta",
")",
",",
"-",
"sympy",
".",
"sin",
"(",
"symbolic_theta",
")",
",",
"0",
"]",
",",
"[",
"sympy",
".",
"sin",
"(",
"symbolic_theta",
")",
",",
"sympy",
".",
"cos",
"(",
"symbolic_theta",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")"
] | Matrice symbolique de rotation autour de l'axe Z | [
"Matrice",
"symbolique",
"de",
"rotation",
"autour",
"de",
"l",
"axe",
"Z"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L28-L34 |
227,738 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Ry_matrix | def Ry_matrix(theta):
"""Rotation matrix around the Y axis"""
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | python | def Ry_matrix(theta):
"""Rotation matrix around the Y axis"""
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | [
"def",
"Ry_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
",",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
",",
"np",
".",
"cos",
"(",
"theta",
")",
"]",
"]",
")"
] | Rotation matrix around the Y axis | [
"Rotation",
"matrix",
"around",
"the",
"Y",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L37-L43 |
227,739 | Phylliade/ikpy | src/ikpy/geometry_utils.py | rpy_matrix | def rpy_matrix(roll, pitch, yaw):
"""Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates"""
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | python | def rpy_matrix(roll, pitch, yaw):
"""Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates"""
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | [
"def",
"rpy_matrix",
"(",
"roll",
",",
"pitch",
",",
"yaw",
")",
":",
"return",
"np",
".",
"dot",
"(",
"Rz_matrix",
"(",
"yaw",
")",
",",
"np",
".",
"dot",
"(",
"Ry_matrix",
"(",
"pitch",
")",
",",
"Rx_matrix",
"(",
"roll",
")",
")",
")"
] | Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates | [
"Returns",
"a",
"rotation",
"matrix",
"described",
"by",
"the",
"extrinsinc",
"roll",
"pitch",
"yaw",
"coordinates"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L56-L58 |
227,740 | Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
"""Converts a cartesian matrix to an homogenous matrix"""
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | python | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
"""Converts a cartesian matrix to an homogenous matrix"""
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | [
"def",
"cartesian_to_homogeneous",
"(",
"cartesian_matrix",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
",",
"dimension_y",
"=",
"cartesian_matrix",
".",
"shape",
"# Square matrix",
"# Manage different types fo input matrixes",
"if",
"matrix_type",
"==",
"\"numpy\"",
":",
"homogeneous_matrix",
"=",
"np",
".",
"eye",
"(",
"dimension_x",
"+",
"1",
")",
"elif",
"matrix_type",
"==",
"\"sympy\"",
":",
"homogeneous_matrix",
"=",
"sympy",
".",
"eye",
"(",
"dimension_x",
"+",
"1",
")",
"# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one",
"homogeneous_matrix",
"[",
":",
"-",
"1",
",",
":",
"-",
"1",
"]",
"=",
"cartesian_matrix",
"return",
"homogeneous_matrix"
] | Converts a cartesian matrix to an homogenous matrix | [
"Converts",
"a",
"cartesian",
"matrix",
"to",
"an",
"homogenous",
"matrix"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L112-L124 |
227,741 | Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous_vectors | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
"""Converts a cartesian vector to an homogenous vector"""
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | python | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
"""Converts a cartesian vector to an homogenous vector"""
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | [
"def",
"cartesian_to_homogeneous_vectors",
"(",
"cartesian_vector",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
"=",
"cartesian_vector",
".",
"shape",
"[",
"0",
"]",
"# Vector",
"if",
"matrix_type",
"==",
"\"numpy\"",
":",
"homogeneous_vector",
"=",
"np",
".",
"zeros",
"(",
"dimension_x",
"+",
"1",
")",
"# Last item is a 1",
"homogeneous_vector",
"[",
"-",
"1",
"]",
"=",
"1",
"homogeneous_vector",
"[",
":",
"-",
"1",
"]",
"=",
"cartesian_vector",
"return",
"homogeneous_vector"
] | Converts a cartesian vector to an homogenous vector | [
"Converts",
"a",
"cartesian",
"vector",
"to",
"an",
"homogenous",
"vector"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L127-L136 |
227,742 | Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_joint | def find_next_joint(root, current_link, next_joint_name):
"""
Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
"""
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | python | def find_next_joint(root, current_link, next_joint_name):
"""
Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
"""
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | [
"def",
"find_next_joint",
"(",
"root",
",",
"current_link",
",",
"next_joint_name",
")",
":",
"# Find the joint attached to the link",
"has_next",
"=",
"False",
"next_joint",
"=",
"None",
"search_by_name",
"=",
"True",
"current_link_name",
"=",
"None",
"if",
"next_joint_name",
"is",
"None",
":",
"# If no next joint is provided, find it automatically",
"search_by_name",
"=",
"False",
"current_link_name",
"=",
"current_link",
".",
"attrib",
"[",
"\"name\"",
"]",
"for",
"joint",
"in",
"root",
".",
"iter",
"(",
"\"joint\"",
")",
":",
"# Iterate through all joints to find the good one",
"if",
"search_by_name",
":",
"# Find the joint given its name",
"if",
"joint",
".",
"attrib",
"[",
"\"name\"",
"]",
"==",
"next_joint_name",
":",
"has_next",
"=",
"True",
"next_joint",
"=",
"joint",
"else",
":",
"# Find the first joint whose parent is the current_link",
"# FIXME: We are not sending a warning when we have two children for the same link",
"# Even if this is not possible, we should ensure something coherent",
"if",
"joint",
".",
"find",
"(",
"\"parent\"",
")",
".",
"attrib",
"[",
"\"link\"",
"]",
"==",
"current_link_name",
":",
"has_next",
"=",
"True",
"next_joint",
"=",
"joint",
"break",
"return",
"has_next",
",",
"next_joint"
] | Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link. | [
"Find",
"the",
"next",
"joint",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L16-L55 |
227,743 | Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_link | def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
"""
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | python | def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
"""
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | [
"def",
"find_next_link",
"(",
"root",
",",
"current_joint",
",",
"next_link_name",
")",
":",
"has_next",
"=",
"False",
"next_link",
"=",
"None",
"# If no next link, find it automatically",
"if",
"next_link_name",
"is",
"None",
":",
"# If the name of the next link is not provided, find it",
"next_link_name",
"=",
"current_joint",
".",
"find",
"(",
"\"child\"",
")",
".",
"attrib",
"[",
"\"link\"",
"]",
"for",
"urdf_link",
"in",
"root",
".",
"iter",
"(",
"\"link\"",
")",
":",
"if",
"urdf_link",
".",
"attrib",
"[",
"\"name\"",
"]",
"==",
"next_link_name",
":",
"next_link",
"=",
"urdf_link",
"has_next",
"=",
"True",
"return",
"has_next",
",",
"next_link"
] | Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint. | [
"Find",
"the",
"next",
"link",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L58-L82 |
227,744 | Phylliade/ikpy | src/ikpy/URDF_utils.py | get_urdf_parameters | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
"""
Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink]
"""
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | python | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
"""
Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink]
"""
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | [
"def",
"get_urdf_parameters",
"(",
"urdf_file",
",",
"base_elements",
"=",
"None",
",",
"last_link_vector",
"=",
"None",
",",
"base_element_type",
"=",
"\"link\"",
")",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"urdf_file",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"base_elements",
"=",
"list",
"(",
"base_elements",
")",
"if",
"base_elements",
"is",
"None",
":",
"base_elements",
"=",
"[",
"\"base_link\"",
"]",
"elif",
"base_elements",
"is",
"[",
"]",
":",
"raise",
"ValueError",
"(",
"\"base_elements can't be the empty list []\"",
")",
"joints",
"=",
"[",
"]",
"links",
"=",
"[",
"]",
"has_next",
"=",
"True",
"current_joint",
"=",
"None",
"current_link",
"=",
"None",
"# Initialize the tree traversal",
"if",
"base_element_type",
"==",
"\"link\"",
":",
"# The first element is a link, so its (virtual) parent should be a joint",
"node_type",
"=",
"\"joint\"",
"elif",
"base_element_type",
"==",
"\"joint\"",
":",
"# The same as before, but swap link and joint",
"node_type",
"=",
"\"link\"",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown type: {}\"",
".",
"format",
"(",
"base_element_type",
")",
")",
"# Parcours récursif de la structure de la chain",
"while",
"has_next",
":",
"if",
"len",
"(",
"base_elements",
")",
"!=",
"0",
":",
"next_element",
"=",
"base_elements",
".",
"pop",
"(",
"0",
")",
"else",
":",
"next_element",
"=",
"None",
"if",
"node_type",
"==",
"\"link\"",
":",
"# Current element is a link, find child joint",
"(",
"has_next",
",",
"current_joint",
")",
"=",
"find_next_joint",
"(",
"root",
",",
"current_link",
",",
"next_element",
")",
"node_type",
"=",
"\"joint\"",
"if",
"has_next",
":",
"joints",
".",
"append",
"(",
"current_joint",
")",
"elif",
"node_type",
"==",
"\"joint\"",
":",
"# Current element is a joint, find child link",
"(",
"has_next",
",",
"current_link",
")",
"=",
"find_next_link",
"(",
"root",
",",
"current_joint",
",",
"next_element",
")",
"node_type",
"=",
"\"link\"",
"if",
"has_next",
":",
"links",
".",
"append",
"(",
"current_link",
")",
"parameters",
"=",
"[",
"]",
"# Save the joints in the good format",
"for",
"joint",
"in",
"joints",
":",
"translation",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"orientation",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"rotation",
"=",
"[",
"1",
",",
"0",
",",
"0",
"]",
"bounds",
"=",
"[",
"None",
",",
"None",
"]",
"origin",
"=",
"joint",
".",
"find",
"(",
"\"origin\"",
")",
"if",
"origin",
"is",
"not",
"None",
":",
"if",
"origin",
".",
"attrib",
"[",
"\"xyz\"",
"]",
":",
"translation",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"origin",
".",
"attrib",
"[",
"\"xyz\"",
"]",
".",
"split",
"(",
")",
"]",
"if",
"origin",
".",
"attrib",
"[",
"\"rpy\"",
"]",
":",
"orientation",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"origin",
".",
"attrib",
"[",
"\"rpy\"",
"]",
".",
"split",
"(",
")",
"]",
"axis",
"=",
"joint",
".",
"find",
"(",
"\"axis\"",
")",
"if",
"axis",
"is",
"not",
"None",
":",
"rotation",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"axis",
".",
"attrib",
"[",
"\"xyz\"",
"]",
".",
"split",
"(",
")",
"]",
"limit",
"=",
"joint",
".",
"find",
"(",
"\"limit\"",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"if",
"limit",
".",
"attrib",
"[",
"\"lower\"",
"]",
":",
"bounds",
"[",
"0",
"]",
"=",
"float",
"(",
"limit",
".",
"attrib",
"[",
"\"lower\"",
"]",
")",
"if",
"limit",
".",
"attrib",
"[",
"\"upper\"",
"]",
":",
"bounds",
"[",
"1",
"]",
"=",
"float",
"(",
"limit",
".",
"attrib",
"[",
"\"upper\"",
"]",
")",
"parameters",
".",
"append",
"(",
"lib_link",
".",
"URDFLink",
"(",
"name",
"=",
"joint",
".",
"attrib",
"[",
"\"name\"",
"]",
",",
"bounds",
"=",
"tuple",
"(",
"bounds",
")",
",",
"translation_vector",
"=",
"translation",
",",
"orientation",
"=",
"orientation",
",",
"rotation",
"=",
"rotation",
",",
")",
")",
"# Add last_link_vector to parameters",
"if",
"last_link_vector",
"is",
"not",
"None",
":",
"parameters",
".",
"append",
"(",
"lib_link",
".",
"URDFLink",
"(",
"translation_vector",
"=",
"last_link_vector",
",",
"orientation",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"rotation",
"=",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"name",
"=",
"\"last_joint\"",
")",
")",
"return",
"parameters"
] | Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink] | [
"Returns",
"translated",
"parameters",
"from",
"the",
"given",
"URDF",
"file"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L103-L210 |
227,745 | Phylliade/ikpy | src/ikpy/URDF_utils.py | _convert_angle_limit | def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | python | def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | [
"def",
"_convert_angle_limit",
"(",
"angle",
",",
"joint",
",",
"*",
"*",
"kwargs",
")",
":",
"angle_pypot",
"=",
"angle",
"# No need to take care of orientation",
"if",
"joint",
"[",
"\"orientation\"",
"]",
"==",
"\"indirect\"",
":",
"angle_pypot",
"=",
"1",
"*",
"angle_pypot",
"# angle_pypot = angle_pypot + offset",
"return",
"angle_pypot",
"*",
"np",
".",
"pi",
"/",
"180"
] | Converts the limit angle of the PyPot JSON file to the internal format | [
"Converts",
"the",
"limit",
"angle",
"of",
"the",
"PyPot",
"JSON",
"file",
"to",
"the",
"internal",
"format"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L261-L271 |
227,746 | Phylliade/ikpy | scripts/hand_follow.py | follow_hand | def follow_hand(poppy, delta):
"""Tell the right hand to follow the left hand"""
right_arm_position = poppy.l_arm_chain.end_effector + delta
poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True) | python | def follow_hand(poppy, delta):
"""Tell the right hand to follow the left hand"""
right_arm_position = poppy.l_arm_chain.end_effector + delta
poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True) | [
"def",
"follow_hand",
"(",
"poppy",
",",
"delta",
")",
":",
"right_arm_position",
"=",
"poppy",
".",
"l_arm_chain",
".",
"end_effector",
"+",
"delta",
"poppy",
".",
"r_arm_chain",
".",
"goto",
"(",
"right_arm_position",
",",
"0.5",
",",
"wait",
"=",
"True",
")"
] | Tell the right hand to follow the left hand | [
"Tell",
"the",
"right",
"hand",
"to",
"follow",
"the",
"left",
"hand"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/scripts/hand_follow.py#L27-L30 |
227,747 | Phylliade/ikpy | src/ikpy/inverse_kinematics.py | inverse_kinematic_optimization | def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
"""
Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of your chain.
regularization_parameter: float
The coefficient of the regularization.
max_iter: int
Maximum number of iterations for the optimisation algorithm.
"""
# Only get the position
target = target_frame[:3, 3]
if starting_nodes_angles is None:
raise ValueError("starting_nodes_angles must be specified")
# Compute squared distance to target
def optimize_target(x):
# y = np.append(starting_nodes_angles[:chain.first_active_joint], x)
y = chain.active_to_full(x, starting_nodes_angles)
squared_distance = np.linalg.norm(chain.forward_kinematics(y)[:3, -1] - target)
return squared_distance
# If a regularization is selected
if regularization_parameter is not None:
def optimize_total(x):
regularization = np.linalg.norm(x - starting_nodes_angles[chain.first_active_joint:])
return optimize_target(x) + regularization_parameter * regularization
else:
def optimize_total(x):
return optimize_target(x)
# Compute bounds
real_bounds = [link.bounds for link in chain.links]
# real_bounds = real_bounds[chain.first_active_joint:]
real_bounds = chain.active_from_full(real_bounds)
options = {}
# Manage iterations maximum
if max_iter is not None:
options["maxiter"] = max_iter
# Utilisation d'une optimisation L-BFGS-B
res = scipy.optimize.minimize(optimize_total, chain.active_from_full(starting_nodes_angles), method='L-BFGS-B', bounds=real_bounds, options=options)
logs.manager.info("Inverse kinematic optimisation OK, done in {} iterations".format(res.nit))
return chain.active_to_full(res.x, starting_nodes_angles) | python | def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
"""
Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of your chain.
regularization_parameter: float
The coefficient of the regularization.
max_iter: int
Maximum number of iterations for the optimisation algorithm.
"""
# Only get the position
target = target_frame[:3, 3]
if starting_nodes_angles is None:
raise ValueError("starting_nodes_angles must be specified")
# Compute squared distance to target
def optimize_target(x):
# y = np.append(starting_nodes_angles[:chain.first_active_joint], x)
y = chain.active_to_full(x, starting_nodes_angles)
squared_distance = np.linalg.norm(chain.forward_kinematics(y)[:3, -1] - target)
return squared_distance
# If a regularization is selected
if regularization_parameter is not None:
def optimize_total(x):
regularization = np.linalg.norm(x - starting_nodes_angles[chain.first_active_joint:])
return optimize_target(x) + regularization_parameter * regularization
else:
def optimize_total(x):
return optimize_target(x)
# Compute bounds
real_bounds = [link.bounds for link in chain.links]
# real_bounds = real_bounds[chain.first_active_joint:]
real_bounds = chain.active_from_full(real_bounds)
options = {}
# Manage iterations maximum
if max_iter is not None:
options["maxiter"] = max_iter
# Utilisation d'une optimisation L-BFGS-B
res = scipy.optimize.minimize(optimize_total, chain.active_from_full(starting_nodes_angles), method='L-BFGS-B', bounds=real_bounds, options=options)
logs.manager.info("Inverse kinematic optimisation OK, done in {} iterations".format(res.nit))
return chain.active_to_full(res.x, starting_nodes_angles) | [
"def",
"inverse_kinematic_optimization",
"(",
"chain",
",",
"target_frame",
",",
"starting_nodes_angles",
",",
"regularization_parameter",
"=",
"None",
",",
"max_iter",
"=",
"None",
")",
":",
"# Only get the position",
"target",
"=",
"target_frame",
"[",
":",
"3",
",",
"3",
"]",
"if",
"starting_nodes_angles",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"starting_nodes_angles must be specified\"",
")",
"# Compute squared distance to target",
"def",
"optimize_target",
"(",
"x",
")",
":",
"# y = np.append(starting_nodes_angles[:chain.first_active_joint], x)",
"y",
"=",
"chain",
".",
"active_to_full",
"(",
"x",
",",
"starting_nodes_angles",
")",
"squared_distance",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"chain",
".",
"forward_kinematics",
"(",
"y",
")",
"[",
":",
"3",
",",
"-",
"1",
"]",
"-",
"target",
")",
"return",
"squared_distance",
"# If a regularization is selected",
"if",
"regularization_parameter",
"is",
"not",
"None",
":",
"def",
"optimize_total",
"(",
"x",
")",
":",
"regularization",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"x",
"-",
"starting_nodes_angles",
"[",
"chain",
".",
"first_active_joint",
":",
"]",
")",
"return",
"optimize_target",
"(",
"x",
")",
"+",
"regularization_parameter",
"*",
"regularization",
"else",
":",
"def",
"optimize_total",
"(",
"x",
")",
":",
"return",
"optimize_target",
"(",
"x",
")",
"# Compute bounds",
"real_bounds",
"=",
"[",
"link",
".",
"bounds",
"for",
"link",
"in",
"chain",
".",
"links",
"]",
"# real_bounds = real_bounds[chain.first_active_joint:]",
"real_bounds",
"=",
"chain",
".",
"active_from_full",
"(",
"real_bounds",
")",
"options",
"=",
"{",
"}",
"# Manage iterations maximum",
"if",
"max_iter",
"is",
"not",
"None",
":",
"options",
"[",
"\"maxiter\"",
"]",
"=",
"max_iter",
"# Utilisation d'une optimisation L-BFGS-B",
"res",
"=",
"scipy",
".",
"optimize",
".",
"minimize",
"(",
"optimize_total",
",",
"chain",
".",
"active_from_full",
"(",
"starting_nodes_angles",
")",
",",
"method",
"=",
"'L-BFGS-B'",
",",
"bounds",
"=",
"real_bounds",
",",
"options",
"=",
"options",
")",
"logs",
".",
"manager",
".",
"info",
"(",
"\"Inverse kinematic optimisation OK, done in {} iterations\"",
".",
"format",
"(",
"res",
".",
"nit",
")",
")",
"return",
"chain",
".",
"active_to_full",
"(",
"res",
".",
"x",
",",
"starting_nodes_angles",
")"
] | Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of your chain.
regularization_parameter: float
The coefficient of the regularization.
max_iter: int
Maximum number of iterations for the optimisation algorithm. | [
"Computes",
"the",
"inverse",
"kinematic",
"on",
"the",
"specified",
"target",
"with",
"an",
"optimization",
"method"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/inverse_kinematics.py#L7-L61 |
227,748 | Phylliade/ikpy | src/ikpy/chain.py | Chain.forward_kinematics | def forward_kinematics(self, joints, full_kinematics=False):
"""Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Returns
-------
frame_matrix:
The transformation matrix
"""
frame_matrix = np.eye(4)
if full_kinematics:
frame_matrixes = []
if len(self.links) != len(joints):
raise ValueError("Your joints vector length is {} but you have {} links".format(len(joints), len(self.links)))
for index, (link, joint_angle) in enumerate(zip(self.links, joints)):
# Compute iteratively the position
# NB : Use asarray to avoid old sympy problems
frame_matrix = np.dot(frame_matrix, np.asarray(link.get_transformation_matrix(joint_angle)))
if full_kinematics:
# rotation_axe = np.dot(frame_matrix, link.rotation)
frame_matrixes.append(frame_matrix)
# Return the matrix, or matrixes
if full_kinematics:
return frame_matrixes
else:
return frame_matrix | python | def forward_kinematics(self, joints, full_kinematics=False):
"""Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Returns
-------
frame_matrix:
The transformation matrix
"""
frame_matrix = np.eye(4)
if full_kinematics:
frame_matrixes = []
if len(self.links) != len(joints):
raise ValueError("Your joints vector length is {} but you have {} links".format(len(joints), len(self.links)))
for index, (link, joint_angle) in enumerate(zip(self.links, joints)):
# Compute iteratively the position
# NB : Use asarray to avoid old sympy problems
frame_matrix = np.dot(frame_matrix, np.asarray(link.get_transformation_matrix(joint_angle)))
if full_kinematics:
# rotation_axe = np.dot(frame_matrix, link.rotation)
frame_matrixes.append(frame_matrix)
# Return the matrix, or matrixes
if full_kinematics:
return frame_matrixes
else:
return frame_matrix | [
"def",
"forward_kinematics",
"(",
"self",
",",
"joints",
",",
"full_kinematics",
"=",
"False",
")",
":",
"frame_matrix",
"=",
"np",
".",
"eye",
"(",
"4",
")",
"if",
"full_kinematics",
":",
"frame_matrixes",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
"links",
")",
"!=",
"len",
"(",
"joints",
")",
":",
"raise",
"ValueError",
"(",
"\"Your joints vector length is {} but you have {} links\"",
".",
"format",
"(",
"len",
"(",
"joints",
")",
",",
"len",
"(",
"self",
".",
"links",
")",
")",
")",
"for",
"index",
",",
"(",
"link",
",",
"joint_angle",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"links",
",",
"joints",
")",
")",
":",
"# Compute iteratively the position",
"# NB : Use asarray to avoid old sympy problems",
"frame_matrix",
"=",
"np",
".",
"dot",
"(",
"frame_matrix",
",",
"np",
".",
"asarray",
"(",
"link",
".",
"get_transformation_matrix",
"(",
"joint_angle",
")",
")",
")",
"if",
"full_kinematics",
":",
"# rotation_axe = np.dot(frame_matrix, link.rotation)",
"frame_matrixes",
".",
"append",
"(",
"frame_matrix",
")",
"# Return the matrix, or matrixes",
"if",
"full_kinematics",
":",
"return",
"frame_matrixes",
"else",
":",
"return",
"frame_matrix"
] | Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Returns
-------
frame_matrix:
The transformation matrix | [
"Returns",
"the",
"transformation",
"matrix",
"of",
"the",
"forward",
"kinematics"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L48-L83 |
227,749 | Phylliade/ikpy | src/ikpy/chain.py | Chain.inverse_kinematics | def inverse_kinematics(self, target, initial_position=None, **kwargs):
"""Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initial_position: numpy.array
Optional : the initial position of each joint of the chain. Defaults to 0 for each joint
Returns
-------
The list of the positions of each joint according to the target. Note : Inactive joints are in the list.
"""
# Checks on input
target = np.array(target)
if target.shape != (4, 4):
raise ValueError("Your target must be a 4x4 transformation matrix")
if initial_position is None:
initial_position = [0] * len(self.links)
return ik.inverse_kinematic_optimization(self, target, starting_nodes_angles=initial_position, **kwargs) | python | def inverse_kinematics(self, target, initial_position=None, **kwargs):
"""Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initial_position: numpy.array
Optional : the initial position of each joint of the chain. Defaults to 0 for each joint
Returns
-------
The list of the positions of each joint according to the target. Note : Inactive joints are in the list.
"""
# Checks on input
target = np.array(target)
if target.shape != (4, 4):
raise ValueError("Your target must be a 4x4 transformation matrix")
if initial_position is None:
initial_position = [0] * len(self.links)
return ik.inverse_kinematic_optimization(self, target, starting_nodes_angles=initial_position, **kwargs) | [
"def",
"inverse_kinematics",
"(",
"self",
",",
"target",
",",
"initial_position",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Checks on input",
"target",
"=",
"np",
".",
"array",
"(",
"target",
")",
"if",
"target",
".",
"shape",
"!=",
"(",
"4",
",",
"4",
")",
":",
"raise",
"ValueError",
"(",
"\"Your target must be a 4x4 transformation matrix\"",
")",
"if",
"initial_position",
"is",
"None",
":",
"initial_position",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"self",
".",
"links",
")",
"return",
"ik",
".",
"inverse_kinematic_optimization",
"(",
"self",
",",
"target",
",",
"starting_nodes_angles",
"=",
"initial_position",
",",
"*",
"*",
"kwargs",
")"
] | Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initial_position: numpy.array
Optional : the initial position of each joint of the chain. Defaults to 0 for each joint
Returns
-------
The list of the positions of each joint according to the target. Note : Inactive joints are in the list. | [
"Computes",
"the",
"inverse",
"kinematic",
"on",
"the",
"specified",
"target"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L85-L107 |
227,750 | Phylliade/ikpy | src/ikpy/chain.py | Chain.plot | def plot(self, joints, ax, target=None, show=False):
"""Plots the Chain using Matplotlib
Parameters
----------
joints: list
The list of the positions of each joint
ax: matplotlib.axes.Axes
A matplotlib axes
target: numpy.array
An optional target
show: bool
Display the axe. Defaults to False
"""
from . import plot_utils
if ax is None:
# If ax is not given, create one
ax = plot_utils.init_3d_figure()
plot_utils.plot_chain(self, joints, ax)
plot_utils.plot_basis(ax, self._length)
# Plot the goal position
if target is not None:
plot_utils.plot_target(target, ax)
if show:
plot_utils.show_figure() | python | def plot(self, joints, ax, target=None, show=False):
"""Plots the Chain using Matplotlib
Parameters
----------
joints: list
The list of the positions of each joint
ax: matplotlib.axes.Axes
A matplotlib axes
target: numpy.array
An optional target
show: bool
Display the axe. Defaults to False
"""
from . import plot_utils
if ax is None:
# If ax is not given, create one
ax = plot_utils.init_3d_figure()
plot_utils.plot_chain(self, joints, ax)
plot_utils.plot_basis(ax, self._length)
# Plot the goal position
if target is not None:
plot_utils.plot_target(target, ax)
if show:
plot_utils.show_figure() | [
"def",
"plot",
"(",
"self",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"from",
".",
"import",
"plot_utils",
"if",
"ax",
"is",
"None",
":",
"# If ax is not given, create one",
"ax",
"=",
"plot_utils",
".",
"init_3d_figure",
"(",
")",
"plot_utils",
".",
"plot_chain",
"(",
"self",
",",
"joints",
",",
"ax",
")",
"plot_utils",
".",
"plot_basis",
"(",
"ax",
",",
"self",
".",
"_length",
")",
"# Plot the goal position",
"if",
"target",
"is",
"not",
"None",
":",
"plot_utils",
".",
"plot_target",
"(",
"target",
",",
"ax",
")",
"if",
"show",
":",
"plot_utils",
".",
"show_figure",
"(",
")"
] | Plots the Chain using Matplotlib
Parameters
----------
joints: list
The list of the positions of each joint
ax: matplotlib.axes.Axes
A matplotlib axes
target: numpy.array
An optional target
show: bool
Display the axe. Defaults to False | [
"Plots",
"the",
"Chain",
"using",
"Matplotlib"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L109-L135 |
227,751 | Phylliade/ikpy | src/ikpy/chain.py | Chain.from_urdf_file | def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"):
"""Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
name: str
The name of the Chain
base_element_type: str
active_links_mask: list[bool]
"""
if base_elements is None:
base_elements = ["base_link"]
links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last_link_vector=last_link_vector, base_element_type=base_element_type)
# Add an origin link at the beginning
return cls([link_lib.OriginLink()] + links, active_links_mask=active_links_mask, name=name) | python | def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"):
"""Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
name: str
The name of the Chain
base_element_type: str
active_links_mask: list[bool]
"""
if base_elements is None:
base_elements = ["base_link"]
links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last_link_vector=last_link_vector, base_element_type=base_element_type)
# Add an origin link at the beginning
return cls([link_lib.OriginLink()] + links, active_links_mask=active_links_mask, name=name) | [
"def",
"from_urdf_file",
"(",
"cls",
",",
"urdf_file",
",",
"base_elements",
"=",
"None",
",",
"last_link_vector",
"=",
"None",
",",
"base_element_type",
"=",
"\"link\"",
",",
"active_links_mask",
"=",
"None",
",",
"name",
"=",
"\"chain\"",
")",
":",
"if",
"base_elements",
"is",
"None",
":",
"base_elements",
"=",
"[",
"\"base_link\"",
"]",
"links",
"=",
"URDF_utils",
".",
"get_urdf_parameters",
"(",
"urdf_file",
",",
"base_elements",
"=",
"base_elements",
",",
"last_link_vector",
"=",
"last_link_vector",
",",
"base_element_type",
"=",
"base_element_type",
")",
"# Add an origin link at the beginning",
"return",
"cls",
"(",
"[",
"link_lib",
".",
"OriginLink",
"(",
")",
"]",
"+",
"links",
",",
"active_links_mask",
"=",
"active_links_mask",
",",
"name",
"=",
"name",
")"
] | Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
name: str
The name of the Chain
base_element_type: str
active_links_mask: list[bool] | [
"Creates",
"a",
"chain",
"from",
"an",
"URDF",
"file"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L138-L159 |
227,752 | blockchain-certificates/cert-issuer | cert_issuer/signer.py | check_internet_off | def check_internet_off(secrets_file_path):
"""If internet off and USB plugged in, returns true. Else, continues to wait..."""
while True:
if internet_on() is False and os.path.exists(secrets_file_path):
break
else:
print("Turn off your internet and plug in your USB to continue...")
time.sleep(10)
return True | python | def check_internet_off(secrets_file_path):
"""If internet off and USB plugged in, returns true. Else, continues to wait..."""
while True:
if internet_on() is False and os.path.exists(secrets_file_path):
break
else:
print("Turn off your internet and plug in your USB to continue...")
time.sleep(10)
return True | [
"def",
"check_internet_off",
"(",
"secrets_file_path",
")",
":",
"while",
"True",
":",
"if",
"internet_on",
"(",
")",
"is",
"False",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"secrets_file_path",
")",
":",
"break",
"else",
":",
"print",
"(",
"\"Turn off your internet and plug in your USB to continue...\"",
")",
"time",
".",
"sleep",
"(",
"10",
")",
"return",
"True"
] | If internet off and USB plugged in, returns true. Else, continues to wait... | [
"If",
"internet",
"off",
"and",
"USB",
"plugged",
"in",
"returns",
"true",
".",
"Else",
"continues",
"to",
"wait",
"..."
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L66-L74 |
227,753 | blockchain-certificates/cert-issuer | cert_issuer/signer.py | check_internet_on | def check_internet_on(secrets_file_path):
"""If internet on and USB unplugged, returns true. Else, continues to wait..."""
while True:
if internet_on() is True and not os.path.exists(secrets_file_path):
break
else:
print("Turn on your internet and unplug your USB to continue...")
time.sleep(10)
return True | python | def check_internet_on(secrets_file_path):
"""If internet on and USB unplugged, returns true. Else, continues to wait..."""
while True:
if internet_on() is True and not os.path.exists(secrets_file_path):
break
else:
print("Turn on your internet and unplug your USB to continue...")
time.sleep(10)
return True | [
"def",
"check_internet_on",
"(",
"secrets_file_path",
")",
":",
"while",
"True",
":",
"if",
"internet_on",
"(",
")",
"is",
"True",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"secrets_file_path",
")",
":",
"break",
"else",
":",
"print",
"(",
"\"Turn on your internet and unplug your USB to continue...\"",
")",
"time",
".",
"sleep",
"(",
"10",
")",
"return",
"True"
] | If internet on and USB unplugged, returns true. Else, continues to wait... | [
"If",
"internet",
"on",
"and",
"USB",
"unplugged",
"returns",
"true",
".",
"Else",
"continues",
"to",
"wait",
"..."
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L77-L85 |
227,754 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/bitcoin/signer.py | verify_signature | def verify_signature(uid, signed_cert_file_name, issuing_address):
"""
Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
VerifyMessage to confirm that the signature in the certificate matches the issuing_address.
Raises error is verification fails.
Raises UnverifiedSignatureError if signature is invalid
:param uid:
:param signed_cert_file_name:
:param issuing_address:
:return:
"""
logging.info('verifying signature for certificate with uid=%s:', uid)
with open(signed_cert_file_name) as in_file:
signed_cert = in_file.read()
signed_cert_json = json.loads(signed_cert)
to_verify = uid
signature = signed_cert_json['signature']
verified = verify_message(issuing_address, to_verify, signature)
if not verified:
error_message = 'There was a problem with the signature for certificate uid={}'.format(uid)
raise UnverifiedSignatureError(error_message)
logging.info('verified signature') | python | def verify_signature(uid, signed_cert_file_name, issuing_address):
"""
Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
VerifyMessage to confirm that the signature in the certificate matches the issuing_address.
Raises error is verification fails.
Raises UnverifiedSignatureError if signature is invalid
:param uid:
:param signed_cert_file_name:
:param issuing_address:
:return:
"""
logging.info('verifying signature for certificate with uid=%s:', uid)
with open(signed_cert_file_name) as in_file:
signed_cert = in_file.read()
signed_cert_json = json.loads(signed_cert)
to_verify = uid
signature = signed_cert_json['signature']
verified = verify_message(issuing_address, to_verify, signature)
if not verified:
error_message = 'There was a problem with the signature for certificate uid={}'.format(uid)
raise UnverifiedSignatureError(error_message)
logging.info('verified signature') | [
"def",
"verify_signature",
"(",
"uid",
",",
"signed_cert_file_name",
",",
"issuing_address",
")",
":",
"logging",
".",
"info",
"(",
"'verifying signature for certificate with uid=%s:'",
",",
"uid",
")",
"with",
"open",
"(",
"signed_cert_file_name",
")",
"as",
"in_file",
":",
"signed_cert",
"=",
"in_file",
".",
"read",
"(",
")",
"signed_cert_json",
"=",
"json",
".",
"loads",
"(",
"signed_cert",
")",
"to_verify",
"=",
"uid",
"signature",
"=",
"signed_cert_json",
"[",
"'signature'",
"]",
"verified",
"=",
"verify_message",
"(",
"issuing_address",
",",
"to_verify",
",",
"signature",
")",
"if",
"not",
"verified",
":",
"error_message",
"=",
"'There was a problem with the signature for certificate uid={}'",
".",
"format",
"(",
"uid",
")",
"raise",
"UnverifiedSignatureError",
"(",
"error_message",
")",
"logging",
".",
"info",
"(",
"'verified signature'",
")"
] | Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
VerifyMessage to confirm that the signature in the certificate matches the issuing_address.
Raises error is verification fails.
Raises UnverifiedSignatureError if signature is invalid
:param uid:
:param signed_cert_file_name:
:param issuing_address:
:return: | [
"Verify",
"the",
"certificate",
"signature",
"matches",
"the",
"expected",
".",
"Double",
"-",
"check",
"the",
"uid",
"field",
"in",
"the",
"certificate",
"and",
"use",
"VerifyMessage",
"to",
"confirm",
"that",
"the",
"signature",
"in",
"the",
"certificate",
"matches",
"the",
"issuing_address",
"."
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/bitcoin/signer.py#L52-L78 |
227,755 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/ethereum/connectors.py | EtherscanBroadcaster.get_balance | def get_balance(self, address, api_token):
"""
returns the balance in wei
with some inspiration from PyWallet
"""
broadcast_url = self.base_url + '?module=account&action=balance'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url)
if int(response.status_code) == 200:
balance = int(response.json().get('result', None))
logging.info('Balance check succeeded: %s', response.json())
return balance
raise BroadcastError(response.text) | python | def get_balance(self, address, api_token):
"""
returns the balance in wei
with some inspiration from PyWallet
"""
broadcast_url = self.base_url + '?module=account&action=balance'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url)
if int(response.status_code) == 200:
balance = int(response.json().get('result', None))
logging.info('Balance check succeeded: %s', response.json())
return balance
raise BroadcastError(response.text) | [
"def",
"get_balance",
"(",
"self",
",",
"address",
",",
"api_token",
")",
":",
"broadcast_url",
"=",
"self",
".",
"base_url",
"+",
"'?module=account&action=balance'",
"broadcast_url",
"+=",
"'&address=%s'",
"%",
"address",
"broadcast_url",
"+=",
"'&tag=latest'",
"if",
"api_token",
":",
"'&apikey=%s'",
"%",
"api_token",
"response",
"=",
"requests",
".",
"get",
"(",
"broadcast_url",
")",
"if",
"int",
"(",
"response",
".",
"status_code",
")",
"==",
"200",
":",
"balance",
"=",
"int",
"(",
"response",
".",
"json",
"(",
")",
".",
"get",
"(",
"'result'",
",",
"None",
")",
")",
"logging",
".",
"info",
"(",
"'Balance check succeeded: %s'",
",",
"response",
".",
"json",
"(",
")",
")",
"return",
"balance",
"raise",
"BroadcastError",
"(",
"response",
".",
"text",
")"
] | returns the balance in wei
with some inspiration from PyWallet | [
"returns",
"the",
"balance",
"in",
"wei",
"with",
"some",
"inspiration",
"from",
"PyWallet"
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L80-L95 |
227,756 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/ethereum/connectors.py | EtherscanBroadcaster.get_address_nonce | def get_address_nonce(self, address, api_token):
"""
Looks up the address nonce of this address
Neccesary for the transaction creation
"""
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url, )
if int(response.status_code) == 200:
# the int(res, 0) transforms the hex nonce to int
nonce = int(response.json().get('result', None), 0)
logging.info('Nonce check went correct: %s', response.json())
return nonce
else:
logging.info('response error checking nonce')
raise BroadcastError('Error checking the nonce through the Etherscan API. Error msg: %s', response.text) | python | def get_address_nonce(self, address, api_token):
"""
Looks up the address nonce of this address
Neccesary for the transaction creation
"""
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url, )
if int(response.status_code) == 200:
# the int(res, 0) transforms the hex nonce to int
nonce = int(response.json().get('result', None), 0)
logging.info('Nonce check went correct: %s', response.json())
return nonce
else:
logging.info('response error checking nonce')
raise BroadcastError('Error checking the nonce through the Etherscan API. Error msg: %s', response.text) | [
"def",
"get_address_nonce",
"(",
"self",
",",
"address",
",",
"api_token",
")",
":",
"broadcast_url",
"=",
"self",
".",
"base_url",
"+",
"'?module=proxy&action=eth_getTransactionCount'",
"broadcast_url",
"+=",
"'&address=%s'",
"%",
"address",
"broadcast_url",
"+=",
"'&tag=latest'",
"if",
"api_token",
":",
"'&apikey=%s'",
"%",
"api_token",
"response",
"=",
"requests",
".",
"get",
"(",
"broadcast_url",
",",
")",
"if",
"int",
"(",
"response",
".",
"status_code",
")",
"==",
"200",
":",
"# the int(res, 0) transforms the hex nonce to int",
"nonce",
"=",
"int",
"(",
"response",
".",
"json",
"(",
")",
".",
"get",
"(",
"'result'",
",",
"None",
")",
",",
"0",
")",
"logging",
".",
"info",
"(",
"'Nonce check went correct: %s'",
",",
"response",
".",
"json",
"(",
")",
")",
"return",
"nonce",
"else",
":",
"logging",
".",
"info",
"(",
"'response error checking nonce'",
")",
"raise",
"BroadcastError",
"(",
"'Error checking the nonce through the Etherscan API. Error msg: %s'",
",",
"response",
".",
"text",
")"
] | Looks up the address nonce of this address
Neccesary for the transaction creation | [
"Looks",
"up",
"the",
"address",
"nonce",
"of",
"this",
"address",
"Neccesary",
"for",
"the",
"transaction",
"creation"
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L97-L115 |
227,757 | tensorflow/mesh | mesh_tensorflow/tpu_variables.py | ReplicatedVariable._dense_var_to_tensor | def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, as_ref)
else:
return ops.convert_to_tensor(self._primary_var)
# pylint: enable=protected-access
if dtype is not None and dtype != self.dtype:
return NotImplemented
if as_ref:
return self.handle
else:
return self.read_value() | python | def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, as_ref)
else:
return ops.convert_to_tensor(self._primary_var)
# pylint: enable=protected-access
if dtype is not None and dtype != self.dtype:
return NotImplemented
if as_ref:
return self.handle
else:
return self.read_value() | [
"def",
"_dense_var_to_tensor",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"as_ref",
"=",
"False",
")",
":",
"# pylint: disable=protected-access",
"if",
"_enclosing_tpu_context",
"(",
")",
"is",
"None",
":",
"if",
"hasattr",
"(",
"self",
".",
"_primary_var",
",",
"'_dense_var_to_tensor'",
")",
":",
"return",
"self",
".",
"_primary_var",
".",
"_dense_var_to_tensor",
"(",
"dtype",
",",
"name",
",",
"as_ref",
")",
"else",
":",
"return",
"ops",
".",
"convert_to_tensor",
"(",
"self",
".",
"_primary_var",
")",
"# pylint: enable=protected-access",
"if",
"dtype",
"is",
"not",
"None",
"and",
"dtype",
"!=",
"self",
".",
"dtype",
":",
"return",
"NotImplemented",
"if",
"as_ref",
":",
"return",
"self",
".",
"handle",
"else",
":",
"return",
"self",
".",
"read_value",
"(",
")"
] | Converts a variable to a tensor. | [
"Converts",
"a",
"variable",
"to",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/tpu_variables.py#L183-L197 |
227,758 | tensorflow/mesh | mesh_tensorflow/auto_mtf/memory_estimator.py | MemoryEstimator._compute_layout_validator | def _compute_layout_validator(self):
"""Computes self._layout_validator."""
self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph,
self.mesh_shape) | python | def _compute_layout_validator(self):
"""Computes self._layout_validator."""
self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph,
self.mesh_shape) | [
"def",
"_compute_layout_validator",
"(",
"self",
")",
":",
"self",
".",
"_layout_validator",
"=",
"valid_layouts",
".",
"LayoutValidator",
"(",
"self",
".",
"mtf_graph",
",",
"self",
".",
"mesh_shape",
")"
] | Computes self._layout_validator. | [
"Computes",
"self",
".",
"_layout_validator",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L87-L90 |
227,759 | tensorflow/mesh | mesh_tensorflow/auto_mtf/memory_estimator.py | MemoryEstimator._compute_graph_interface | def _compute_graph_interface(self):
"""Computes self._graph_interface."""
self._graph_interface = graph_interface.GraphInterface(self.mtf_graph)
for mtf_output in self.mtf_outputs:
self._graph_interface.set_tensor_final(mtf_output.name) | python | def _compute_graph_interface(self):
"""Computes self._graph_interface."""
self._graph_interface = graph_interface.GraphInterface(self.mtf_graph)
for mtf_output in self.mtf_outputs:
self._graph_interface.set_tensor_final(mtf_output.name) | [
"def",
"_compute_graph_interface",
"(",
"self",
")",
":",
"self",
".",
"_graph_interface",
"=",
"graph_interface",
".",
"GraphInterface",
"(",
"self",
".",
"mtf_graph",
")",
"for",
"mtf_output",
"in",
"self",
".",
"mtf_outputs",
":",
"self",
".",
"_graph_interface",
".",
"set_tensor_final",
"(",
"mtf_output",
".",
"name",
")"
] | Computes self._graph_interface. | [
"Computes",
"self",
".",
"_graph_interface",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L92-L96 |
227,760 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | make_layer_stack | def make_layer_stack(layers=gin.REQUIRED, num_layers=6):
"""Configurable layer stack.
Args:
layers: a list of subclasses of TransformerLayer
num_layers: an integer
Returns:
a LayerStack
"""
return LayerStack([cls() for cls in layers] * num_layers) | python | def make_layer_stack(layers=gin.REQUIRED, num_layers=6):
"""Configurable layer stack.
Args:
layers: a list of subclasses of TransformerLayer
num_layers: an integer
Returns:
a LayerStack
"""
return LayerStack([cls() for cls in layers] * num_layers) | [
"def",
"make_layer_stack",
"(",
"layers",
"=",
"gin",
".",
"REQUIRED",
",",
"num_layers",
"=",
"6",
")",
":",
"return",
"LayerStack",
"(",
"[",
"cls",
"(",
")",
"for",
"cls",
"in",
"layers",
"]",
"*",
"num_layers",
")"
] | Configurable layer stack.
Args:
layers: a list of subclasses of TransformerLayer
num_layers: an integer
Returns:
a LayerStack | [
"Configurable",
"layer",
"stack",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L946-L955 |
227,761 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | make_bitransformer | def make_bitransformer(
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout=None,
mesh_shape=None):
"""Gin-configurable bitransformer constructor.
In your config file you need to set the encoder and decoder layers like this:
encoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.DenseReluDense,
]
decoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.EncDecAttention,
@transformer_layers.DenseReluDense,
]
Args:
input_vocab_size: a integer
output_vocab_size: an integer
layout: optional - an input to mtf.convert_to_layout_rules
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
mesh_shape: optional - an input to mtf.convert_to_shape
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
Returns:
a Bitransformer
"""
with gin.config_scope("encoder"):
encoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=None,
autoregressive=False,
name="encoder",
layout=layout,
mesh_shape=mesh_shape)
with gin.config_scope("decoder"):
decoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=output_vocab_size,
output_vocab_size=output_vocab_size,
autoregressive=True,
name="decoder",
layout=layout,
mesh_shape=mesh_shape)
return Bitransformer(encoder, decoder) | python | def make_bitransformer(
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout=None,
mesh_shape=None):
"""Gin-configurable bitransformer constructor.
In your config file you need to set the encoder and decoder layers like this:
encoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.DenseReluDense,
]
decoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.EncDecAttention,
@transformer_layers.DenseReluDense,
]
Args:
input_vocab_size: a integer
output_vocab_size: an integer
layout: optional - an input to mtf.convert_to_layout_rules
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
mesh_shape: optional - an input to mtf.convert_to_shape
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
Returns:
a Bitransformer
"""
with gin.config_scope("encoder"):
encoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=None,
autoregressive=False,
name="encoder",
layout=layout,
mesh_shape=mesh_shape)
with gin.config_scope("decoder"):
decoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=output_vocab_size,
output_vocab_size=output_vocab_size,
autoregressive=True,
name="decoder",
layout=layout,
mesh_shape=mesh_shape)
return Bitransformer(encoder, decoder) | [
"def",
"make_bitransformer",
"(",
"input_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"output_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"layout",
"=",
"None",
",",
"mesh_shape",
"=",
"None",
")",
":",
"with",
"gin",
".",
"config_scope",
"(",
"\"encoder\"",
")",
":",
"encoder",
"=",
"Unitransformer",
"(",
"layer_stack",
"=",
"make_layer_stack",
"(",
")",
",",
"input_vocab_size",
"=",
"input_vocab_size",
",",
"output_vocab_size",
"=",
"None",
",",
"autoregressive",
"=",
"False",
",",
"name",
"=",
"\"encoder\"",
",",
"layout",
"=",
"layout",
",",
"mesh_shape",
"=",
"mesh_shape",
")",
"with",
"gin",
".",
"config_scope",
"(",
"\"decoder\"",
")",
":",
"decoder",
"=",
"Unitransformer",
"(",
"layer_stack",
"=",
"make_layer_stack",
"(",
")",
",",
"input_vocab_size",
"=",
"output_vocab_size",
",",
"output_vocab_size",
"=",
"output_vocab_size",
",",
"autoregressive",
"=",
"True",
",",
"name",
"=",
"\"decoder\"",
",",
"layout",
"=",
"layout",
",",
"mesh_shape",
"=",
"mesh_shape",
")",
"return",
"Bitransformer",
"(",
"encoder",
",",
"decoder",
")"
] | Gin-configurable bitransformer constructor.
In your config file you need to set the encoder and decoder layers like this:
encoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.DenseReluDense,
]
decoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.EncDecAttention,
@transformer_layers.DenseReluDense,
]
Args:
input_vocab_size: a integer
output_vocab_size: an integer
layout: optional - an input to mtf.convert_to_layout_rules
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
mesh_shape: optional - an input to mtf.convert_to_shape
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
Returns:
a Bitransformer | [
"Gin",
"-",
"configurable",
"bitransformer",
"constructor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L959-L1005 |
227,762 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.get_states | def get_states(self, n):
"""Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors
"""
return self.states[len(self.new_states):len(self.new_states) + n] | python | def get_states(self, n):
"""Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors
"""
return self.states[len(self.new_states):len(self.new_states) + n] | [
"def",
"get_states",
"(",
"self",
",",
"n",
")",
":",
"return",
"self",
".",
"states",
"[",
"len",
"(",
"self",
".",
"new_states",
")",
":",
"len",
"(",
"self",
".",
"new_states",
")",
"+",
"n",
"]"
] | Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors | [
"Get",
"the",
"next",
"n",
"recurrent",
"states",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L219-L229 |
227,763 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.get_constant_state | def get_constant_state(self):
"""Read state that was written in "first_part" mode.
Returns:
a structure
"""
ret = self.constant_states[self.next_constant_state]
self.next_constant_state += 1
return ret | python | def get_constant_state(self):
"""Read state that was written in "first_part" mode.
Returns:
a structure
"""
ret = self.constant_states[self.next_constant_state]
self.next_constant_state += 1
return ret | [
"def",
"get_constant_state",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"constant_states",
"[",
"self",
".",
"next_constant_state",
"]",
"self",
".",
"next_constant_state",
"+=",
"1",
"return",
"ret"
] | Read state that was written in "first_part" mode.
Returns:
a structure | [
"Read",
"state",
"that",
"was",
"written",
"in",
"first_part",
"mode",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L252-L260 |
227,764 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.nonpadding | def nonpadding(self):
"""Tensor with zeros in padding positions and ones elsewhere."""
if self.sequence_id is None:
return None
if self.sequence_id == 1:
return 1
else:
return mtf.cast(
mtf.not_equal(self.sequence_id, 0), self.activation_dtype) | python | def nonpadding(self):
"""Tensor with zeros in padding positions and ones elsewhere."""
if self.sequence_id is None:
return None
if self.sequence_id == 1:
return 1
else:
return mtf.cast(
mtf.not_equal(self.sequence_id, 0), self.activation_dtype) | [
"def",
"nonpadding",
"(",
"self",
")",
":",
"if",
"self",
".",
"sequence_id",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"sequence_id",
"==",
"1",
":",
"return",
"1",
"else",
":",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"not_equal",
"(",
"self",
".",
"sequence_id",
",",
"0",
")",
",",
"self",
".",
"activation_dtype",
")"
] | Tensor with zeros in padding positions and ones elsewhere. | [
"Tensor",
"with",
"zeros",
"in",
"padding",
"positions",
"and",
"ones",
"elsewhere",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L263-L271 |
227,765 | tensorflow/mesh | mesh_tensorflow/transformer/metrics.py | sequence_accuracy | def sequence_accuracy(labels, outputs):
"""Compute the sequence-level accuracy.
A sequence is only considered correct if all of its entries were predicted
correctly.
Args:
labels: ground-truth labels, shape=(batch, packed_seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate.
"""
# A sequence is correct if all of the non-padded entries are correct
all_correct = tf.reduce_all(
tf.logical_or(tf.equal(labels, outputs), tf.equal(labels, 0)), axis=-1
)
return tf.metrics.mean(all_correct) | python | def sequence_accuracy(labels, outputs):
"""Compute the sequence-level accuracy.
A sequence is only considered correct if all of its entries were predicted
correctly.
Args:
labels: ground-truth labels, shape=(batch, packed_seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate.
"""
# A sequence is correct if all of the non-padded entries are correct
all_correct = tf.reduce_all(
tf.logical_or(tf.equal(labels, outputs), tf.equal(labels, 0)), axis=-1
)
return tf.metrics.mean(all_correct) | [
"def",
"sequence_accuracy",
"(",
"labels",
",",
"outputs",
")",
":",
"# A sequence is correct if all of the non-padded entries are correct",
"all_correct",
"=",
"tf",
".",
"reduce_all",
"(",
"tf",
".",
"logical_or",
"(",
"tf",
".",
"equal",
"(",
"labels",
",",
"outputs",
")",
",",
"tf",
".",
"equal",
"(",
"labels",
",",
"0",
")",
")",
",",
"axis",
"=",
"-",
"1",
")",
"return",
"tf",
".",
"metrics",
".",
"mean",
"(",
"all_correct",
")"
] | Compute the sequence-level accuracy.
A sequence is only considered correct if all of its entries were predicted
correctly.
Args:
labels: ground-truth labels, shape=(batch, packed_seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate. | [
"Compute",
"the",
"sequence",
"-",
"level",
"accuracy",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metrics.py#L46-L63 |
227,766 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_input_names | def get_operation_input_names(self, operation_name):
"""Generates the names of all input tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an input tensor.
"""
for input_tensor in self._name_to_operation(operation_name).inputs:
yield input_tensor.name | python | def get_operation_input_names(self, operation_name):
"""Generates the names of all input tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an input tensor.
"""
for input_tensor in self._name_to_operation(operation_name).inputs:
yield input_tensor.name | [
"def",
"get_operation_input_names",
"(",
"self",
",",
"operation_name",
")",
":",
"for",
"input_tensor",
"in",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
".",
"inputs",
":",
"yield",
"input_tensor",
".",
"name"
] | Generates the names of all input tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an input tensor. | [
"Generates",
"the",
"names",
"of",
"all",
"input",
"tensors",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L93-L103 |
227,767 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_output_names | def get_operation_output_names(self, operation_name):
"""Generates the names of all output tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an output tensor.
"""
for output_tensor in self._name_to_operation(operation_name).outputs:
yield output_tensor.name | python | def get_operation_output_names(self, operation_name):
"""Generates the names of all output tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an output tensor.
"""
for output_tensor in self._name_to_operation(operation_name).outputs:
yield output_tensor.name | [
"def",
"get_operation_output_names",
"(",
"self",
",",
"operation_name",
")",
":",
"for",
"output_tensor",
"in",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
".",
"outputs",
":",
"yield",
"output_tensor",
".",
"name"
] | Generates the names of all output tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an output tensor. | [
"Generates",
"the",
"names",
"of",
"all",
"output",
"tensors",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L105-L115 |
227,768 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_shape | def get_tensor_shape(self, tensor_name):
"""The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tf.TensorShape(tensor.shape.to_integer_list)
else: # tf.Tensor
return tensor.shape | python | def get_tensor_shape(self, tensor_name):
"""The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tf.TensorShape(tensor.shape.to_integer_list)
else: # tf.Tensor
return tensor.shape | [
"def",
"get_tensor_shape",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"mtf",
".",
"Tensor",
")",
":",
"return",
"tf",
".",
"TensorShape",
"(",
"tensor",
".",
"shape",
".",
"to_integer_list",
")",
"else",
":",
"# tf.Tensor",
"return",
"tensor",
".",
"shape"
] | The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape | [
"The",
"tf",
".",
"TensorShape",
"of",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L137-L151 |
227,769 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_num_entries | def get_tensor_num_entries(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The number of entries in a tensor.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the number of entries on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
shape = self.get_tensor_shape(tensor_name)
# We don't have to worry about divisiblity issues because Mesh TensorFlow
# only allows evenly divisible assignments.
num_entries = 1
for dim in shape.dims:
num_entries = num_entries * dim.value
if not partial_layout:
return num_entries
for mtf_dimension_name in self.get_tensor_mtf_dimension_names(tensor_name):
if mtf_dimension_name not in partial_layout:
continue
mesh_dimension_name = partial_layout[mtf_dimension_name]
mesh_dimension_size = mesh_dimension_to_size[mesh_dimension_name]
num_entries = int(math.ceil(num_entries / mesh_dimension_size))
return num_entries | python | def get_tensor_num_entries(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The number of entries in a tensor.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the number of entries on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
shape = self.get_tensor_shape(tensor_name)
# We don't have to worry about divisiblity issues because Mesh TensorFlow
# only allows evenly divisible assignments.
num_entries = 1
for dim in shape.dims:
num_entries = num_entries * dim.value
if not partial_layout:
return num_entries
for mtf_dimension_name in self.get_tensor_mtf_dimension_names(tensor_name):
if mtf_dimension_name not in partial_layout:
continue
mesh_dimension_name = partial_layout[mtf_dimension_name]
mesh_dimension_size = mesh_dimension_to_size[mesh_dimension_name]
num_entries = int(math.ceil(num_entries / mesh_dimension_size))
return num_entries | [
"def",
"get_tensor_num_entries",
"(",
"self",
",",
"tensor_name",
",",
"partial_layout",
"=",
"None",
",",
"mesh_dimension_to_size",
"=",
"None",
")",
":",
"shape",
"=",
"self",
".",
"get_tensor_shape",
"(",
"tensor_name",
")",
"# We don't have to worry about divisiblity issues because Mesh TensorFlow",
"# only allows evenly divisible assignments.",
"num_entries",
"=",
"1",
"for",
"dim",
"in",
"shape",
".",
"dims",
":",
"num_entries",
"=",
"num_entries",
"*",
"dim",
".",
"value",
"if",
"not",
"partial_layout",
":",
"return",
"num_entries",
"for",
"mtf_dimension_name",
"in",
"self",
".",
"get_tensor_mtf_dimension_names",
"(",
"tensor_name",
")",
":",
"if",
"mtf_dimension_name",
"not",
"in",
"partial_layout",
":",
"continue",
"mesh_dimension_name",
"=",
"partial_layout",
"[",
"mtf_dimension_name",
"]",
"mesh_dimension_size",
"=",
"mesh_dimension_to_size",
"[",
"mesh_dimension_name",
"]",
"num_entries",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"num_entries",
"/",
"mesh_dimension_size",
")",
")",
"return",
"num_entries"
] | The number of entries in a tensor.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the number of entries on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer | [
"The",
"number",
"of",
"entries",
"in",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L153-L187 |
227,770 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_size | def get_tensor_size(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
return (self.get_tensor_dtype(tensor_name).size *
self.get_tensor_num_entries(tensor_name, partial_layout,
mesh_dimension_to_size)) | python | def get_tensor_size(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
return (self.get_tensor_dtype(tensor_name).size *
self.get_tensor_num_entries(tensor_name, partial_layout,
mesh_dimension_to_size)) | [
"def",
"get_tensor_size",
"(",
"self",
",",
"tensor_name",
",",
"partial_layout",
"=",
"None",
",",
"mesh_dimension_to_size",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"get_tensor_dtype",
"(",
"tensor_name",
")",
".",
"size",
"*",
"self",
".",
"get_tensor_num_entries",
"(",
"tensor_name",
",",
"partial_layout",
",",
"mesh_dimension_to_size",
")",
")"
] | The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer | [
"The",
"size",
"of",
"a",
"tensor",
"in",
"bytes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L189-L208 |
227,771 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_device | def get_tensor_device(self, tensor_name):
"""The device of a tensor.
Note that only tf tensors have device assignments.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a string or None, representing the device name.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, tf.Tensor):
return tensor.device
else: # mtf.Tensor
return None | python | def get_tensor_device(self, tensor_name):
"""The device of a tensor.
Note that only tf tensors have device assignments.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a string or None, representing the device name.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, tf.Tensor):
return tensor.device
else: # mtf.Tensor
return None | [
"def",
"get_tensor_device",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"tf",
".",
"Tensor",
")",
":",
"return",
"tensor",
".",
"device",
"else",
":",
"# mtf.Tensor",
"return",
"None"
] | The device of a tensor.
Note that only tf tensors have device assignments.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a string or None, representing the device name. | [
"The",
"device",
"of",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L210-L225 |
227,772 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_device | def get_operation_device(self, operation_name):
"""The device of an operation.
Note that only tf operations have device assignments.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a string or None, representing the device name.
"""
operation = self._name_to_operation(operation_name)
if isinstance(operation, tf.Operation):
return operation.device
else: # mtf.Operation
return None | python | def get_operation_device(self, operation_name):
"""The device of an operation.
Note that only tf operations have device assignments.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a string or None, representing the device name.
"""
operation = self._name_to_operation(operation_name)
if isinstance(operation, tf.Operation):
return operation.device
else: # mtf.Operation
return None | [
"def",
"get_operation_device",
"(",
"self",
",",
"operation_name",
")",
":",
"operation",
"=",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
"if",
"isinstance",
"(",
"operation",
",",
"tf",
".",
"Operation",
")",
":",
"return",
"operation",
".",
"device",
"else",
":",
"# mtf.Operation",
"return",
"None"
] | The device of an operation.
Note that only tf operations have device assignments.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a string or None, representing the device name. | [
"The",
"device",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L242-L257 |
227,773 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_mtf_dimension_names | def get_tensor_mtf_dimension_names(self, tensor_name):
"""The Mesh TensorFlow dimensions associated with a tensor.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a [string], the names of Mesh TensorFlow dimensions.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tensor.shape.dimension_names
else: # tf.Tensor
return [] | python | def get_tensor_mtf_dimension_names(self, tensor_name):
"""The Mesh TensorFlow dimensions associated with a tensor.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a [string], the names of Mesh TensorFlow dimensions.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tensor.shape.dimension_names
else: # tf.Tensor
return [] | [
"def",
"get_tensor_mtf_dimension_names",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"mtf",
".",
"Tensor",
")",
":",
"return",
"tensor",
".",
"shape",
".",
"dimension_names",
"else",
":",
"# tf.Tensor",
"return",
"[",
"]"
] | The Mesh TensorFlow dimensions associated with a tensor.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a [string], the names of Mesh TensorFlow dimensions. | [
"The",
"Mesh",
"TensorFlow",
"dimensions",
"associated",
"with",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L259-L272 |
227,774 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_mtf_dimension_names | def get_operation_mtf_dimension_names(self, operation_name):
"""The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions.
"""
mtf_dimension_names = set()
for tensor_name in self.get_operation_input_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
for tensor_name in self.get_operation_output_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
return mtf_dimension_names | python | def get_operation_mtf_dimension_names(self, operation_name):
"""The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions.
"""
mtf_dimension_names = set()
for tensor_name in self.get_operation_input_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
for tensor_name in self.get_operation_output_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
return mtf_dimension_names | [
"def",
"get_operation_mtf_dimension_names",
"(",
"self",
",",
"operation_name",
")",
":",
"mtf_dimension_names",
"=",
"set",
"(",
")",
"for",
"tensor_name",
"in",
"self",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"mtf_dimension_names",
".",
"update",
"(",
"self",
".",
"get_tensor_mtf_dimension_names",
"(",
"tensor_name",
")",
")",
"for",
"tensor_name",
"in",
"self",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"mtf_dimension_names",
".",
"update",
"(",
"self",
".",
"get_tensor_mtf_dimension_names",
"(",
"tensor_name",
")",
")",
"return",
"mtf_dimension_names"
] | The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions. | [
"The",
"Mesh",
"TensorFlow",
"dimensions",
"associated",
"with",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L274-L290 |
227,775 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.set_tensor_final | def set_tensor_final(self, tensor_name):
"""Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
"""
tensor = self._name_to_tensor(tensor_name)
self._final_tensors.add(tensor) | python | def set_tensor_final(self, tensor_name):
"""Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
"""
tensor = self._name_to_tensor(tensor_name)
self._final_tensors.add(tensor) | [
"def",
"set_tensor_final",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"self",
".",
"_final_tensors",
".",
"add",
"(",
"tensor",
")"
] | Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph. | [
"Denotes",
"a",
"tensor",
"as",
"a",
"final",
"output",
"of",
"the",
"computation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L292-L299 |
227,776 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.is_tensor_final | def is_tensor_final(self, tensor_name):
"""Whether a tensor is a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor was a final output.
"""
tensor = self._name_to_tensor(tensor_name)
return tensor in self._final_tensors | python | def is_tensor_final(self, tensor_name):
"""Whether a tensor is a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor was a final output.
"""
tensor = self._name_to_tensor(tensor_name)
return tensor in self._final_tensors | [
"def",
"is_tensor_final",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"return",
"tensor",
"in",
"self",
".",
"_final_tensors"
] | Whether a tensor is a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor was a final output. | [
"Whether",
"a",
"tensor",
"is",
"a",
"final",
"output",
"of",
"the",
"computation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L301-L311 |
227,777 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.compute_cost_graph | def compute_cost_graph(self, devices=None):
"""Computes a CostGraphDef protobuf based on this graph.
Defined in tensorflow/core/framework/cost_graph.proto.
Args:
devices: optional [string], the names of devices to consider. If
specified, any tensor on a device not listed is given a size of zero.
Any device-less tensor (e.g. Mesh TensorFlow tensor) is not affected.
Returns:
a CostGraphDef protobuf with a Node for every operation in the graph, each
of which is populated with size/dtype information for its inputs and
outputs (which match the input/output order of the operation).
"""
cost_graph_def = cost_graph_pb2.CostGraphDef()
for i, operation_name in enumerate(self.get_all_operation_names()):
node = cost_graph_def.node.add(
name=operation_name,
device=self.get_operation_device(operation_name),
id=i)
for input_name in self.get_operation_input_names(operation_name):
id1, id2 = self._tensor_name_to_ids[input_name]
node.input_info.add(preceding_node=id1, preceding_port=id2)
for output_name in self.get_operation_output_names(operation_name):
tensor_device = self.get_tensor_device(output_name)
# devices = [] is not the same as None, and tensor_device = '' is also
# not the same as None.
if devices is None or tensor_device is None or tensor_device in devices:
node.output_info.add(
size=self.get_tensor_num_entries(output_name),
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
shape=self.get_tensor_shape(output_name).as_proto(),
)
else:
node.output_info.add(
size=0,
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
)
# NOTE(joshuawang): Unfortunately, the CostGraphDef protobuf has final
# operations, not tensors. As a result, we have to declare any operation
# that outputs a final tensor as final, which may expand the final set
# of tensors to keep in memory. This issue also arises in the scheduler
# code we will interface with.
if self.is_tensor_final(output_name):
node.is_final = True
return cost_graph_def | python | def compute_cost_graph(self, devices=None):
"""Computes a CostGraphDef protobuf based on this graph.
Defined in tensorflow/core/framework/cost_graph.proto.
Args:
devices: optional [string], the names of devices to consider. If
specified, any tensor on a device not listed is given a size of zero.
Any device-less tensor (e.g. Mesh TensorFlow tensor) is not affected.
Returns:
a CostGraphDef protobuf with a Node for every operation in the graph, each
of which is populated with size/dtype information for its inputs and
outputs (which match the input/output order of the operation).
"""
cost_graph_def = cost_graph_pb2.CostGraphDef()
for i, operation_name in enumerate(self.get_all_operation_names()):
node = cost_graph_def.node.add(
name=operation_name,
device=self.get_operation_device(operation_name),
id=i)
for input_name in self.get_operation_input_names(operation_name):
id1, id2 = self._tensor_name_to_ids[input_name]
node.input_info.add(preceding_node=id1, preceding_port=id2)
for output_name in self.get_operation_output_names(operation_name):
tensor_device = self.get_tensor_device(output_name)
# devices = [] is not the same as None, and tensor_device = '' is also
# not the same as None.
if devices is None or tensor_device is None or tensor_device in devices:
node.output_info.add(
size=self.get_tensor_num_entries(output_name),
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
shape=self.get_tensor_shape(output_name).as_proto(),
)
else:
node.output_info.add(
size=0,
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
)
# NOTE(joshuawang): Unfortunately, the CostGraphDef protobuf has final
# operations, not tensors. As a result, we have to declare any operation
# that outputs a final tensor as final, which may expand the final set
# of tensors to keep in memory. This issue also arises in the scheduler
# code we will interface with.
if self.is_tensor_final(output_name):
node.is_final = True
return cost_graph_def | [
"def",
"compute_cost_graph",
"(",
"self",
",",
"devices",
"=",
"None",
")",
":",
"cost_graph_def",
"=",
"cost_graph_pb2",
".",
"CostGraphDef",
"(",
")",
"for",
"i",
",",
"operation_name",
"in",
"enumerate",
"(",
"self",
".",
"get_all_operation_names",
"(",
")",
")",
":",
"node",
"=",
"cost_graph_def",
".",
"node",
".",
"add",
"(",
"name",
"=",
"operation_name",
",",
"device",
"=",
"self",
".",
"get_operation_device",
"(",
"operation_name",
")",
",",
"id",
"=",
"i",
")",
"for",
"input_name",
"in",
"self",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"id1",
",",
"id2",
"=",
"self",
".",
"_tensor_name_to_ids",
"[",
"input_name",
"]",
"node",
".",
"input_info",
".",
"add",
"(",
"preceding_node",
"=",
"id1",
",",
"preceding_port",
"=",
"id2",
")",
"for",
"output_name",
"in",
"self",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"tensor_device",
"=",
"self",
".",
"get_tensor_device",
"(",
"output_name",
")",
"# devices = [] is not the same as None, and tensor_device = '' is also",
"# not the same as None.",
"if",
"devices",
"is",
"None",
"or",
"tensor_device",
"is",
"None",
"or",
"tensor_device",
"in",
"devices",
":",
"node",
".",
"output_info",
".",
"add",
"(",
"size",
"=",
"self",
".",
"get_tensor_num_entries",
"(",
"output_name",
")",
",",
"alias_input_port",
"=",
"-",
"1",
",",
"dtype",
"=",
"self",
".",
"get_tensor_dtype",
"(",
"output_name",
")",
".",
"as_datatype_enum",
",",
"shape",
"=",
"self",
".",
"get_tensor_shape",
"(",
"output_name",
")",
".",
"as_proto",
"(",
")",
",",
")",
"else",
":",
"node",
".",
"output_info",
".",
"add",
"(",
"size",
"=",
"0",
",",
"alias_input_port",
"=",
"-",
"1",
",",
"dtype",
"=",
"self",
".",
"get_tensor_dtype",
"(",
"output_name",
")",
".",
"as_datatype_enum",
",",
")",
"# NOTE(joshuawang): Unfortunately, the CostGraphDef protobuf has final",
"# operations, not tensors. As a result, we have to declare any operation",
"# that outputs a final tensor as final, which may expand the final set",
"# of tensors to keep in memory. This issue also arises in the scheduler",
"# code we will interface with.",
"if",
"self",
".",
"is_tensor_final",
"(",
"output_name",
")",
":",
"node",
".",
"is_final",
"=",
"True",
"return",
"cost_graph_def"
] | Computes a CostGraphDef protobuf based on this graph.
Defined in tensorflow/core/framework/cost_graph.proto.
Args:
devices: optional [string], the names of devices to consider. If
specified, any tensor on a device not listed is given a size of zero.
Any device-less tensor (e.g. Mesh TensorFlow tensor) is not affected.
Returns:
a CostGraphDef protobuf with a Node for every operation in the graph, each
of which is populated with size/dtype information for its inputs and
outputs (which match the input/output order of the operation). | [
"Computes",
"a",
"CostGraphDef",
"protobuf",
"based",
"on",
"this",
"graph",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L313-L365 |
227,778 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.compute_memory_contents_under_schedule | def compute_memory_contents_under_schedule(self, schedule):
"""The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()).
"""
out_degree = self._compute_initial_out_degree()
curr_memory_contents = set()
memory_contents_for_each_operation = []
for operation_id in schedule:
operation_name = self._operations[operation_id].name
# Allocate new memory to perform the computation at this node.
for output_name in self.get_operation_output_names(operation_name):
curr_memory_contents.add(output_name)
memory_contents_for_each_operation.append(frozenset(curr_memory_contents))
# Free any tensors which are no longer needed.
for output_name in self.get_operation_output_names(operation_name):
if out_degree[output_name] == 0:
curr_memory_contents.remove(output_name)
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] -= 1
if out_degree[input_name] == 0:
curr_memory_contents.remove(input_name)
return memory_contents_for_each_operation | python | def compute_memory_contents_under_schedule(self, schedule):
"""The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()).
"""
out_degree = self._compute_initial_out_degree()
curr_memory_contents = set()
memory_contents_for_each_operation = []
for operation_id in schedule:
operation_name = self._operations[operation_id].name
# Allocate new memory to perform the computation at this node.
for output_name in self.get_operation_output_names(operation_name):
curr_memory_contents.add(output_name)
memory_contents_for_each_operation.append(frozenset(curr_memory_contents))
# Free any tensors which are no longer needed.
for output_name in self.get_operation_output_names(operation_name):
if out_degree[output_name] == 0:
curr_memory_contents.remove(output_name)
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] -= 1
if out_degree[input_name] == 0:
curr_memory_contents.remove(input_name)
return memory_contents_for_each_operation | [
"def",
"compute_memory_contents_under_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"out_degree",
"=",
"self",
".",
"_compute_initial_out_degree",
"(",
")",
"curr_memory_contents",
"=",
"set",
"(",
")",
"memory_contents_for_each_operation",
"=",
"[",
"]",
"for",
"operation_id",
"in",
"schedule",
":",
"operation_name",
"=",
"self",
".",
"_operations",
"[",
"operation_id",
"]",
".",
"name",
"# Allocate new memory to perform the computation at this node.",
"for",
"output_name",
"in",
"self",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"curr_memory_contents",
".",
"add",
"(",
"output_name",
")",
"memory_contents_for_each_operation",
".",
"append",
"(",
"frozenset",
"(",
"curr_memory_contents",
")",
")",
"# Free any tensors which are no longer needed.",
"for",
"output_name",
"in",
"self",
".",
"get_operation_output_names",
"(",
"operation_name",
")",
":",
"if",
"out_degree",
"[",
"output_name",
"]",
"==",
"0",
":",
"curr_memory_contents",
".",
"remove",
"(",
"output_name",
")",
"for",
"input_name",
"in",
"self",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"out_degree",
"[",
"input_name",
"]",
"-=",
"1",
"if",
"out_degree",
"[",
"input_name",
"]",
"==",
"0",
":",
"curr_memory_contents",
".",
"remove",
"(",
"input_name",
")",
"return",
"memory_contents_for_each_operation"
] | The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()). | [
"The",
"in",
"-",
"memory",
"tensors",
"present",
"when",
"executing",
"each",
"operation",
"in",
"schedule",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L367-L407 |
227,779 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_operations | def _initialize_operations(self):
"""Initializer for _operations.
Raises:
TypeError: _graph is not a tf.Graph or mtf.Graph.
Returns:
a list of (tf.Operation or mtf.Operation)
"""
if isinstance(self._graph, tf.Graph):
return self._graph.get_operations()
elif isinstance(self._graph, mtf.Graph):
return self._graph.operations
else:
raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'
.format(type(self._graph))) | python | def _initialize_operations(self):
"""Initializer for _operations.
Raises:
TypeError: _graph is not a tf.Graph or mtf.Graph.
Returns:
a list of (tf.Operation or mtf.Operation)
"""
if isinstance(self._graph, tf.Graph):
return self._graph.get_operations()
elif isinstance(self._graph, mtf.Graph):
return self._graph.operations
else:
raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'
.format(type(self._graph))) | [
"def",
"_initialize_operations",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_graph",
",",
"tf",
".",
"Graph",
")",
":",
"return",
"self",
".",
"_graph",
".",
"get_operations",
"(",
")",
"elif",
"isinstance",
"(",
"self",
".",
"_graph",
",",
"mtf",
".",
"Graph",
")",
":",
"return",
"self",
".",
"_graph",
".",
"operations",
"else",
":",
"raise",
"TypeError",
"(",
"'Graph is not tf.Graph or mtf.Graph: {}'",
".",
"format",
"(",
"type",
"(",
"self",
".",
"_graph",
")",
")",
")"
] | Initializer for _operations.
Raises:
TypeError: _graph is not a tf.Graph or mtf.Graph.
Returns:
a list of (tf.Operation or mtf.Operation) | [
"Initializer",
"for",
"_operations",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L409-L424 |
227,780 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_operation_name_to_id | def _initialize_operation_name_to_id(self):
"""Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations.
"""
operation_name_to_id = {}
for i, operation in enumerate(self._operations):
operation_name_to_id[operation.name] = i
return operation_name_to_id | python | def _initialize_operation_name_to_id(self):
"""Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations.
"""
operation_name_to_id = {}
for i, operation in enumerate(self._operations):
operation_name_to_id[operation.name] = i
return operation_name_to_id | [
"def",
"_initialize_operation_name_to_id",
"(",
"self",
")",
":",
"operation_name_to_id",
"=",
"{",
"}",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"self",
".",
"_operations",
")",
":",
"operation_name_to_id",
"[",
"operation",
".",
"name",
"]",
"=",
"i",
"return",
"operation_name_to_id"
] | Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations. | [
"Initializer",
"for",
"_operation_name_to_id",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L426-L435 |
227,781 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_tensor_name_to_ids | def _initialize_tensor_name_to_ids(self):
"""Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs.
"""
tensor_name_to_ids = {}
for i, operation in enumerate(self._operations):
for j, tensor in enumerate(operation.outputs):
tensor_name_to_ids[tensor.name] = (i, j)
return tensor_name_to_ids | python | def _initialize_tensor_name_to_ids(self):
"""Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs.
"""
tensor_name_to_ids = {}
for i, operation in enumerate(self._operations):
for j, tensor in enumerate(operation.outputs):
tensor_name_to_ids[tensor.name] = (i, j)
return tensor_name_to_ids | [
"def",
"_initialize_tensor_name_to_ids",
"(",
"self",
")",
":",
"tensor_name_to_ids",
"=",
"{",
"}",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"self",
".",
"_operations",
")",
":",
"for",
"j",
",",
"tensor",
"in",
"enumerate",
"(",
"operation",
".",
"outputs",
")",
":",
"tensor_name_to_ids",
"[",
"tensor",
".",
"name",
"]",
"=",
"(",
"i",
",",
"j",
")",
"return",
"tensor_name_to_ids"
] | Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs. | [
"Initializer",
"for",
"_tensor_name_to_ids",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L437-L448 |
227,782 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._name_to_tensor | def _name_to_tensor(self, tensor_name):
"""The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
"""
id1, id2 = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] | python | def _name_to_tensor(self, tensor_name):
"""The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
"""
id1, id2 = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] | [
"def",
"_name_to_tensor",
"(",
"self",
",",
"tensor_name",
")",
":",
"id1",
",",
"id2",
"=",
"self",
".",
"_tensor_name_to_ids",
"[",
"tensor_name",
"]",
"return",
"self",
".",
"_operations",
"[",
"id1",
"]",
".",
"outputs",
"[",
"id2",
"]"
] | The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor | [
"The",
"tensor",
"with",
"the",
"given",
"name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L471-L481 |
227,783 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._compute_initial_out_degree | def _compute_initial_out_degree(self):
"""The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final.
"""
out_degree = collections.defaultdict(int)
# Pretend that final tensors have an additional degree so they are not
# freed.
for tensor_name in self.get_all_tensor_names():
if self.is_tensor_final(tensor_name):
out_degree[tensor_name] = 1
for operation_name in self.get_all_operation_names():
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] += 1
return out_degree | python | def _compute_initial_out_degree(self):
"""The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final.
"""
out_degree = collections.defaultdict(int)
# Pretend that final tensors have an additional degree so they are not
# freed.
for tensor_name in self.get_all_tensor_names():
if self.is_tensor_final(tensor_name):
out_degree[tensor_name] = 1
for operation_name in self.get_all_operation_names():
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] += 1
return out_degree | [
"def",
"_compute_initial_out_degree",
"(",
"self",
")",
":",
"out_degree",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"# Pretend that final tensors have an additional degree so they are not",
"# freed.",
"for",
"tensor_name",
"in",
"self",
".",
"get_all_tensor_names",
"(",
")",
":",
"if",
"self",
".",
"is_tensor_final",
"(",
"tensor_name",
")",
":",
"out_degree",
"[",
"tensor_name",
"]",
"=",
"1",
"for",
"operation_name",
"in",
"self",
".",
"get_all_operation_names",
"(",
")",
":",
"for",
"input_name",
"in",
"self",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"out_degree",
"[",
"input_name",
"]",
"+=",
"1",
"return",
"out_degree"
] | The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final. | [
"The",
"number",
"of",
"operations",
"which",
"use",
"each",
"tensor",
"as",
"input",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L483-L502 |
227,784 | tensorflow/mesh | mesh_tensorflow/layers.py | layer_norm | def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"):
"""Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x.
"""
with tf.variable_scope(name + "/layer_norm"):
scale = mtf.get_variable(
x.mesh,
"layer_norm_scale",
mtf.Shape([dim]),
initializer=tf.ones_initializer(),
activation_dtype=x.dtype)
bias = mtf.get_variable(
x.mesh,
"layer_norm_bias",
mtf.Shape([dim]),
initializer=tf.zeros_initializer(),
activation_dtype=x.dtype)
reduced_shape = x.shape - dim
mean = mtf.reduce_mean(x, output_shape=reduced_shape)
variance = mtf.reduce_mean(mtf.square(x - mean), output_shape=reduced_shape)
norm_x = (x - mean) * mtf.rsqrt(variance + epsilon)
return norm_x * scale + bias | python | def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"):
"""Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x.
"""
with tf.variable_scope(name + "/layer_norm"):
scale = mtf.get_variable(
x.mesh,
"layer_norm_scale",
mtf.Shape([dim]),
initializer=tf.ones_initializer(),
activation_dtype=x.dtype)
bias = mtf.get_variable(
x.mesh,
"layer_norm_bias",
mtf.Shape([dim]),
initializer=tf.zeros_initializer(),
activation_dtype=x.dtype)
reduced_shape = x.shape - dim
mean = mtf.reduce_mean(x, output_shape=reduced_shape)
variance = mtf.reduce_mean(mtf.square(x - mean), output_shape=reduced_shape)
norm_x = (x - mean) * mtf.rsqrt(variance + epsilon)
return norm_x * scale + bias | [
"def",
"layer_norm",
"(",
"x",
",",
"dim",
",",
"epsilon",
"=",
"1e-6",
",",
"name",
"=",
"\"layer_prepostprocess\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"\"/layer_norm\"",
")",
":",
"scale",
"=",
"mtf",
".",
"get_variable",
"(",
"x",
".",
"mesh",
",",
"\"layer_norm_scale\"",
",",
"mtf",
".",
"Shape",
"(",
"[",
"dim",
"]",
")",
",",
"initializer",
"=",
"tf",
".",
"ones_initializer",
"(",
")",
",",
"activation_dtype",
"=",
"x",
".",
"dtype",
")",
"bias",
"=",
"mtf",
".",
"get_variable",
"(",
"x",
".",
"mesh",
",",
"\"layer_norm_bias\"",
",",
"mtf",
".",
"Shape",
"(",
"[",
"dim",
"]",
")",
",",
"initializer",
"=",
"tf",
".",
"zeros_initializer",
"(",
")",
",",
"activation_dtype",
"=",
"x",
".",
"dtype",
")",
"reduced_shape",
"=",
"x",
".",
"shape",
"-",
"dim",
"mean",
"=",
"mtf",
".",
"reduce_mean",
"(",
"x",
",",
"output_shape",
"=",
"reduced_shape",
")",
"variance",
"=",
"mtf",
".",
"reduce_mean",
"(",
"mtf",
".",
"square",
"(",
"x",
"-",
"mean",
")",
",",
"output_shape",
"=",
"reduced_shape",
")",
"norm_x",
"=",
"(",
"x",
"-",
"mean",
")",
"*",
"mtf",
".",
"rsqrt",
"(",
"variance",
"+",
"epsilon",
")",
"return",
"norm_x",
"*",
"scale",
"+",
"bias"
] | Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x. | [
"Layer",
"normalization",
"over",
"dimension",
"dim",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L85-L114 |
227,785 | tensorflow/mesh | mesh_tensorflow/layers.py | softmax_cross_entropy_with_logits | def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0):
"""Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero, which can cause
unacceptable roundoff errors in bfloat16.
- To encourage the logits to be normalized log-probabilities.
Args:
logits: a mtf.Tensor whose shape contains vocab_dim
targets: a mtf.Tensor with the same shape as logits
vocab_dim: a mtf.Dimension
z_loss: a float
Returns:
a mtf.Tensor whose shape is equal to logits.shape - vocab_dim
Raises:
ValueError: if the shapes do not match.
"""
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
if vocab_dim not in logits.shape.dims:
raise ValueError("vocab_dim must be in logits.shape.dims")
log_z = mtf.reduce_logsumexp(logits, vocab_dim)
log_softmax = logits - log_z
loss = mtf.negative(
mtf.reduce_sum(log_softmax * targets, reduced_dim=vocab_dim))
if z_loss != 0:
loss += z_loss * mtf.square(log_z)
return loss | python | def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0):
"""Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero, which can cause
unacceptable roundoff errors in bfloat16.
- To encourage the logits to be normalized log-probabilities.
Args:
logits: a mtf.Tensor whose shape contains vocab_dim
targets: a mtf.Tensor with the same shape as logits
vocab_dim: a mtf.Dimension
z_loss: a float
Returns:
a mtf.Tensor whose shape is equal to logits.shape - vocab_dim
Raises:
ValueError: if the shapes do not match.
"""
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
if vocab_dim not in logits.shape.dims:
raise ValueError("vocab_dim must be in logits.shape.dims")
log_z = mtf.reduce_logsumexp(logits, vocab_dim)
log_softmax = logits - log_z
loss = mtf.negative(
mtf.reduce_sum(log_softmax * targets, reduced_dim=vocab_dim))
if z_loss != 0:
loss += z_loss * mtf.square(log_z)
return loss | [
"def",
"softmax_cross_entropy_with_logits",
"(",
"logits",
",",
"targets",
",",
"vocab_dim",
",",
"z_loss",
"=",
"0.0",
")",
":",
"if",
"logits",
".",
"shape",
"!=",
"targets",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"logits shape must equal targets shape\"",
"\"logits=%s targets=%s\"",
"%",
"(",
"logits",
".",
"to_string",
",",
"targets",
".",
"to_string",
")",
")",
"if",
"vocab_dim",
"not",
"in",
"logits",
".",
"shape",
".",
"dims",
":",
"raise",
"ValueError",
"(",
"\"vocab_dim must be in logits.shape.dims\"",
")",
"log_z",
"=",
"mtf",
".",
"reduce_logsumexp",
"(",
"logits",
",",
"vocab_dim",
")",
"log_softmax",
"=",
"logits",
"-",
"log_z",
"loss",
"=",
"mtf",
".",
"negative",
"(",
"mtf",
".",
"reduce_sum",
"(",
"log_softmax",
"*",
"targets",
",",
"reduced_dim",
"=",
"vocab_dim",
")",
")",
"if",
"z_loss",
"!=",
"0",
":",
"loss",
"+=",
"z_loss",
"*",
"mtf",
".",
"square",
"(",
"log_z",
")",
"return",
"loss"
] | Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero, which can cause
unacceptable roundoff errors in bfloat16.
- To encourage the logits to be normalized log-probabilities.
Args:
logits: a mtf.Tensor whose shape contains vocab_dim
targets: a mtf.Tensor with the same shape as logits
vocab_dim: a mtf.Dimension
z_loss: a float
Returns:
a mtf.Tensor whose shape is equal to logits.shape - vocab_dim
Raises:
ValueError: if the shapes do not match. | [
"Per",
"-",
"example",
"softmax",
"loss",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L187-L220 |
227,786 | tensorflow/mesh | mesh_tensorflow/layers.py | sigmoid_cross_entropy_with_logits | def sigmoid_cross_entropy_with_logits(logits, targets):
"""Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match.
"""
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
x = logits
z = targets
return mtf.relu(x) - x * z + mtf.log(1 + mtf.exp(-mtf.abs(x))) | python | def sigmoid_cross_entropy_with_logits(logits, targets):
"""Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match.
"""
if logits.shape != targets.shape:
raise ValueError(
"logits shape must equal targets shape"
"logits=%s targets=%s" % (logits.to_string, targets.to_string))
x = logits
z = targets
return mtf.relu(x) - x * z + mtf.log(1 + mtf.exp(-mtf.abs(x))) | [
"def",
"sigmoid_cross_entropy_with_logits",
"(",
"logits",
",",
"targets",
")",
":",
"if",
"logits",
".",
"shape",
"!=",
"targets",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"logits shape must equal targets shape\"",
"\"logits=%s targets=%s\"",
"%",
"(",
"logits",
".",
"to_string",
",",
"targets",
".",
"to_string",
")",
")",
"x",
"=",
"logits",
"z",
"=",
"targets",
"return",
"mtf",
".",
"relu",
"(",
"x",
")",
"-",
"x",
"*",
"z",
"+",
"mtf",
".",
"log",
"(",
"1",
"+",
"mtf",
".",
"exp",
"(",
"-",
"mtf",
".",
"abs",
"(",
"x",
")",
")",
")"
] | Sigmoid cross-entropy loss.
Args:
logits: a mtf.Tensor
targets: a mtf.Tensor with the same shape as logits
Returns:
a mtf.Tensor whose shape is equal to logits.shape
Raises:
ValueError: if the shapes do not match. | [
"Sigmoid",
"cross",
"-",
"entropy",
"loss",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L223-L242 |
227,787 | tensorflow/mesh | mesh_tensorflow/layers.py | dense_relu_dense | def dense_relu_dense(x,
hidden_channels,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32, name=None):
"""Hidden layer with ReLU activation followed by linear projection.
The output has the same number of channels as the input.
Args:
x: a mtf.Tensor
hidden_channels: a mtf.Dimension - channels in the hidden layer
dropout: an optional float
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string
Returns:
a mtf.Tensor with the same shape as x.
"""
with tf.variable_scope(name, default_name="dense_relu_dense"):
io_channels = x.shape.dims[-1]
h = dense(x, hidden_channels,
use_bias=False, activation=mtf.relu,
master_dtype=master_dtype, slice_dtype=slice_dtype, name="wi")
if dropout != 0.0:
h = mtf.dropout(h, 1.0 - dropout,
noise_shape=h.shape - dropout_broadcast_dims)
return dense(h, io_channels, use_bias=False, activation=None,
master_dtype=master_dtype, slice_dtype=slice_dtype,
name="wo") | python | def dense_relu_dense(x,
hidden_channels,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32, name=None):
"""Hidden layer with ReLU activation followed by linear projection.
The output has the same number of channels as the input.
Args:
x: a mtf.Tensor
hidden_channels: a mtf.Dimension - channels in the hidden layer
dropout: an optional float
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string
Returns:
a mtf.Tensor with the same shape as x.
"""
with tf.variable_scope(name, default_name="dense_relu_dense"):
io_channels = x.shape.dims[-1]
h = dense(x, hidden_channels,
use_bias=False, activation=mtf.relu,
master_dtype=master_dtype, slice_dtype=slice_dtype, name="wi")
if dropout != 0.0:
h = mtf.dropout(h, 1.0 - dropout,
noise_shape=h.shape - dropout_broadcast_dims)
return dense(h, io_channels, use_bias=False, activation=None,
master_dtype=master_dtype, slice_dtype=slice_dtype,
name="wo") | [
"def",
"dense_relu_dense",
"(",
"x",
",",
"hidden_channels",
",",
"dropout",
"=",
"0.0",
",",
"dropout_broadcast_dims",
"=",
"None",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"dense_relu_dense\"",
")",
":",
"io_channels",
"=",
"x",
".",
"shape",
".",
"dims",
"[",
"-",
"1",
"]",
"h",
"=",
"dense",
"(",
"x",
",",
"hidden_channels",
",",
"use_bias",
"=",
"False",
",",
"activation",
"=",
"mtf",
".",
"relu",
",",
"master_dtype",
"=",
"master_dtype",
",",
"slice_dtype",
"=",
"slice_dtype",
",",
"name",
"=",
"\"wi\"",
")",
"if",
"dropout",
"!=",
"0.0",
":",
"h",
"=",
"mtf",
".",
"dropout",
"(",
"h",
",",
"1.0",
"-",
"dropout",
",",
"noise_shape",
"=",
"h",
".",
"shape",
"-",
"dropout_broadcast_dims",
")",
"return",
"dense",
"(",
"h",
",",
"io_channels",
",",
"use_bias",
"=",
"False",
",",
"activation",
"=",
"None",
",",
"master_dtype",
"=",
"master_dtype",
",",
"slice_dtype",
"=",
"slice_dtype",
",",
"name",
"=",
"\"wo\"",
")"
] | Hidden layer with ReLU activation followed by linear projection.
The output has the same number of channels as the input.
Args:
x: a mtf.Tensor
hidden_channels: a mtf.Dimension - channels in the hidden layer
dropout: an optional float
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string
Returns:
a mtf.Tensor with the same shape as x. | [
"Hidden",
"layer",
"with",
"ReLU",
"activation",
"followed",
"by",
"linear",
"projection",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L251-L283 |
227,788 | tensorflow/mesh | mesh_tensorflow/layers.py | local_1d_halo_exchange | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
k = mtf.halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
if mask_right:
k = mtf.pad(k, [w_dim, None], w_dim.name)
v = mtf.pad(v, [w_dim, None], w_dim.name)
else:
k = mtf.pad(k, [w_dim, w_dim], w_dim.name)
v = mtf.pad(v, [w_dim, w_dim], w_dim.name)
return k, v | python | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
k = mtf.halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
if mask_right:
k = mtf.pad(k, [w_dim, None], w_dim.name)
v = mtf.pad(v, [w_dim, None], w_dim.name)
else:
k = mtf.pad(k, [w_dim, w_dim], w_dim.name)
v = mtf.pad(v, [w_dim, w_dim], w_dim.name)
return k, v | [
"def",
"local_1d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_w_blocks",
",",
"w_dim",
",",
"mask_right",
")",
":",
"if",
"num_w_blocks",
"is",
"not",
"None",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"k",
",",
"num_w_blocks",
",",
"w_dim",
",",
"w_dim",
".",
"size",
")",
"v",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"v",
",",
"num_w_blocks",
",",
"w_dim",
",",
"w_dim",
".",
"size",
")",
"else",
":",
"k",
"=",
"mtf",
".",
"halo_exchange",
"(",
"k",
",",
"num_w_blocks",
",",
"w_dim",
",",
"w_dim",
".",
"size",
")",
"v",
"=",
"mtf",
".",
"halo_exchange",
"(",
"v",
",",
"num_w_blocks",
",",
"w_dim",
",",
"w_dim",
".",
"size",
")",
"else",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"pad",
"(",
"k",
",",
"[",
"w_dim",
",",
"None",
"]",
",",
"w_dim",
".",
"name",
")",
"v",
"=",
"mtf",
".",
"pad",
"(",
"v",
",",
"[",
"w_dim",
",",
"None",
"]",
",",
"w_dim",
".",
"name",
")",
"else",
":",
"k",
"=",
"mtf",
".",
"pad",
"(",
"k",
",",
"[",
"w_dim",
",",
"w_dim",
"]",
",",
"w_dim",
".",
"name",
")",
"v",
"=",
"mtf",
".",
"pad",
"(",
"v",
",",
"[",
"w_dim",
",",
"w_dim",
"]",
",",
"w_dim",
".",
"name",
")",
"return",
"k",
",",
"v"
] | Halo exchange for keys and values for Local 1D attention. | [
"Halo",
"exchange",
"for",
"keys",
"and",
"values",
"for",
"Local",
"1D",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L286-L302 |
227,789 | tensorflow/mesh | mesh_tensorflow/layers.py | local_2d_halo_exchange | def local_2d_halo_exchange(k, v, num_h_blocks, h_dim,
num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 2D attention."""
for blocks_dim, block_size_dim, halo_size in [
(num_h_blocks, h_dim, h_dim.size),
(num_w_blocks, w_dim, w_dim.size)]:
# shape of k is [num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels]
if halo_size > 0:
if blocks_dim is not None:
if mask_right:
k = mtf.left_halo_exchange(k, blocks_dim, block_size_dim, halo_size)
v = mtf.left_halo_exchange(v, blocks_dim, block_size_dim, halo_size)
else:
k = mtf.halo_exchange(k, blocks_dim, block_size_dim, halo_size)
v = mtf.halo_exchange(v, blocks_dim, block_size_dim, halo_size)
else:
if mask_right:
k = mtf.pad(k, [halo_size, None], block_size_dim.name)
v = mtf.pad(v, [halo_size, None], block_size_dim.name)
else:
k = mtf.pad(k, [halo_size, halo_size], block_size_dim.name)
v = mtf.pad(v, [halo_size, halo_size], block_size_dim.name)
return k, v | python | def local_2d_halo_exchange(k, v, num_h_blocks, h_dim,
num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 2D attention."""
for blocks_dim, block_size_dim, halo_size in [
(num_h_blocks, h_dim, h_dim.size),
(num_w_blocks, w_dim, w_dim.size)]:
# shape of k is [num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels]
if halo_size > 0:
if blocks_dim is not None:
if mask_right:
k = mtf.left_halo_exchange(k, blocks_dim, block_size_dim, halo_size)
v = mtf.left_halo_exchange(v, blocks_dim, block_size_dim, halo_size)
else:
k = mtf.halo_exchange(k, blocks_dim, block_size_dim, halo_size)
v = mtf.halo_exchange(v, blocks_dim, block_size_dim, halo_size)
else:
if mask_right:
k = mtf.pad(k, [halo_size, None], block_size_dim.name)
v = mtf.pad(v, [halo_size, None], block_size_dim.name)
else:
k = mtf.pad(k, [halo_size, halo_size], block_size_dim.name)
v = mtf.pad(v, [halo_size, halo_size], block_size_dim.name)
return k, v | [
"def",
"local_2d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_h_blocks",
",",
"h_dim",
",",
"num_w_blocks",
",",
"w_dim",
",",
"mask_right",
")",
":",
"for",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
"in",
"[",
"(",
"num_h_blocks",
",",
"h_dim",
",",
"h_dim",
".",
"size",
")",
",",
"(",
"num_w_blocks",
",",
"w_dim",
",",
"w_dim",
".",
"size",
")",
"]",
":",
"# shape of k is [num_h_blocks, num_w_blocks, h_dim, w_dim, kv_channels]",
"if",
"halo_size",
">",
"0",
":",
"if",
"blocks_dim",
"is",
"not",
"None",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"k",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
")",
"v",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"v",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
")",
"else",
":",
"k",
"=",
"mtf",
".",
"halo_exchange",
"(",
"k",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
")",
"v",
"=",
"mtf",
".",
"halo_exchange",
"(",
"v",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
")",
"else",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"pad",
"(",
"k",
",",
"[",
"halo_size",
",",
"None",
"]",
",",
"block_size_dim",
".",
"name",
")",
"v",
"=",
"mtf",
".",
"pad",
"(",
"v",
",",
"[",
"halo_size",
",",
"None",
"]",
",",
"block_size_dim",
".",
"name",
")",
"else",
":",
"k",
"=",
"mtf",
".",
"pad",
"(",
"k",
",",
"[",
"halo_size",
",",
"halo_size",
"]",
",",
"block_size_dim",
".",
"name",
")",
"v",
"=",
"mtf",
".",
"pad",
"(",
"v",
",",
"[",
"halo_size",
",",
"halo_size",
"]",
",",
"block_size_dim",
".",
"name",
")",
"return",
"k",
",",
"v"
] | Halo exchange for keys and values for Local 2D attention. | [
"Halo",
"exchange",
"for",
"keys",
"and",
"values",
"for",
"Local",
"2D",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L535-L557 |
227,790 | tensorflow/mesh | mesh_tensorflow/layers.py | local_2d_self_attention_spatial_blocks | def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
mask_right=False,
master_dtype=tf.float32,
slice_dtype=tf.float32,
name=None):
"""Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of length block_size.
Attention for a given query position can only see memory positions
less than or equal to the query position, in the corresponding block
and the previous block.
Args:
query_antecedent: a mtf.Tensor with shape [batch, num_h_blocks,
num_w_blocks, h_dim, w_dim, io_channels] must have the same size as
query_length, but a different name.
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
memory_h_dim: mtf Dimension, for the memory height block.
memory_w_dim: mtf Dimension, for the memory width block.
mask_right: bool, flag specifying whether we mask out attention to the right
for the decoder.
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
a Tensor of shape
[batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]
Raises:
ValueError: if channels or depth don't match.
"""
with tf.variable_scope(
name, default_name="multihead_attention", values=[query_antecedent]):
h_dim, w_dim, io_channels = query_antecedent.shape.dims[-3:]
batch, num_h_blocks, num_w_blocks = query_antecedent.shape.dims[:3]
wq, wk, wv, wo = multihead_attention_vars(
query_antecedent.mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, query_antecedent.dtype)
# Rename dimensions for the memory height and width.
memory_antecedent = mtf.rename_dimension(query_antecedent, h_dim.name,
"memory_" + h_dim.name)
memory_antecedent = mtf.rename_dimension(memory_antecedent, w_dim.name,
"memory_" + w_dim.name)
memory_h_dim, memory_w_dim = memory_antecedent.shape.dims[-3:-1]
# Call einsum over the query and memory to get query q, keys k and values v.
q = mtf.einsum([query_antecedent, wq],
mtf.Shape([
batch, heads, num_h_blocks, num_w_blocks, h_dim, w_dim,
kv_channels
]))
k = mtf.einsum([memory_antecedent, wk],
mtf.Shape([batch, heads, num_h_blocks, num_w_blocks,
memory_h_dim, memory_w_dim, kv_channels]))
v = mtf.einsum([memory_antecedent, wv],
mtf.Shape([batch, heads, num_h_blocks, num_w_blocks,
memory_h_dim, memory_w_dim, kv_channels]))
# Halo exchange for memory blocks.
k, v = local_2d_halo_exchange(k, v, num_h_blocks, memory_h_dim,
num_w_blocks, memory_w_dim, mask_right)
# Calculate the causal mask to avoid peeking into the future. We compute
# this once and reuse it for all blocks since the block_size is known.
mask = None
if mask_right:
mask = attention_bias_local_2d_block(query_antecedent.mesh, h_dim, w_dim,
memory_h_dim, memory_w_dim)
output = dot_product_attention(q, k, v, mask=mask)
return mtf.einsum(
[output, wo],
mtf.Shape(
[batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels])) | python | def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
mask_right=False,
master_dtype=tf.float32,
slice_dtype=tf.float32,
name=None):
"""Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of length block_size.
Attention for a given query position can only see memory positions
less than or equal to the query position, in the corresponding block
and the previous block.
Args:
query_antecedent: a mtf.Tensor with shape [batch, num_h_blocks,
num_w_blocks, h_dim, w_dim, io_channels] must have the same size as
query_length, but a different name.
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
memory_h_dim: mtf Dimension, for the memory height block.
memory_w_dim: mtf Dimension, for the memory width block.
mask_right: bool, flag specifying whether we mask out attention to the right
for the decoder.
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
a Tensor of shape
[batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]
Raises:
ValueError: if channels or depth don't match.
"""
with tf.variable_scope(
name, default_name="multihead_attention", values=[query_antecedent]):
h_dim, w_dim, io_channels = query_antecedent.shape.dims[-3:]
batch, num_h_blocks, num_w_blocks = query_antecedent.shape.dims[:3]
wq, wk, wv, wo = multihead_attention_vars(
query_antecedent.mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, query_antecedent.dtype)
# Rename dimensions for the memory height and width.
memory_antecedent = mtf.rename_dimension(query_antecedent, h_dim.name,
"memory_" + h_dim.name)
memory_antecedent = mtf.rename_dimension(memory_antecedent, w_dim.name,
"memory_" + w_dim.name)
memory_h_dim, memory_w_dim = memory_antecedent.shape.dims[-3:-1]
# Call einsum over the query and memory to get query q, keys k and values v.
q = mtf.einsum([query_antecedent, wq],
mtf.Shape([
batch, heads, num_h_blocks, num_w_blocks, h_dim, w_dim,
kv_channels
]))
k = mtf.einsum([memory_antecedent, wk],
mtf.Shape([batch, heads, num_h_blocks, num_w_blocks,
memory_h_dim, memory_w_dim, kv_channels]))
v = mtf.einsum([memory_antecedent, wv],
mtf.Shape([batch, heads, num_h_blocks, num_w_blocks,
memory_h_dim, memory_w_dim, kv_channels]))
# Halo exchange for memory blocks.
k, v = local_2d_halo_exchange(k, v, num_h_blocks, memory_h_dim,
num_w_blocks, memory_w_dim, mask_right)
# Calculate the causal mask to avoid peeking into the future. We compute
# this once and reuse it for all blocks since the block_size is known.
mask = None
if mask_right:
mask = attention_bias_local_2d_block(query_antecedent.mesh, h_dim, w_dim,
memory_h_dim, memory_w_dim)
output = dot_product_attention(q, k, v, mask=mask)
return mtf.einsum(
[output, wo],
mtf.Shape(
[batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels])) | [
"def",
"local_2d_self_attention_spatial_blocks",
"(",
"query_antecedent",
",",
"kv_channels",
",",
"heads",
",",
"memory_h_dim",
"=",
"None",
",",
"memory_w_dim",
"=",
"None",
",",
"mask_right",
"=",
"False",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"multihead_attention\"",
",",
"values",
"=",
"[",
"query_antecedent",
"]",
")",
":",
"h_dim",
",",
"w_dim",
",",
"io_channels",
"=",
"query_antecedent",
".",
"shape",
".",
"dims",
"[",
"-",
"3",
":",
"]",
"batch",
",",
"num_h_blocks",
",",
"num_w_blocks",
"=",
"query_antecedent",
".",
"shape",
".",
"dims",
"[",
":",
"3",
"]",
"wq",
",",
"wk",
",",
"wv",
",",
"wo",
"=",
"multihead_attention_vars",
"(",
"query_antecedent",
".",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"master_dtype",
",",
"slice_dtype",
",",
"query_antecedent",
".",
"dtype",
")",
"# Rename dimensions for the memory height and width.",
"memory_antecedent",
"=",
"mtf",
".",
"rename_dimension",
"(",
"query_antecedent",
",",
"h_dim",
".",
"name",
",",
"\"memory_\"",
"+",
"h_dim",
".",
"name",
")",
"memory_antecedent",
"=",
"mtf",
".",
"rename_dimension",
"(",
"memory_antecedent",
",",
"w_dim",
".",
"name",
",",
"\"memory_\"",
"+",
"w_dim",
".",
"name",
")",
"memory_h_dim",
",",
"memory_w_dim",
"=",
"memory_antecedent",
".",
"shape",
".",
"dims",
"[",
"-",
"3",
":",
"-",
"1",
"]",
"# Call einsum over the query and memory to get query q, keys k and values v.",
"q",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"query_antecedent",
",",
"wq",
"]",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch",
",",
"heads",
",",
"num_h_blocks",
",",
"num_w_blocks",
",",
"h_dim",
",",
"w_dim",
",",
"kv_channels",
"]",
")",
")",
"k",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"wk",
"]",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch",
",",
"heads",
",",
"num_h_blocks",
",",
"num_w_blocks",
",",
"memory_h_dim",
",",
"memory_w_dim",
",",
"kv_channels",
"]",
")",
")",
"v",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"wv",
"]",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch",
",",
"heads",
",",
"num_h_blocks",
",",
"num_w_blocks",
",",
"memory_h_dim",
",",
"memory_w_dim",
",",
"kv_channels",
"]",
")",
")",
"# Halo exchange for memory blocks.",
"k",
",",
"v",
"=",
"local_2d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_h_blocks",
",",
"memory_h_dim",
",",
"num_w_blocks",
",",
"memory_w_dim",
",",
"mask_right",
")",
"# Calculate the causal mask to avoid peeking into the future. We compute",
"# this once and reuse it for all blocks since the block_size is known.",
"mask",
"=",
"None",
"if",
"mask_right",
":",
"mask",
"=",
"attention_bias_local_2d_block",
"(",
"query_antecedent",
".",
"mesh",
",",
"h_dim",
",",
"w_dim",
",",
"memory_h_dim",
",",
"memory_w_dim",
")",
"output",
"=",
"dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"mask",
"=",
"mask",
")",
"return",
"mtf",
".",
"einsum",
"(",
"[",
"output",
",",
"wo",
"]",
",",
"mtf",
".",
"Shape",
"(",
"[",
"batch",
",",
"num_h_blocks",
",",
"num_w_blocks",
",",
"h_dim",
",",
"w_dim",
",",
"io_channels",
"]",
")",
")"
] | Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of length block_size.
Attention for a given query position can only see memory positions
less than or equal to the query position, in the corresponding block
and the previous block.
Args:
query_antecedent: a mtf.Tensor with shape [batch, num_h_blocks,
num_w_blocks, h_dim, w_dim, io_channels] must have the same size as
query_length, but a different name.
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
memory_h_dim: mtf Dimension, for the memory height block.
memory_w_dim: mtf Dimension, for the memory width block.
mask_right: bool, flag specifying whether we mask out attention to the right
for the decoder.
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
a Tensor of shape
[batch, num_h_blocks, num_w_blocks, h_dim, w_dim, io_channels]
Raises:
ValueError: if channels or depth don't match. | [
"Attention",
"to",
"the",
"source",
"position",
"and",
"a",
"neighborhood",
"to",
"the",
"left",
"or",
"right",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L560-L642 |
227,791 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_attention_vars | def multihead_attention_vars(
mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, activation_dtype):
"""Deprecated version of multihead_attention_params with combine=True."""
return multihead_attention_params(
mesh, heads, io_channels, kv_channels,
mtf.VariableDType(master_dtype, slice_dtype, activation_dtype),
combine=True) | python | def multihead_attention_vars(
mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, activation_dtype):
"""Deprecated version of multihead_attention_params with combine=True."""
return multihead_attention_params(
mesh, heads, io_channels, kv_channels,
mtf.VariableDType(master_dtype, slice_dtype, activation_dtype),
combine=True) | [
"def",
"multihead_attention_vars",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"master_dtype",
",",
"slice_dtype",
",",
"activation_dtype",
")",
":",
"return",
"multihead_attention_params",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"mtf",
".",
"VariableDType",
"(",
"master_dtype",
",",
"slice_dtype",
",",
"activation_dtype",
")",
",",
"combine",
"=",
"True",
")"
] | Deprecated version of multihead_attention_params with combine=True. | [
"Deprecated",
"version",
"of",
"multihead_attention_params",
"with",
"combine",
"=",
"True",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L650-L657 |
227,792 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_attention_params | def multihead_attention_params(mesh, heads, io_channels, kv_channels,
variable_dtype, combine=False):
"""Create Parameters for Multihead Attention.
If the combine flag is set to True, then we create only one variable
which stacks together all of the parameters. Otherwise, we create four
separate variables.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
variable_dtype: a mtf.VariableDType
combine: a boolean
Returns:
wq: a Tensor with shape [heads, io_channels, kv_channels]
wk: a Tensor with shape [heads, io_channels, kv_channels]
wv: a Tensor with shape [heads, io_channels, kv_channels]
wo: a Tensor with shape [heads, io_channels, kv_channels]
"""
qkvo = mtf.Dimension("qkvo", 4)
qk_stddev = (io_channels.size ** -0.5) * (kv_channels.size ** -0.25)
v_stddev = io_channels.size ** -0.5
# TODO(noam): should be: o_stddev = (kv_channels.size * heads.size) ** -0.5
# verify that this still works and change it.
o_stddev = (io_channels.size * heads.size) ** -0.5
if combine:
def qkvo_initializer(shape,
dtype=None,
partition_info=None,
verify_shape=None):
del partition_info, verify_shape
return tf.random_normal(shape, dtype=dtype) * tf.reshape(
tf.cast([qk_stddev, qk_stddev, v_stddev, o_stddev],
dtype or tf.float32), [4, 1, 1, 1])
var = mtf.get_variable(
mesh, "qkvo", mtf.Shape([qkvo, heads, io_channels, kv_channels]),
initializer=qkvo_initializer, dtype=variable_dtype)
return mtf.unstack(var, qkvo)
else:
return [mtf.get_variable(
mesh, name, mtf.Shape([heads, io_channels, kv_channels]),
initializer=tf.random_normal_initializer(stddev=stddev),
dtype=variable_dtype) for name, stddev in zip(
["q", "k", "v", "o"],
[qk_stddev, qk_stddev, v_stddev, o_stddev])] | python | def multihead_attention_params(mesh, heads, io_channels, kv_channels,
variable_dtype, combine=False):
"""Create Parameters for Multihead Attention.
If the combine flag is set to True, then we create only one variable
which stacks together all of the parameters. Otherwise, we create four
separate variables.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
variable_dtype: a mtf.VariableDType
combine: a boolean
Returns:
wq: a Tensor with shape [heads, io_channels, kv_channels]
wk: a Tensor with shape [heads, io_channels, kv_channels]
wv: a Tensor with shape [heads, io_channels, kv_channels]
wo: a Tensor with shape [heads, io_channels, kv_channels]
"""
qkvo = mtf.Dimension("qkvo", 4)
qk_stddev = (io_channels.size ** -0.5) * (kv_channels.size ** -0.25)
v_stddev = io_channels.size ** -0.5
# TODO(noam): should be: o_stddev = (kv_channels.size * heads.size) ** -0.5
# verify that this still works and change it.
o_stddev = (io_channels.size * heads.size) ** -0.5
if combine:
def qkvo_initializer(shape,
dtype=None,
partition_info=None,
verify_shape=None):
del partition_info, verify_shape
return tf.random_normal(shape, dtype=dtype) * tf.reshape(
tf.cast([qk_stddev, qk_stddev, v_stddev, o_stddev],
dtype or tf.float32), [4, 1, 1, 1])
var = mtf.get_variable(
mesh, "qkvo", mtf.Shape([qkvo, heads, io_channels, kv_channels]),
initializer=qkvo_initializer, dtype=variable_dtype)
return mtf.unstack(var, qkvo)
else:
return [mtf.get_variable(
mesh, name, mtf.Shape([heads, io_channels, kv_channels]),
initializer=tf.random_normal_initializer(stddev=stddev),
dtype=variable_dtype) for name, stddev in zip(
["q", "k", "v", "o"],
[qk_stddev, qk_stddev, v_stddev, o_stddev])] | [
"def",
"multihead_attention_params",
"(",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"variable_dtype",
",",
"combine",
"=",
"False",
")",
":",
"qkvo",
"=",
"mtf",
".",
"Dimension",
"(",
"\"qkvo\"",
",",
"4",
")",
"qk_stddev",
"=",
"(",
"io_channels",
".",
"size",
"**",
"-",
"0.5",
")",
"*",
"(",
"kv_channels",
".",
"size",
"**",
"-",
"0.25",
")",
"v_stddev",
"=",
"io_channels",
".",
"size",
"**",
"-",
"0.5",
"# TODO(noam): should be: o_stddev = (kv_channels.size * heads.size) ** -0.5",
"# verify that this still works and change it.",
"o_stddev",
"=",
"(",
"io_channels",
".",
"size",
"*",
"heads",
".",
"size",
")",
"**",
"-",
"0.5",
"if",
"combine",
":",
"def",
"qkvo_initializer",
"(",
"shape",
",",
"dtype",
"=",
"None",
",",
"partition_info",
"=",
"None",
",",
"verify_shape",
"=",
"None",
")",
":",
"del",
"partition_info",
",",
"verify_shape",
"return",
"tf",
".",
"random_normal",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"*",
"tf",
".",
"reshape",
"(",
"tf",
".",
"cast",
"(",
"[",
"qk_stddev",
",",
"qk_stddev",
",",
"v_stddev",
",",
"o_stddev",
"]",
",",
"dtype",
"or",
"tf",
".",
"float32",
")",
",",
"[",
"4",
",",
"1",
",",
"1",
",",
"1",
"]",
")",
"var",
"=",
"mtf",
".",
"get_variable",
"(",
"mesh",
",",
"\"qkvo\"",
",",
"mtf",
".",
"Shape",
"(",
"[",
"qkvo",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
"]",
")",
",",
"initializer",
"=",
"qkvo_initializer",
",",
"dtype",
"=",
"variable_dtype",
")",
"return",
"mtf",
".",
"unstack",
"(",
"var",
",",
"qkvo",
")",
"else",
":",
"return",
"[",
"mtf",
".",
"get_variable",
"(",
"mesh",
",",
"name",
",",
"mtf",
".",
"Shape",
"(",
"[",
"heads",
",",
"io_channels",
",",
"kv_channels",
"]",
")",
",",
"initializer",
"=",
"tf",
".",
"random_normal_initializer",
"(",
"stddev",
"=",
"stddev",
")",
",",
"dtype",
"=",
"variable_dtype",
")",
"for",
"name",
",",
"stddev",
"in",
"zip",
"(",
"[",
"\"q\"",
",",
"\"k\"",
",",
"\"v\"",
",",
"\"o\"",
"]",
",",
"[",
"qk_stddev",
",",
"qk_stddev",
",",
"v_stddev",
",",
"o_stddev",
"]",
")",
"]"
] | Create Parameters for Multihead Attention.
If the combine flag is set to True, then we create only one variable
which stacks together all of the parameters. Otherwise, we create four
separate variables.
Args:
mesh: a Mesh
heads: a Dimension
io_channels: a Dimension
kv_channels: a Dimension
variable_dtype: a mtf.VariableDType
combine: a boolean
Returns:
wq: a Tensor with shape [heads, io_channels, kv_channels]
wk: a Tensor with shape [heads, io_channels, kv_channels]
wv: a Tensor with shape [heads, io_channels, kv_channels]
wo: a Tensor with shape [heads, io_channels, kv_channels] | [
"Create",
"Parameters",
"for",
"Multihead",
"Attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L660-L707 |
227,793 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_ignore_padding | def attention_mask_ignore_padding(inputs, dtype=tf.float32):
"""Bias for encoder-decoder attention.
Args:
inputs: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., memory_length_dim]
"""
inputs = rename_length_to_memory_length(inputs)
return mtf.cast(mtf.equal(inputs, 0), dtype) * -1e9 | python | def attention_mask_ignore_padding(inputs, dtype=tf.float32):
"""Bias for encoder-decoder attention.
Args:
inputs: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., memory_length_dim]
"""
inputs = rename_length_to_memory_length(inputs)
return mtf.cast(mtf.equal(inputs, 0), dtype) * -1e9 | [
"def",
"attention_mask_ignore_padding",
"(",
"inputs",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"inputs",
"=",
"rename_length_to_memory_length",
"(",
"inputs",
")",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"equal",
"(",
"inputs",
",",
"0",
")",
",",
"dtype",
")",
"*",
"-",
"1e9"
] | Bias for encoder-decoder attention.
Args:
inputs: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., memory_length_dim] | [
"Bias",
"for",
"encoder",
"-",
"decoder",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L918-L929 |
227,794 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_autoregressive | def attention_mask_autoregressive(query_pos, dtype=tf.float32):
"""Bias for self-attention where attention to the right is disallowed.
Args:
query_pos: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim]
"""
memory_pos = rename_length_to_memory_length(query_pos)
return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1e9 | python | def attention_mask_autoregressive(query_pos, dtype=tf.float32):
"""Bias for self-attention where attention to the right is disallowed.
Args:
query_pos: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim]
"""
memory_pos = rename_length_to_memory_length(query_pos)
return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1e9 | [
"def",
"attention_mask_autoregressive",
"(",
"query_pos",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"memory_pos",
"=",
"rename_length_to_memory_length",
"(",
"query_pos",
")",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"less",
"(",
"query_pos",
",",
"memory_pos",
")",
",",
"dtype",
")",
"*",
"-",
"1e9"
] | Bias for self-attention where attention to the right is disallowed.
Args:
query_pos: a mtf.Tensor with shape [..., length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim] | [
"Bias",
"for",
"self",
"-",
"attention",
"where",
"attention",
"to",
"the",
"right",
"is",
"disallowed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L932-L943 |
227,795 | tensorflow/mesh | mesh_tensorflow/layers.py | attention_mask_same_segment | def attention_mask_same_segment(
query_segment, memory_segment=None, dtype=tf.float32):
"""Bias for attention where attention between segments is disallowed.
Args:
query_segment: a mtf.Tensor with shape [..., length_dim]
memory_segment: a mtf.Tensor with shape [..., memory_length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim]
"""
memory_segment = rename_length_to_memory_length(
memory_segment or query_segment)
return mtf.cast(mtf.not_equal(query_segment, memory_segment), dtype) * -1e9 | python | def attention_mask_same_segment(
query_segment, memory_segment=None, dtype=tf.float32):
"""Bias for attention where attention between segments is disallowed.
Args:
query_segment: a mtf.Tensor with shape [..., length_dim]
memory_segment: a mtf.Tensor with shape [..., memory_length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim]
"""
memory_segment = rename_length_to_memory_length(
memory_segment or query_segment)
return mtf.cast(mtf.not_equal(query_segment, memory_segment), dtype) * -1e9 | [
"def",
"attention_mask_same_segment",
"(",
"query_segment",
",",
"memory_segment",
"=",
"None",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"memory_segment",
"=",
"rename_length_to_memory_length",
"(",
"memory_segment",
"or",
"query_segment",
")",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"not_equal",
"(",
"query_segment",
",",
"memory_segment",
")",
",",
"dtype",
")",
"*",
"-",
"1e9"
] | Bias for attention where attention between segments is disallowed.
Args:
query_segment: a mtf.Tensor with shape [..., length_dim]
memory_segment: a mtf.Tensor with shape [..., memory_length_dim]
dtype: a tf.dtype
Returns:
a mtf.Tensor with shape [..., length_dim, memory_length_dim] | [
"Bias",
"for",
"attention",
"where",
"attention",
"between",
"segments",
"is",
"disallowed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L946-L960 |
227,796 | tensorflow/mesh | mesh_tensorflow/layers.py | multiplicative_jitter | def multiplicative_jitter(x, epsilon=1e-2):
"""Multiply values by a random number between 1-epsilon and 1+epsilon.
Makes models more resilient to rounding errors introduced by bfloat16.
This seems particularly important for logits.
Args:
x: a mtf.Tensor
epsilon: a floating point value
Returns:
a mtf.Tensor with the same type and shape as x.
"""
if epsilon == 0:
return x
return x * mtf.random_uniform(
x.mesh, x.shape, minval=1.0 - epsilon, maxval=1.0+epsilon, dtype=x.dtype) | python | def multiplicative_jitter(x, epsilon=1e-2):
"""Multiply values by a random number between 1-epsilon and 1+epsilon.
Makes models more resilient to rounding errors introduced by bfloat16.
This seems particularly important for logits.
Args:
x: a mtf.Tensor
epsilon: a floating point value
Returns:
a mtf.Tensor with the same type and shape as x.
"""
if epsilon == 0:
return x
return x * mtf.random_uniform(
x.mesh, x.shape, minval=1.0 - epsilon, maxval=1.0+epsilon, dtype=x.dtype) | [
"def",
"multiplicative_jitter",
"(",
"x",
",",
"epsilon",
"=",
"1e-2",
")",
":",
"if",
"epsilon",
"==",
"0",
":",
"return",
"x",
"return",
"x",
"*",
"mtf",
".",
"random_uniform",
"(",
"x",
".",
"mesh",
",",
"x",
".",
"shape",
",",
"minval",
"=",
"1.0",
"-",
"epsilon",
",",
"maxval",
"=",
"1.0",
"+",
"epsilon",
",",
"dtype",
"=",
"x",
".",
"dtype",
")"
] | Multiply values by a random number between 1-epsilon and 1+epsilon.
Makes models more resilient to rounding errors introduced by bfloat16.
This seems particularly important for logits.
Args:
x: a mtf.Tensor
epsilon: a floating point value
Returns:
a mtf.Tensor with the same type and shape as x. | [
"Multiply",
"values",
"by",
"a",
"random",
"number",
"between",
"1",
"-",
"epsilon",
"and",
"1",
"+",
"epsilon",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1029-L1045 |
227,797 | tensorflow/mesh | mesh_tensorflow/layers.py | multihead_self_attention_memory_compressed | def multihead_self_attention_memory_compressed(x,
mask_right,
compression_factor,
kv_channels,
heads,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32,
name="multihead_attention"):
"""Memory-compressed self-attention.
The memory is first average-pooled (strided) to make it shorter by
a factor of compression_factor.
Args:
x: a mtf.Tensor with shape
[<batch_dims>, query_length, io_channels]
mask_right: a boolean
compression_factor: an integer
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
dropout: a floating point value
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
A mtf.Tensor with shape [batch, query_length, io_channels]
Raises:
ValueError: if the dimensions do not match.
"""
batch_dims = x.shape.dims[:-2]
length, io_channels = x.shape.dims[-2:]
with tf.variable_scope(name,
default_name="compressed_attention",
values=[x]):
wq, wk, wv, wo = multihead_attention_vars(
x.mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, x.dtype)
memory_antecedent = compress_mean(x, length, compression_factor)
memory_antecedent = rename_length_to_memory_length(memory_antecedent)
memory_length = memory_antecedent.shape.dims[-2]
q = mtf.einsum(
[x, wq],
mtf.Shape(batch_dims + [heads, length, kv_channels]))
k = mtf.einsum(
[memory_antecedent, wk],
mtf.Shape(batch_dims + [heads, memory_length, kv_channels]))
v = mtf.einsum(
[memory_antecedent, wv],
mtf.Shape(batch_dims + [heads, memory_length, kv_channels]))
if mask_right:
query_pos = mtf.range(x.mesh, length, dtype=tf.int32)
memory_pos = (
mtf.range(x.mesh, memory_length, dtype=tf.int32) * compression_factor
+ (compression_factor - 1))
mask = mtf.cast(mtf.greater(memory_pos, query_pos), x.dtype) * -1e9
else:
mask = None
o = dot_product_attention(
q, k, v, mask, dropout, dropout_broadcast_dims, extra_logit=0.0)
return mtf.einsum(
[o, wo], mtf.Shape(batch_dims + [length, io_channels])) | python | def multihead_self_attention_memory_compressed(x,
mask_right,
compression_factor,
kv_channels,
heads,
dropout=0.0,
dropout_broadcast_dims=None,
master_dtype=tf.float32,
slice_dtype=tf.float32,
name="multihead_attention"):
"""Memory-compressed self-attention.
The memory is first average-pooled (strided) to make it shorter by
a factor of compression_factor.
Args:
x: a mtf.Tensor with shape
[<batch_dims>, query_length, io_channels]
mask_right: a boolean
compression_factor: an integer
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
dropout: a floating point value
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
A mtf.Tensor with shape [batch, query_length, io_channels]
Raises:
ValueError: if the dimensions do not match.
"""
batch_dims = x.shape.dims[:-2]
length, io_channels = x.shape.dims[-2:]
with tf.variable_scope(name,
default_name="compressed_attention",
values=[x]):
wq, wk, wv, wo = multihead_attention_vars(
x.mesh, heads, io_channels, kv_channels,
master_dtype, slice_dtype, x.dtype)
memory_antecedent = compress_mean(x, length, compression_factor)
memory_antecedent = rename_length_to_memory_length(memory_antecedent)
memory_length = memory_antecedent.shape.dims[-2]
q = mtf.einsum(
[x, wq],
mtf.Shape(batch_dims + [heads, length, kv_channels]))
k = mtf.einsum(
[memory_antecedent, wk],
mtf.Shape(batch_dims + [heads, memory_length, kv_channels]))
v = mtf.einsum(
[memory_antecedent, wv],
mtf.Shape(batch_dims + [heads, memory_length, kv_channels]))
if mask_right:
query_pos = mtf.range(x.mesh, length, dtype=tf.int32)
memory_pos = (
mtf.range(x.mesh, memory_length, dtype=tf.int32) * compression_factor
+ (compression_factor - 1))
mask = mtf.cast(mtf.greater(memory_pos, query_pos), x.dtype) * -1e9
else:
mask = None
o = dot_product_attention(
q, k, v, mask, dropout, dropout_broadcast_dims, extra_logit=0.0)
return mtf.einsum(
[o, wo], mtf.Shape(batch_dims + [length, io_channels])) | [
"def",
"multihead_self_attention_memory_compressed",
"(",
"x",
",",
"mask_right",
",",
"compression_factor",
",",
"kv_channels",
",",
"heads",
",",
"dropout",
"=",
"0.0",
",",
"dropout_broadcast_dims",
"=",
"None",
",",
"master_dtype",
"=",
"tf",
".",
"float32",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"name",
"=",
"\"multihead_attention\"",
")",
":",
"batch_dims",
"=",
"x",
".",
"shape",
".",
"dims",
"[",
":",
"-",
"2",
"]",
"length",
",",
"io_channels",
"=",
"x",
".",
"shape",
".",
"dims",
"[",
"-",
"2",
":",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"compressed_attention\"",
",",
"values",
"=",
"[",
"x",
"]",
")",
":",
"wq",
",",
"wk",
",",
"wv",
",",
"wo",
"=",
"multihead_attention_vars",
"(",
"x",
".",
"mesh",
",",
"heads",
",",
"io_channels",
",",
"kv_channels",
",",
"master_dtype",
",",
"slice_dtype",
",",
"x",
".",
"dtype",
")",
"memory_antecedent",
"=",
"compress_mean",
"(",
"x",
",",
"length",
",",
"compression_factor",
")",
"memory_antecedent",
"=",
"rename_length_to_memory_length",
"(",
"memory_antecedent",
")",
"memory_length",
"=",
"memory_antecedent",
".",
"shape",
".",
"dims",
"[",
"-",
"2",
"]",
"q",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"x",
",",
"wq",
"]",
",",
"mtf",
".",
"Shape",
"(",
"batch_dims",
"+",
"[",
"heads",
",",
"length",
",",
"kv_channels",
"]",
")",
")",
"k",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"wk",
"]",
",",
"mtf",
".",
"Shape",
"(",
"batch_dims",
"+",
"[",
"heads",
",",
"memory_length",
",",
"kv_channels",
"]",
")",
")",
"v",
"=",
"mtf",
".",
"einsum",
"(",
"[",
"memory_antecedent",
",",
"wv",
"]",
",",
"mtf",
".",
"Shape",
"(",
"batch_dims",
"+",
"[",
"heads",
",",
"memory_length",
",",
"kv_channels",
"]",
")",
")",
"if",
"mask_right",
":",
"query_pos",
"=",
"mtf",
".",
"range",
"(",
"x",
".",
"mesh",
",",
"length",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"memory_pos",
"=",
"(",
"mtf",
".",
"range",
"(",
"x",
".",
"mesh",
",",
"memory_length",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"*",
"compression_factor",
"+",
"(",
"compression_factor",
"-",
"1",
")",
")",
"mask",
"=",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"greater",
"(",
"memory_pos",
",",
"query_pos",
")",
",",
"x",
".",
"dtype",
")",
"*",
"-",
"1e9",
"else",
":",
"mask",
"=",
"None",
"o",
"=",
"dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
",",
"mask",
",",
"dropout",
",",
"dropout_broadcast_dims",
",",
"extra_logit",
"=",
"0.0",
")",
"return",
"mtf",
".",
"einsum",
"(",
"[",
"o",
",",
"wo",
"]",
",",
"mtf",
".",
"Shape",
"(",
"batch_dims",
"+",
"[",
"length",
",",
"io_channels",
"]",
")",
")"
] | Memory-compressed self-attention.
The memory is first average-pooled (strided) to make it shorter by
a factor of compression_factor.
Args:
x: a mtf.Tensor with shape
[<batch_dims>, query_length, io_channels]
mask_right: a boolean
compression_factor: an integer
kv_channels: a mtf.Dimension (the size of the key and value vectors)
heads: a mtf.Dimension (the number of heads)
dropout: a floating point value
dropout_broadcast_dims: an optional list of mtf.Dimension
master_dtype: a tf.dtype
slice_dtype: a tf.dtype
name: an optional string.
Returns:
A mtf.Tensor with shape [batch, query_length, io_channels]
Raises:
ValueError: if the dimensions do not match. | [
"Memory",
"-",
"compressed",
"self",
"-",
"attention",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1048-L1113 |
227,798 | tensorflow/mesh | mesh_tensorflow/layers.py | compress_mean | def compress_mean(x, dim, compression_factor):
"""Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor
"""
dims = x.shape.dims
pos = dims.index(dim)
compressed_dim = mtf.Dimension(dim.name, dim.size // compression_factor)
compression_factor_dim = mtf.Dimension(
"compression_factor", compression_factor)
new_shape = (
dims[:pos] + [compressed_dim, compression_factor_dim] + dims[pos + 1:])
x = mtf.reshape(x, new_shape)
x = mtf.reduce_mean(x, reduced_dim=compression_factor_dim)
return x | python | def compress_mean(x, dim, compression_factor):
"""Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor
"""
dims = x.shape.dims
pos = dims.index(dim)
compressed_dim = mtf.Dimension(dim.name, dim.size // compression_factor)
compression_factor_dim = mtf.Dimension(
"compression_factor", compression_factor)
new_shape = (
dims[:pos] + [compressed_dim, compression_factor_dim] + dims[pos + 1:])
x = mtf.reshape(x, new_shape)
x = mtf.reduce_mean(x, reduced_dim=compression_factor_dim)
return x | [
"def",
"compress_mean",
"(",
"x",
",",
"dim",
",",
"compression_factor",
")",
":",
"dims",
"=",
"x",
".",
"shape",
".",
"dims",
"pos",
"=",
"dims",
".",
"index",
"(",
"dim",
")",
"compressed_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"dim",
".",
"name",
",",
"dim",
".",
"size",
"//",
"compression_factor",
")",
"compression_factor_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"compression_factor\"",
",",
"compression_factor",
")",
"new_shape",
"=",
"(",
"dims",
"[",
":",
"pos",
"]",
"+",
"[",
"compressed_dim",
",",
"compression_factor_dim",
"]",
"+",
"dims",
"[",
"pos",
"+",
"1",
":",
"]",
")",
"x",
"=",
"mtf",
".",
"reshape",
"(",
"x",
",",
"new_shape",
")",
"x",
"=",
"mtf",
".",
"reduce_mean",
"(",
"x",
",",
"reduced_dim",
"=",
"compression_factor_dim",
")",
"return",
"x"
] | Compress by taking group means.
Args:
x: a Tensor
dim: a dimension in x.shape
compression_factor: an integer
Returns:
a Tensor | [
"Compress",
"by",
"taking",
"group",
"means",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1116-L1136 |
227,799 | tensorflow/mesh | mesh_tensorflow/layers.py | embedding | def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"):
"""Embedding layer."""
weights = embedding_weights(
indices.mesh, vocab_dim, output_dim, variable_dtype, name)
return mtf.gather(weights, indices, vocab_dim) | python | def embedding(indices, vocab_dim, output_dim, variable_dtype, name="embedding"):
"""Embedding layer."""
weights = embedding_weights(
indices.mesh, vocab_dim, output_dim, variable_dtype, name)
return mtf.gather(weights, indices, vocab_dim) | [
"def",
"embedding",
"(",
"indices",
",",
"vocab_dim",
",",
"output_dim",
",",
"variable_dtype",
",",
"name",
"=",
"\"embedding\"",
")",
":",
"weights",
"=",
"embedding_weights",
"(",
"indices",
".",
"mesh",
",",
"vocab_dim",
",",
"output_dim",
",",
"variable_dtype",
",",
"name",
")",
"return",
"mtf",
".",
"gather",
"(",
"weights",
",",
"indices",
",",
"vocab_dim",
")"
] | Embedding layer. | [
"Embedding",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1146-L1150 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.