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: ...
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: ...
[ "def", "list_images", "(", "path", "=", "[", "'.'", "]", ")", ":", "for", "image_dir", "in", "set", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "image_dir", ")", ":", "continue", "for", "filename", "in", "os", ".", "...
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, file...
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, file...
[ "def", "list_all_image", "(", "path", ",", "valid_exts", "=", "VALID_IMAGE_EXTS", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "bname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", ...
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...
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...
[ "def", "search_image", "(", "name", "=", "None", ",", "path", "=", "[", "'.'", "]", ")", ":", "name", "=", "strutils", ".", "decode", "(", "name", ")", "for", "image_dir", "in", "path", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "ima...
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)...
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)...
[ "def", "run_cmd", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "pop", "(", "'timeout'", ",", "None", ")", "p", "=", "self", ".", "raw_cmd", "(", "*", "args", ",", "*", "*", "kwargs", ")", "ret...
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...
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...
[ "def", "display", "(", "self", ")", ":", "w", ",", "h", "=", "(", "0", ",", "0", ")", "for", "line", "in", "self", ".", "shell", "(", "'dumpsys'", ",", "'display'", ")", ".", "splitlines", "(", ")", ":", "m", "=", "_DISPLAY_RE", ".", "search", ...
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 ...
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 ...
[ "def", "packages", "(", "self", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'package:(/[^=]+\\.apk)=([^\\s]+)'", ")", "packages", "=", "[", "]", "for", "line", "in", "self", ".", "shell", "(", "'pm'", ",", "'list'", ",", "'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'...
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'...
[ "def", "_adb_screencap", "(", "self", ",", "scale", "=", "1.0", ")", ":", "remote_file", "=", "tempfile", ".", "mktemp", "(", "dir", "=", "'/data/local/tmp/'", ",", "prefix", "=", "'screencap-'", ",", "suffix", "=", "'.png'", ")", "local_file", "=", "tempf...
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...
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...
[ "def", "_adb_minicap", "(", "self", ",", "scale", "=", "1.0", ")", ":", "remote_file", "=", "tempfile", ".", "mktemp", "(", "dir", "=", "'/data/local/tmp/'", ",", "prefix", "=", "'minicap-'", ",", "suffix", "=", "'.jpg'", ")", "local_file", "=", "tempfile"...
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 ...
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 ...
[ "def", "screenshot", "(", "self", ",", "filename", "=", "None", ",", "scale", "=", "1.0", ",", "method", "=", "None", ")", ":", "image", "=", "None", "method", "=", "method", "or", "self", ".", "_screenshot_method", "if", "method", "==", "'minicap'", "...
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"...
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['f...
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['f...
[ "def", "analyze_frames", "(", "cls", ",", "workdir", ")", ":", "record", "=", "cls", "(", "None", ",", "workdir", ")", "obj", "=", "{", "}", "with", "open", "(", "os", ".", "path", ".", "join", "(", "workdir", ",", "'frames'", ",", "'frames.json'", ...
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...
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...
[ "def", "process_casefile", "(", "cls", ",", "workdir", ")", ":", "record", "=", "cls", "(", "None", ",", "workdir", ")", "obj", "=", "{", "}", "with", "open", "(", "os", ".", "path", ".", "join", "(", "workdir", ",", "'frames'", ",", "'frames.json'",...
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...
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...
[ "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", "...
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'"...
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...
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...
[ "def", "main", "(", "host", "=", "None", ",", "port", "=", "None", ",", "serial", "=", "None", ",", "scale", "=", "1.0", ",", "out", "=", "'screenshot.png'", ",", "method", "=", "'minicap'", ")", ":", "print", "(", "'Started screencap'", ")", "start", ...
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 se...
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 se...
[ "def", "rotation", "(", "self", ")", ":", "if", "self", ".", "screen_rotation", "in", "range", "(", "4", ")", ":", "return", "self", ".", "screen_rotation", "return", "self", ".", "adb_device", ".", "rotation", "(", ")", "or", "self", ".", "info", "[",...
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 ...
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 ...
[ "def", "properties", "(", "self", ")", ":", "props", "=", "{", "}", "for", "line", "in", "self", ".", "adb_shell", "(", "[", "'getprop'", "]", ")", ".", "splitlines", "(", ")", ":", "m", "=", "_PROP_PATTERN", ".", "match", "(", "line", ")", "if", ...
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 - ne...
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 - ne...
[ "def", "type", "(", "self", ",", "s", ",", "enter", "=", "False", ",", "clear", "=", "False", ")", ":", "if", "clear", ":", "self", ".", "clear_text", "(", ")", "self", ".", "_uiauto", ".", "send_keys", "(", "s", ")", "if", "enter", ":", "self", ...
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...
[ "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() ...
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() ...
[ "def", "input_methods", "(", "self", ")", ":", "imes", "=", "[", "]", "for", "line", "in", "self", ".", "adb_shell", "(", "[", "'ime'", ",", "'list'", ",", "'-s'", ",", "'-a'", "]", ")", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".",...
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"...
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", "[...
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", "=", ...
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(ov...
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(ov...
[ "def", "mark_point", "(", "img", ",", "x", ",", "y", ")", ":", "overlay", "=", "img", ".", "copy", "(", ")", "output", "=", "img", ".", "copy", "(", ")", "alpha", "=", "0.5", "radius", "=", "max", "(", "5", ",", "min", "(", "img", ".", "shape...
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 sel...
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 sel...
[ "def", "forward", "(", "self", ",", "device_port", ",", "local_port", "=", "None", ")", ":", "if", "local_port", "is", "None", ":", "for", "s", ",", "lp", ",", "rp", "in", "self", ".", "forward_list", "(", ")", ":", "if", "s", "==", "self", ".", ...
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", "==", ...
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_origin...
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_origin...
[ "def", "patch_wda", "(", "self", ")", ":", "import", "wda", "def", "_click", "(", "that", ")", ":", "rawx", ",", "rawy", "=", "that", ".", "bounds", ".", "center", "x", ",", "y", "=", "self", ".", "d", ".", "scale", "*", "rawx", ",", "self", "....
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 sc...
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 sc...
[ "def", "_take_screenshot", "(", "self", ",", "screenshot", "=", "False", ",", "name_prefix", "=", "'unknown'", ")", ":", "if", "isinstance", "(", "screenshot", ",", "bool", ")", ":", "if", "not", "screenshot", ":", "return", "return", "self", ".", "_save_s...
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 ...
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 ...
[ "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...
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 (in...
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 (in...
[ "def", "plot_chain", "(", "chain", ",", "joints", ",", "ax", ",", "target", "=", "None", ",", "show", "=", "False", ")", ":", "# LIst of nodes and orientations", "nodes", "=", "[", "]", "axes", "=", "[", "]", "transformation_matrixes", "=", "chain", ".", ...
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", ")", "]", ",", "[", ...
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", ")", ",", ...
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",...
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", "]", ",", "[", "-", ...
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(d...
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(d...
[ "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", "==", ...
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 hom...
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 hom...
[ "def", "cartesian_to_homogeneous_vectors", "(", "cartesian_vector", ",", "matrix_type", "=", "\"numpy\"", ")", ":", "dimension_x", "=", "cartesian_vector", ".", "shape", "[", "0", "]", "# Vector", "if", "matrix_type", "==", "\"numpy\"", ":", "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 automa...
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 automa...
[ "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_joi...
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 automati...
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 automati...
[ "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 p...
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 beg...
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 beg...
[ "def", "get_urdf_parameters", "(", "urdf_file", ",", "base_elements", "=", "None", ",", "last_link_vector", "=", "None", ",", "base_element_type", "=", "\"link\"", ")", ":", "tree", "=", "ET", ".", "parse", "(", "urdf_file", ")", "root", "=", "tree", ".", ...
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_ele...
[ "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...
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...
[ "def", "_convert_angle_limit", "(", "angle", ",", "joint", ",", "*", "*", "kwargs", ")", ":", "angle_pypot", "=", "angle", "# No need to take care of orientation", "if", "joint", "[", "\"orientation\"", "]", "==", "\"indirect\"", ":", "angle_pypot", "=", "1", "*...
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 k...
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 k...
[ "def", "inverse_kinematic_optimization", "(", "chain", ",", "target_frame", ",", "starting_nodes_angles", ",", "regularization_parameter", "=", "None", ",", "max_iter", "=", "None", ")", ":", "# Only get the position", "target", "=", "target_frame", "[", ":", "3", "...
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 yo...
[ "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 ...
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 ...
[ "def", "forward_kinematics", "(", "self", ",", "joints", ",", "full_kinematics", "=", "False", ")", ":", "frame_matrix", "=", "np", ".", "eye", "(", "4", ")", "if", "full_kinematics", ":", "frame_matrixes", "=", "[", "]", "if", "len", "(", "self", ".", ...
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 Ret...
[ "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 initi...
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 initi...
[ "def", "inverse_kinematics", "(", "self", ",", "target", ",", "initial_position", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Checks on input", "target", "=", "np", ".", "array", "(", "target", ")", "if", "target", ".", "shape", "!=", "(", "4", ...
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...
[ "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 optio...
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 optio...
[ "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", ".", ...
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. Defau...
[ "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 s...
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 s...
[ "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", "...
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. ...
[ "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 con...
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 con...
[ "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 of...
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 conti...
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 conti...
[ "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", "(", "\"...
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 fa...
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 fa...
[ "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...
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 u...
[ "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", "...
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 ap...
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 ap...
[ "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...
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 broad...
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 broad...
[ "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", "+=", "'...
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, ...
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, ...
[ "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", "(", "...
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_interfa...
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_l...
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_l...
[ "def", "make_bitransformer", "(", "input_vocab_size", "=", "gin", ".", "REQUIRED", ",", "output_vocab_size", "=", "gin", ".", "REQUIRED", ",", "layout", "=", "None", ",", "mesh_shape", "=", "None", ")", ":", "with", "gin", ".", "config_scope", "(", "\"encode...
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.SelfAttentio...
[ "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...
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: ...
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: ...
[ "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", ",", "outp...
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 ...
[ "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(operat...
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(operat...
[ "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(op...
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(op...
[ "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....
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....
[ "def", "get_tensor_shape", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "mtf", ".", "Tensor", ")", ":", "return", "tf", ".", "TensorShape", "(", ...
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. ...
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. ...
[ "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 divisibl...
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 di...
[ "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 ...
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 ...
[ "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_...
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 ...
[ "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_nam...
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_nam...
[ "def", "get_tensor_device", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "tf", ".", "Tensor", ")", ":", "return", "tensor", ".", "device", "else",...
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._na...
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._na...
[ "def", "get_operation_device", "(", "self", ",", "operation_name", ")", ":", "operation", "=", "self", ".", "_name_to_operation", "(", "operation_name", ")", "if", "isinstance", "(", "operation", ",", "tf", ".", "Operation", ")", ":", "return", "operation", "....
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) ...
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) ...
[ "def", "get_tensor_mtf_dimension_names", "(", "self", ",", "tensor_name", ")", ":", "tensor", "=", "self", ".", "_name_to_tensor", "(", "tensor_name", ")", "if", "isinstance", "(", "tensor", ",", "mtf", ".", "Tensor", ")", ":", "return", "tensor", ".", "shap...
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...
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...
[ "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", ".", ...
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 t...
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 t...
[ "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...
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...
[ "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", "(", ")"...
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 ...
[ "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 poin...
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 poin...
[ "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", ...
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...
[ "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._g...
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._g...
[ "def", "_initialize_operations", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_graph", ",", "tf", ".", "Graph", ")", ":", "return", "self", ".", "_graph", ".", "get_operations", "(", ")", "elif", "isinstance", "(", "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 ...
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 ...
[ "def", "_initialize_operation_name_to_id", "(", "self", ")", ":", "operation_name_to_id", "=", "{", "}", "for", "i", ",", "operation", "in", "enumerate", "(", "self", ".", "_operations", ")", ":", "operation_name_to_id", "[", "operation", ".", "name", "]", "="...
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 enum...
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 enum...
[ "def", "_initialize_tensor_name_to_ids", "(", "self", ")", ":", "tensor_name_to_ids", "=", "{", "}", "for", "i", ",", "operation", "in", "enumerate", "(", "self", ".", "_operations", ")", ":", "for", "j", ",", "tensor", "in", "enumerate", "(", "operation", ...
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) ...
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) ...
[ "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...
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. ""...
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. ""...
[ "def", "layer_norm", "(", "x", ",", "dim", ",", "epsilon", "=", "1e-6", ",", "name", "=", "\"layer_prepostprocess\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", "+", "\"/layer_norm\"", ")", ":", "scale", "=", "mtf", ".", "get_variable", ...
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...
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...
[ "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...
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 th...
[ "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.sh...
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.sh...
[ "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\"", "%", "(", "logit...
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. ...
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. ...
[ "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 m...
[ "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)...
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)...
[ "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_...
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)]: # s...
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)]: # s...
[ "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"...
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, ...
python
def local_2d_self_attention_spatial_blocks(query_antecedent, kv_channels, heads, memory_h_dim=None, memory_w_dim=None, ...
[ "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", ",", ...
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_...
[ "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, s...
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, s...
[ "def", "multihead_attention_vars", "(", "mesh", ",", "heads", ",", "io_channels", ",", "kv_channels", ",", "master_dtype", ",", "slice_dtype", ",", "activation_dtype", ")", ":", "return", "multihead_attention_params", "(", "mesh", ",", "heads", ",", "io_channels", ...
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 creat...
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 creat...
[ "def", "multihead_attention_params", "(", "mesh", ",", "heads", ",", "io_channels", ",", "kv_channels", ",", "variable_dtype", ",", "combine", "=", "False", ")", ":", "qkvo", "=", "mtf", ".", "Dimension", "(", "\"qkvo\"", ",", "4", ")", "qk_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 ...
[ "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...
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...
[ "def", "attention_mask_ignore_padding", "(", "inputs", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "inputs", "=", "rename_length_to_memory_length", "(", "inputs", ")", "return", "mtf", ".", "cast", "(", "mtf", ".", "equal", "(", "inputs", ",", "0", ...
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...
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...
[ "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", ",...
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.d...
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.d...
[ "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", "...
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: ...
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: ...
[ "def", "multiplicative_jitter", "(", "x", ",", "epsilon", "=", "1e-2", ")", ":", "if", "epsilon", "==", "0", ":", "return", "x", "return", "x", "*", "mtf", ".", "random_uniform", "(", "x", ".", "mesh", ",", "x", ".", "shape", ",", "minval", "=", "1...
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, ...
python
def multihead_self_attention_memory_compressed(x, mask_right, compression_factor, kv_channels, heads, ...
[ "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", "...
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 ...
[ "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_...
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_...
[ "def", "compress_mean", "(", "x", ",", "dim", ",", "compression_factor", ")", ":", "dims", "=", "x", ".", "shape", ".", "dims", "pos", "=", "dims", ".", "index", "(", "dim", ")", "compressed_dim", "=", "mtf", ".", "Dimension", "(", "dim", ".", "name"...
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_d...
Embedding layer.
[ "Embedding", "layer", "." ]
3921196e5e43302e820da0a87329f25d7e2a3016
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L1146-L1150