body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
c1433d6dbcb4bc1e4bff9b994a2d07e1aa87990bbb5822ffe6838a201e45a8e5
@task def ngrok(c): '\n Open the local web server with Ngrok\n ' subprocess.run('ngrok http -host-header=local.starfleet.app local.starfleet.app:443', shell=True)
Open the local web server with Ngrok
tasks.py
ngrok
jolicode/starfleet
19
python
@task def ngrok(c): '\n \n ' subprocess.run('ngrok http -host-header=local.starfleet.app local.starfleet.app:443', shell=True)
@task def ngrok(c): '\n \n ' subprocess.run('ngrok http -host-header=local.starfleet.app local.starfleet.app:443', shell=True)<|docstring|>Open the local web server with Ngrok<|endoftext|>
77763ae9ed3fbdb5450a0206fc050d1d42cdaadf3849aa60dad78b15d254dfa8
@task def webpack_watch(c): '\n Compile and watch CSS and JS files for dev env\n ' with Builder(c): docker_compose_run(c, 'yarn run watch')
Compile and watch CSS and JS files for dev env
tasks.py
webpack_watch
jolicode/starfleet
19
python
@task def webpack_watch(c): '\n \n ' with Builder(c): docker_compose_run(c, 'yarn run watch')
@task def webpack_watch(c): '\n \n ' with Builder(c): docker_compose_run(c, 'yarn run watch')<|docstring|>Compile and watch CSS and JS files for dev env<|endoftext|>
d572ff8e3907c92cc258816b18f3203db766571717ce8621ee2b6f52aabf7930
@task def webpack(c): '\n Compile CSS and JS files for dev env\n ' with Builder(c): docker_compose_run(c, 'yarn run dev')
Compile CSS and JS files for dev env
tasks.py
webpack
jolicode/starfleet
19
python
@task def webpack(c): '\n \n ' with Builder(c): docker_compose_run(c, 'yarn run dev')
@task def webpack(c): '\n \n ' with Builder(c): docker_compose_run(c, 'yarn run dev')<|docstring|>Compile CSS and JS files for dev env<|endoftext|>
6203f6b10b270da0ab73cbf18ca66c764cea98e8eb61d65b0336026f3b07607a
@task def builder(c, user='app'): '\n Open a shell (bash) into a builder container\n ' with Builder(c): docker_compose_run(c, 'bash', user=user)
Open a shell (bash) into a builder container
tasks.py
builder
jolicode/starfleet
19
python
@task def builder(c, user='app'): '\n \n ' with Builder(c): docker_compose_run(c, 'bash', user=user)
@task def builder(c, user='app'): '\n \n ' with Builder(c): docker_compose_run(c, 'bash', user=user)<|docstring|>Open a shell (bash) into a builder container<|endoftext|>
860ae2c2faec9a2b48ecb2ae3dca1d382b423670a4652995a1fa69169a85fb9b
@task def logs(c): '\n Display infrastructure logs\n ' docker_compose(c, 'logs -f --tail=150')
Display infrastructure logs
tasks.py
logs
jolicode/starfleet
19
python
@task def logs(c): '\n \n ' docker_compose(c, 'logs -f --tail=150')
@task def logs(c): '\n \n ' docker_compose(c, 'logs -f --tail=150')<|docstring|>Display infrastructure logs<|endoftext|>
8114bd9c33017e2e499cadc790576e5a860affdb4afe327eb282ef352f98873d
@task def ps(c): '\n List containers status\n ' docker_compose(c, 'ps --all')
List containers status
tasks.py
ps
jolicode/starfleet
19
python
@task def ps(c): '\n \n ' docker_compose(c, 'ps --all')
@task def ps(c): '\n \n ' docker_compose(c, 'ps --all')<|docstring|>List containers status<|endoftext|>
bfb902f76cb9d215676a598ceec05bc7c5b0ba9a1821ae0a070f8e271d4a78f1
@task def stop(c): '\n Stop the infrastructure\n ' docker_compose(c, 'stop')
Stop the infrastructure
tasks.py
stop
jolicode/starfleet
19
python
@task def stop(c): '\n \n ' docker_compose(c, 'stop')
@task def stop(c): '\n \n ' docker_compose(c, 'stop')<|docstring|>Stop the infrastructure<|endoftext|>
df41852765d8c605a7ba752db59c321b8693446a180d38260b2e6d6469fcd06b
@task def start_workers(c): '\n Start the workers\n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = True c.run(('docker update --restart=unless-stopped %s' % ' '.join(workers)), hide='both') docker_compose(c, 'up --remove-orphans --detach')
Start the workers
tasks.py
start_workers
jolicode/starfleet
19
python
@task def start_workers(c): '\n \n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = True c.run(('docker update --restart=unless-stopped %s' % ' '.join(workers)), hide='both') docker_compose(c, 'up --remove-orphans --detach')
@task def start_workers(c): '\n \n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = True c.run(('docker update --restart=unless-stopped %s' % ' '.join(workers)), hide='both') docker_compose(c, 'up --remove-orphans --detach')<|docstring|>Start the workers<|endoftext|>
45f5cf47dd9f9ae52360da4679c350b7f5a80e723e5f5d9297869617f93e874f
@task def stop_workers(c): '\n Stop the workers\n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = False c.run(('docker update --restart=no %s' % ' '.join(workers)), hide='both') c.run(('docker stop %s' % ' '.join(workers)), hide='both')
Stop the workers
tasks.py
stop_workers
jolicode/starfleet
19
python
@task def stop_workers(c): '\n \n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = False c.run(('docker update --restart=no %s' % ' '.join(workers)), hide='both') c.run(('docker stop %s' % ' '.join(workers)), hide='both')
@task def stop_workers(c): '\n \n ' workers = get_workers(c) if (len(workers) == 0): return c.start_workers = False c.run(('docker update --restart=no %s' % ' '.join(workers)), hide='both') c.run(('docker stop %s' % ' '.join(workers)), hide='both')<|docstring|>Stop the workers<|endoftext|>
2f5623a9f2a10a2e3507db418234ff8a6f1d23b80407d34841fcf14bfacb3f4d
@task def destroy(c, force=False): '\n Clean the infrastructure (remove container, volume, networks)\n ' if (not force): ok = confirm_choice('Are you sure? This will permanently remove all containers, volumes, networks... created for this project.') if (not ok): return with Builder(c): docker_compose(c, 'down --remove-orphans --volumes --rmi=local')
Clean the infrastructure (remove container, volume, networks)
tasks.py
destroy
jolicode/starfleet
19
python
@task def destroy(c, force=False): '\n \n ' if (not force): ok = confirm_choice('Are you sure? This will permanently remove all containers, volumes, networks... created for this project.') if (not ok): return with Builder(c): docker_compose(c, 'down --remove-orphans --volumes --rmi=local')
@task def destroy(c, force=False): '\n \n ' if (not force): ok = confirm_choice('Are you sure? This will permanently remove all containers, volumes, networks... created for this project.') if (not ok): return with Builder(c): docker_compose(c, 'down --remove-orphans --volumes --rmi=local')<|docstring|>Clean the infrastructure (remove container, volume, networks)<|endoftext|>
6ef9debec7d9b030dae0ccabdf51cca67bb5e408dc717d3710d2d473ee58c9fd
@task(default=True) def help(c): '\n Display some help and available urls for the current project\n ' print((((('Run ' + Fore.GREEN) + 'inv help') + Fore.RESET) + ' to display this help.')) print('') print((((('Run ' + Fore.GREEN) + 'inv --help') + Fore.RESET) + ' to display invoke help.')) print('') print((((('Run ' + Fore.GREEN) + 'inv -l') + Fore.RESET) + ' to list all the available tasks.')) c.run('pipenv run inv --list') print(((Fore.GREEN + 'Available URLs for this project:') + Fore.RESET)) for domain in ([c.root_domain] + c.extra_domains): print((((('* ' + Fore.YELLOW) + 'https://') + domain) + Fore.RESET)) print(((((('* ' + Fore.YELLOW) + 'https://') + domain) + '/admin with [email protected]/password') + Fore.RESET)) try: response = json.loads(requests.get(('http://%s:8080/api/http/routers' % c.root_domain)).text) gen = (router for router in response if re.match(('^%s-(.*)@docker$' % c.project_name), router['name'])) for router in gen: if (router['service'] != ('frontend-%s' % c.project_name)): host = re.search('Host\\(\\`(?P<host>.*)\\`\\)', router['rule']).group('host') if host: scheme = ('https' if ('https' in router['using']) else router['using'][0]) print(((((('* ' + Fore.YELLOW) + scheme) + '://') + host) + Fore.RESET)) print('') except: pass
Display some help and available urls for the current project
tasks.py
help
jolicode/starfleet
19
python
@task(default=True) def help(c): '\n \n ' print((((('Run ' + Fore.GREEN) + 'inv help') + Fore.RESET) + ' to display this help.')) print() print((((('Run ' + Fore.GREEN) + 'inv --help') + Fore.RESET) + ' to display invoke help.')) print() print((((('Run ' + Fore.GREEN) + 'inv -l') + Fore.RESET) + ' to list all the available tasks.')) c.run('pipenv run inv --list') print(((Fore.GREEN + 'Available URLs for this project:') + Fore.RESET)) for domain in ([c.root_domain] + c.extra_domains): print((((('* ' + Fore.YELLOW) + 'https://') + domain) + Fore.RESET)) print(((((('* ' + Fore.YELLOW) + 'https://') + domain) + '/admin with [email protected]/password') + Fore.RESET)) try: response = json.loads(requests.get(('http://%s:8080/api/http/routers' % c.root_domain)).text) gen = (router for router in response if re.match(('^%s-(.*)@docker$' % c.project_name), router['name'])) for router in gen: if (router['service'] != ('frontend-%s' % c.project_name)): host = re.search('Host\\(\\`(?P<host>.*)\\`\\)', router['rule']).group('host') if host: scheme = ('https' if ('https' in router['using']) else router['using'][0]) print(((((('* ' + Fore.YELLOW) + scheme) + '://') + host) + Fore.RESET)) print() except: pass
@task(default=True) def help(c): '\n \n ' print((((('Run ' + Fore.GREEN) + 'inv help') + Fore.RESET) + ' to display this help.')) print() print((((('Run ' + Fore.GREEN) + 'inv --help') + Fore.RESET) + ' to display invoke help.')) print() print((((('Run ' + Fore.GREEN) + 'inv -l') + Fore.RESET) + ' to list all the available tasks.')) c.run('pipenv run inv --list') print(((Fore.GREEN + 'Available URLs for this project:') + Fore.RESET)) for domain in ([c.root_domain] + c.extra_domains): print((((('* ' + Fore.YELLOW) + 'https://') + domain) + Fore.RESET)) print(((((('* ' + Fore.YELLOW) + 'https://') + domain) + '/admin with [email protected]/password') + Fore.RESET)) try: response = json.loads(requests.get(('http://%s:8080/api/http/routers' % c.root_domain)).text) gen = (router for router in response if re.match(('^%s-(.*)@docker$' % c.project_name), router['name'])) for router in gen: if (router['service'] != ('frontend-%s' % c.project_name)): host = re.search('Host\\(\\`(?P<host>.*)\\`\\)', router['rule']).group('host') if host: scheme = ('https' if ('https' in router['using']) else router['using'][0]) print(((((('* ' + Fore.YELLOW) + scheme) + '://') + host) + Fore.RESET)) print() except: pass<|docstring|>Display some help and available urls for the current project<|endoftext|>
20e90349ee073a974b0ad0a716f3dead80f4b3ae388b6967bd885ea37ec07392
@task def generate_certificates(c): '\n Generates the cert.pem and cert-key.pem files\n ' with c.cd((c.project_directory + '/infrastructure/docker/services/router/etc/ssl/certs/')): c.run('mkcert -cert-file cert.pem -key-file key.pem "*.starfleet.app"')
Generates the cert.pem and cert-key.pem files
tasks.py
generate_certificates
jolicode/starfleet
19
python
@task def generate_certificates(c): '\n \n ' with c.cd((c.project_directory + '/infrastructure/docker/services/router/etc/ssl/certs/')): c.run('mkcert -cert-file cert.pem -key-file key.pem "*.starfleet.app"')
@task def generate_certificates(c): '\n \n ' with c.cd((c.project_directory + '/infrastructure/docker/services/router/etc/ssl/certs/')): c.run('mkcert -cert-file cert.pem -key-file key.pem "*.starfleet.app"')<|docstring|>Generates the cert.pem and cert-key.pem files<|endoftext|>
caeb1d2cb7654d462c5cf23e3e47abb562c472b9a1732e8519230fef7327ed52
def run_in_docker_or_locally_for_dinghy(c, command, no_deps=False): '\n Mac users have a lot of problems running Yarn / Webpack on the Docker stack so this func allow them to run these tools on their host\n ' if c.dinghy: with c.cd(c.project_directory): c.run(command) else: docker_compose_run(c, command, no_deps=no_deps)
Mac users have a lot of problems running Yarn / Webpack on the Docker stack so this func allow them to run these tools on their host
tasks.py
run_in_docker_or_locally_for_dinghy
jolicode/starfleet
19
python
def run_in_docker_or_locally_for_dinghy(c, command, no_deps=False): '\n \n ' if c.dinghy: with c.cd(c.project_directory): c.run(command) else: docker_compose_run(c, command, no_deps=no_deps)
def run_in_docker_or_locally_for_dinghy(c, command, no_deps=False): '\n \n ' if c.dinghy: with c.cd(c.project_directory): c.run(command) else: docker_compose_run(c, command, no_deps=no_deps)<|docstring|>Mac users have a lot of problems running Yarn / Webpack on the Docker stack so this func allow them to run these tools on their host<|endoftext|>
198eba22cb7138ec47700a5283c1fc0026b6c9030a93dd6c226d8c89f092a909
def get_workers(c): '\n Find worker containers for the current project\n ' cmd = c.run(('docker ps -a --filter "label=docker-starter.worker.%s" --quiet' % c.project_name), hide='both') return list(filter(None, cmd.stdout.rsplit('\n')))
Find worker containers for the current project
tasks.py
get_workers
jolicode/starfleet
19
python
def get_workers(c): '\n \n ' cmd = c.run(('docker ps -a --filter "label=docker-starter.worker.%s" --quiet' % c.project_name), hide='both') return list(filter(None, cmd.stdout.rsplit('\n')))
def get_workers(c): '\n \n ' cmd = c.run(('docker ps -a --filter "label=docker-starter.worker.%s" --quiet' % c.project_name), hide='both') return list(filter(None, cmd.stdout.rsplit('\n')))<|docstring|>Find worker containers for the current project<|endoftext|>
f6b6e67bad1d79f129cf00244d73a2c3229822ba1facf0d8a5373db7d0c05406
def add_metric_obj(self, metric_obj): "Add a metric to the check's performance data from an existing Metric object" self.metrics.append(metric_obj)
Add a metric to the check's performance data from an existing Metric object
plugnpy/check.py
add_metric_obj
opsview/plugnpy
1
python
def add_metric_obj(self, metric_obj): self.metrics.append(metric_obj)
def add_metric_obj(self, metric_obj): self.metrics.append(metric_obj)<|docstring|>Add a metric to the check's performance data from an existing Metric object<|endoftext|>
3fb0a3b1e8d41f2e4f4f8b1999f254e5c4f35a6d4b4adc9fc8636da2b45038e3
def add_metric(self, name, value, unit='', warning_threshold=None, critical_threshold=None, display_format='{name} is {value}{unit}', display_in_perf=True, display_in_summary=True, display_name=None, convert_metric=None, si_bytes_conversion=False, summary_precision=2, perf_data_precision=2, message=''): 'Add a metric to the check\'s performance data.\n\n Keyword Arguments:\n - name -- Name of the Metric\n - value -- Value of the Metric (note: do not include unit of measure)\n - unit -- Unit of Measure of the Metric\n - warning_threshold -- Warning threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - critical_threshold -- Critical threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - display_format -- Formatting string to print the Metric (default: "{name} is {value} {unit}")\n - display_name -- Name to be used in friendly output (default: value of name)\n - display_in_summary -- Whether to print the metric in the summary (default: True)\n - display_in_perf -- Whether to print the metric in performance data (default: True)\n - convert_metric -- Whether to convert the metric value to a more human friendly unit (default: False)\n - si_bytes_conversion -- Whether to convert values using the SI standard, uses IEC by default (default: False)\n - summary_precision -- The number of decimal places to round the metric value in the summary to (default 2)\n - per_data_precision -- The number of decimal places to round the metric value in the perf data to (default 2)\n - message -- Alternative message to print\n ' metric = Metric(name, value, unit, warning_threshold, critical_threshold, display_format=display_format, display_in_perf=display_in_perf, display_in_summary=display_in_summary, display_name=display_name, convert_metric=convert_metric, si_bytes_conversion=si_bytes_conversion, summary_precision=summary_precision, perf_data_precision=perf_data_precision, message=message) self.metrics.append(metric)
Add a metric to the check's performance data. Keyword Arguments: - name -- Name of the Metric - value -- Value of the Metric (note: do not include unit of measure) - unit -- Unit of Measure of the Metric - warning_threshold -- Warning threshold for the Metric (default: '') - see Monitoring Plugins Development Guidelines - critical_threshold -- Critical threshold for the Metric (default: '') - see Monitoring Plugins Development Guidelines - display_format -- Formatting string to print the Metric (default: "{name} is {value} {unit}") - display_name -- Name to be used in friendly output (default: value of name) - display_in_summary -- Whether to print the metric in the summary (default: True) - display_in_perf -- Whether to print the metric in performance data (default: True) - convert_metric -- Whether to convert the metric value to a more human friendly unit (default: False) - si_bytes_conversion -- Whether to convert values using the SI standard, uses IEC by default (default: False) - summary_precision -- The number of decimal places to round the metric value in the summary to (default 2) - per_data_precision -- The number of decimal places to round the metric value in the perf data to (default 2) - message -- Alternative message to print
plugnpy/check.py
add_metric
opsview/plugnpy
1
python
def add_metric(self, name, value, unit=, warning_threshold=None, critical_threshold=None, display_format='{name} is {value}{unit}', display_in_perf=True, display_in_summary=True, display_name=None, convert_metric=None, si_bytes_conversion=False, summary_precision=2, perf_data_precision=2, message=): 'Add a metric to the check\'s performance data.\n\n Keyword Arguments:\n - name -- Name of the Metric\n - value -- Value of the Metric (note: do not include unit of measure)\n - unit -- Unit of Measure of the Metric\n - warning_threshold -- Warning threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - critical_threshold -- Critical threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - display_format -- Formatting string to print the Metric (default: "{name} is {value} {unit}")\n - display_name -- Name to be used in friendly output (default: value of name)\n - display_in_summary -- Whether to print the metric in the summary (default: True)\n - display_in_perf -- Whether to print the metric in performance data (default: True)\n - convert_metric -- Whether to convert the metric value to a more human friendly unit (default: False)\n - si_bytes_conversion -- Whether to convert values using the SI standard, uses IEC by default (default: False)\n - summary_precision -- The number of decimal places to round the metric value in the summary to (default 2)\n - per_data_precision -- The number of decimal places to round the metric value in the perf data to (default 2)\n - message -- Alternative message to print\n ' metric = Metric(name, value, unit, warning_threshold, critical_threshold, display_format=display_format, display_in_perf=display_in_perf, display_in_summary=display_in_summary, display_name=display_name, convert_metric=convert_metric, si_bytes_conversion=si_bytes_conversion, summary_precision=summary_precision, perf_data_precision=perf_data_precision, message=message) self.metrics.append(metric)
def add_metric(self, name, value, unit=, warning_threshold=None, critical_threshold=None, display_format='{name} is {value}{unit}', display_in_perf=True, display_in_summary=True, display_name=None, convert_metric=None, si_bytes_conversion=False, summary_precision=2, perf_data_precision=2, message=): 'Add a metric to the check\'s performance data.\n\n Keyword Arguments:\n - name -- Name of the Metric\n - value -- Value of the Metric (note: do not include unit of measure)\n - unit -- Unit of Measure of the Metric\n - warning_threshold -- Warning threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - critical_threshold -- Critical threshold for the Metric (default: \'\')\n - see Monitoring Plugins Development Guidelines\n - display_format -- Formatting string to print the Metric (default: "{name} is {value} {unit}")\n - display_name -- Name to be used in friendly output (default: value of name)\n - display_in_summary -- Whether to print the metric in the summary (default: True)\n - display_in_perf -- Whether to print the metric in performance data (default: True)\n - convert_metric -- Whether to convert the metric value to a more human friendly unit (default: False)\n - si_bytes_conversion -- Whether to convert values using the SI standard, uses IEC by default (default: False)\n - summary_precision -- The number of decimal places to round the metric value in the summary to (default 2)\n - per_data_precision -- The number of decimal places to round the metric value in the perf data to (default 2)\n - message -- Alternative message to print\n ' metric = Metric(name, value, unit, warning_threshold, critical_threshold, display_format=display_format, display_in_perf=display_in_perf, display_in_summary=display_in_summary, display_name=display_name, convert_metric=convert_metric, si_bytes_conversion=si_bytes_conversion, summary_precision=summary_precision, perf_data_precision=perf_data_precision, message=message) self.metrics.append(metric)<|docstring|>Add a metric to the check's performance data. Keyword Arguments: - name -- Name of the Metric - value -- Value of the Metric (note: do not include unit of measure) - unit -- Unit of Measure of the Metric - warning_threshold -- Warning threshold for the Metric (default: '') - see Monitoring Plugins Development Guidelines - critical_threshold -- Critical threshold for the Metric (default: '') - see Monitoring Plugins Development Guidelines - display_format -- Formatting string to print the Metric (default: "{name} is {value} {unit}") - display_name -- Name to be used in friendly output (default: value of name) - display_in_summary -- Whether to print the metric in the summary (default: True) - display_in_perf -- Whether to print the metric in performance data (default: True) - convert_metric -- Whether to convert the metric value to a more human friendly unit (default: False) - si_bytes_conversion -- Whether to convert values using the SI standard, uses IEC by default (default: False) - summary_precision -- The number of decimal places to round the metric value in the summary to (default 2) - per_data_precision -- The number of decimal places to round the metric value in the perf data to (default 2) - message -- Alternative message to print<|endoftext|>
f827919a0ac94b02101af1b980c4c4e7533a39e178a238f752515dc47888c1b4
def add_message(self, message): 'Add a message' self.metrics[(- 1)].message = message
Add a message
plugnpy/check.py
add_message
opsview/plugnpy
1
python
def add_message(self, message): self.metrics[(- 1)].message = message
def add_message(self, message): self.metrics[(- 1)].message = message<|docstring|>Add a message<|endoftext|>
31424e3ab30f174e5c3307efe306224beece3938b2bb69bbb05d21e20443dc8c
def exit(self, code, message): 'Exits with specified message and specified exit status.\n Note: existing messages and metrics are discarded.\n ' print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[code], message)) sys.exit(code)
Exits with specified message and specified exit status. Note: existing messages and metrics are discarded.
plugnpy/check.py
exit
opsview/plugnpy
1
python
def exit(self, code, message): 'Exits with specified message and specified exit status.\n Note: existing messages and metrics are discarded.\n ' print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[code], message)) sys.exit(code)
def exit(self, code, message): 'Exits with specified message and specified exit status.\n Note: existing messages and metrics are discarded.\n ' print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[code], message)) sys.exit(code)<|docstring|>Exits with specified message and specified exit status. Note: existing messages and metrics are discarded.<|endoftext|>
361f410bb0ceb2b31e1b7ce5e4f35d5f316591e17e95b32ae1de7a3fa2966a88
def exit_ok(self, message): 'Exits with specified message and OK exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(0, message)
Exits with specified message and OK exit status. Note: existing messages and metrics are discarded.
plugnpy/check.py
exit_ok
opsview/plugnpy
1
python
def exit_ok(self, message): 'Exits with specified message and OK exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(0, message)
def exit_ok(self, message): 'Exits with specified message and OK exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(0, message)<|docstring|>Exits with specified message and OK exit status. Note: existing messages and metrics are discarded.<|endoftext|>
135f04462de6a389199d963945ecb9efa3dcdcf377bc8cdd1463c5c0b6610d5b
def exit_warning(self, message): 'Exits with specified message and WARNING exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(1, message)
Exits with specified message and WARNING exit status. Note: existing messages and metrics are discarded.
plugnpy/check.py
exit_warning
opsview/plugnpy
1
python
def exit_warning(self, message): 'Exits with specified message and WARNING exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(1, message)
def exit_warning(self, message): 'Exits with specified message and WARNING exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(1, message)<|docstring|>Exits with specified message and WARNING exit status. Note: existing messages and metrics are discarded.<|endoftext|>
6f3bf2c6bcc0afd70f42b634e10cfc588771667c19b36815d4854f64d1a9249c
def exit_critical(self, message): 'Exits with specified message and CRITICAL exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(2, message)
Exits with specified message and CRITICAL exit status. Note: existing messages and metrics are discarded.
plugnpy/check.py
exit_critical
opsview/plugnpy
1
python
def exit_critical(self, message): 'Exits with specified message and CRITICAL exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(2, message)
def exit_critical(self, message): 'Exits with specified message and CRITICAL exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(2, message)<|docstring|>Exits with specified message and CRITICAL exit status. Note: existing messages and metrics are discarded.<|endoftext|>
0943ba9282dbfacdb39af97552146fecd2aabd169867a52f14a1d9fe8322e369
def exit_unknown(self, message): 'Exits with specified message and UNKNOWN exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(3, message)
Exits with specified message and UNKNOWN exit status. Note: existing messages and metrics are discarded.
plugnpy/check.py
exit_unknown
opsview/plugnpy
1
python
def exit_unknown(self, message): 'Exits with specified message and UNKNOWN exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(3, message)
def exit_unknown(self, message): 'Exits with specified message and UNKNOWN exit status.\n Note: existing messages and metrics are discarded.\n ' self.exit(3, message)<|docstring|>Exits with specified message and UNKNOWN exit status. Note: existing messages and metrics are discarded.<|endoftext|>
83b68d3209d383a7efafe9cabb592eb793cdf5e1afd05977a2ab7d609034ab52
def final(self): 'Calculates the final check output and exit status, prints and exits with the appropriate code.' human_results = [str(metric) for metric in self.metrics if metric.display_in_summary] perf_results = [metric.perf_data for metric in self.metrics if metric.display_in_perf] summary = '{0}{1}{2}'.format(self.sep.join(human_results), (' | ' if perf_results else ''), ' '.join(perf_results)) exit_code = max([metric.state for metric in self.metrics]) print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[exit_code], summary)) sys.exit(exit_code)
Calculates the final check output and exit status, prints and exits with the appropriate code.
plugnpy/check.py
final
opsview/plugnpy
1
python
def final(self): human_results = [str(metric) for metric in self.metrics if metric.display_in_summary] perf_results = [metric.perf_data for metric in self.metrics if metric.display_in_perf] summary = '{0}{1}{2}'.format(self.sep.join(human_results), (' | ' if perf_results else ), ' '.join(perf_results)) exit_code = max([metric.state for metric in self.metrics]) print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[exit_code], summary)) sys.exit(exit_code)
def final(self): human_results = [str(metric) for metric in self.metrics if metric.display_in_summary] perf_results = [metric.perf_data for metric in self.metrics if metric.display_in_perf] summary = '{0}{1}{2}'.format(self.sep.join(human_results), (' | ' if perf_results else ), ' '.join(perf_results)) exit_code = max([metric.state for metric in self.metrics]) print('{0} {1} - {2}'.format(self.state_type, Check.STATUS[exit_code], summary)) sys.exit(exit_code)<|docstring|>Calculates the final check output and exit status, prints and exits with the appropriate code.<|endoftext|>
e1080e52dac044e0c02c91a468e3f3e54949d0e1337f5f81502cf997e9957fe6
@classmethod def from_regions(cls, regions, **kwargs): '\n Initialize group from sequence of regions.\n ' regions = map(mundi.region, regions) new = EpidemicCurve.from_region return cls({r.id: new(r, **kwargs) for r in regions})
Initialize group from sequence of regions.
pydemic/empirical/epidemiology_group.py
from_regions
GCES-Pydemic/pydemic
0
python
@classmethod def from_regions(cls, regions, **kwargs): '\n \n ' regions = map(mundi.region, regions) new = EpidemicCurve.from_region return cls({r.id: new(r, **kwargs) for r in regions})
@classmethod def from_regions(cls, regions, **kwargs): '\n \n ' regions = map(mundi.region, regions) new = EpidemicCurve.from_region return cls({r.id: new(r, **kwargs) for r in regions})<|docstring|>Initialize group from sequence of regions.<|endoftext|>
4b415c9bbc73640effc96867c0797f5c80c007c089f1464e41f13d84a9842a86
@classmethod def from_query(cls, *args, disease=None, params=None, **kwargs): '\n Initialize group from a mundi region query.\n ' regions = mundi.regions(*args, **kwargs) return cls.from_regions(regions.index, disease=disease, params=params)
Initialize group from a mundi region query.
pydemic/empirical/epidemiology_group.py
from_query
GCES-Pydemic/pydemic
0
python
@classmethod def from_query(cls, *args, disease=None, params=None, **kwargs): '\n \n ' regions = mundi.regions(*args, **kwargs) return cls.from_regions(regions.index, disease=disease, params=params)
@classmethod def from_query(cls, *args, disease=None, params=None, **kwargs): '\n \n ' regions = mundi.regions(*args, **kwargs) return cls.from_regions(regions.index, disease=disease, params=params)<|docstring|>Initialize group from a mundi region query.<|endoftext|>
f8ab65dac0a3281315541fdd62da5135b72ae829efdd68bc4adfde0d2ae0b5fd
def experiment_fn(output_dir): "Creates an experiment using Alexnet applied to Oxford's 17 Category Flower Dataset.\n\n References:\n * Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet Classification with\n Deep Convolutional Neural Networks. NIPS, 2012.\n * 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman.\n\n Links:\n * [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) # noqa\n * [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)\n " plx.datasets.flowers17.prepare('../data/flowers17') config = './yaml_configs/alexnet_flower17.yml' config = './json_configs/alexnet_flower17.json' experiment_config = plx.configs.ExperimentConfig.read_configs(config) return plx.experiments.create_experiment(experiment_config)
Creates an experiment using Alexnet applied to Oxford's 17 Category Flower Dataset. References: * Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet Classification with Deep Convolutional Neural Networks. NIPS, 2012. * 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman. Links: * [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) # noqa * [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)
examples/configs_examples/alexnet_flowers17.py
experiment_fn
chandu088/p
0
python
def experiment_fn(output_dir): "Creates an experiment using Alexnet applied to Oxford's 17 Category Flower Dataset.\n\n References:\n * Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet Classification with\n Deep Convolutional Neural Networks. NIPS, 2012.\n * 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman.\n\n Links:\n * [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) # noqa\n * [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)\n " plx.datasets.flowers17.prepare('../data/flowers17') config = './yaml_configs/alexnet_flower17.yml' config = './json_configs/alexnet_flower17.json' experiment_config = plx.configs.ExperimentConfig.read_configs(config) return plx.experiments.create_experiment(experiment_config)
def experiment_fn(output_dir): "Creates an experiment using Alexnet applied to Oxford's 17 Category Flower Dataset.\n\n References:\n * Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet Classification with\n Deep Convolutional Neural Networks. NIPS, 2012.\n * 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman.\n\n Links:\n * [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) # noqa\n * [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)\n " plx.datasets.flowers17.prepare('../data/flowers17') config = './yaml_configs/alexnet_flower17.yml' config = './json_configs/alexnet_flower17.json' experiment_config = plx.configs.ExperimentConfig.read_configs(config) return plx.experiments.create_experiment(experiment_config)<|docstring|>Creates an experiment using Alexnet applied to Oxford's 17 Category Flower Dataset. References: * Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet Classification with Deep Convolutional Neural Networks. NIPS, 2012. * 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew Zisserman. Links: * [AlexNet Paper](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf) # noqa * [Flower Dataset (17)](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/)<|endoftext|>
39f05a8a88de11e5964a2d34eae3f5738f7418cedc58ec3cc8c7e8a0e74c8c53
def current_user(): '\n 从session中获取当前用户id, 在数据库中找出用户数据\n ' uid = session.get('user_id') if (uid is not None): u = User.query.get(uid) return u
从session中获取当前用户id, 在数据库中找出用户数据
routes/user.py
current_user
naturalwang/flask-blog
0
python
def current_user(): '\n \n ' uid = session.get('user_id') if (uid is not None): u = User.query.get(uid) return u
def current_user(): '\n \n ' uid = session.get('user_id') if (uid is not None): u = User.query.get(uid) return u<|docstring|>从session中获取当前用户id, 在数据库中找出用户数据<|endoftext|>
46abb388a2a5d551755195d76c6c2b8a958331771de2e8c3f61251b75b12829c
def _helper_reraises_exception(ex): 'Pickle-able helper function for use by _guarded_task_generation.' raise ex
Pickle-able helper function for use by _guarded_task_generation.
Lib/multiprocessing/pool.py
_helper_reraises_exception
tomKPZ/cpython
52,316
python
def _helper_reraises_exception(ex): raise ex
def _helper_reraises_exception(ex): raise ex<|docstring|>Pickle-able helper function for use by _guarded_task_generation.<|endoftext|>
c1941aea94eacfe6a68cbf43bd05fe0165fd6c33fbd022a006bc03af0dc3450a
@staticmethod def _join_exited_workers(pool): 'Cleanup after any worker processes which have exited due to reaching\n their specified lifetime. Returns True if any workers were cleaned up.\n ' cleaned = False for i in reversed(range(len(pool))): worker = pool[i] if (worker.exitcode is not None): util.debug(('cleaning up worker %d' % i)) worker.join() cleaned = True del pool[i] return cleaned
Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up.
Lib/multiprocessing/pool.py
_join_exited_workers
tomKPZ/cpython
52,316
python
@staticmethod def _join_exited_workers(pool): 'Cleanup after any worker processes which have exited due to reaching\n their specified lifetime. Returns True if any workers were cleaned up.\n ' cleaned = False for i in reversed(range(len(pool))): worker = pool[i] if (worker.exitcode is not None): util.debug(('cleaning up worker %d' % i)) worker.join() cleaned = True del pool[i] return cleaned
@staticmethod def _join_exited_workers(pool): 'Cleanup after any worker processes which have exited due to reaching\n their specified lifetime. Returns True if any workers were cleaned up.\n ' cleaned = False for i in reversed(range(len(pool))): worker = pool[i] if (worker.exitcode is not None): util.debug(('cleaning up worker %d' % i)) worker.join() cleaned = True del pool[i] return cleaned<|docstring|>Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up.<|endoftext|>
3ccfc2b8824e03899c620fed860967d8c37b26a4a733aaa71546c7f0e2b58130
@staticmethod def _repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): 'Bring the number of pool processes up to the specified number,\n for use after reaping workers which have exited.\n ' for i in range((processes - len(pool))): w = Process(ctx, target=worker, args=(inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() pool.append(w) util.debug('added worker')
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
Lib/multiprocessing/pool.py
_repopulate_pool_static
tomKPZ/cpython
52,316
python
@staticmethod def _repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): 'Bring the number of pool processes up to the specified number,\n for use after reaping workers which have exited.\n ' for i in range((processes - len(pool))): w = Process(ctx, target=worker, args=(inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() pool.append(w) util.debug('added worker')
@staticmethod def _repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): 'Bring the number of pool processes up to the specified number,\n for use after reaping workers which have exited.\n ' for i in range((processes - len(pool))): w = Process(ctx, target=worker, args=(inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() pool.append(w) util.debug('added worker')<|docstring|>Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.<|endoftext|>
3c64c42a4f5700cd49837af1a87d33f5bacfc45b80a2953d41f214e3b668e918
@staticmethod def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): 'Clean up any exited workers and start replacements for them.\n ' if Pool._join_exited_workers(pool): Pool._repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)
Clean up any exited workers and start replacements for them.
Lib/multiprocessing/pool.py
_maintain_pool
tomKPZ/cpython
52,316
python
@staticmethod def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): '\n ' if Pool._join_exited_workers(pool): Pool._repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)
@staticmethod def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception): '\n ' if Pool._join_exited_workers(pool): Pool._repopulate_pool_static(ctx, Process, processes, pool, inqueue, outqueue, initializer, initargs, maxtasksperchild, wrap_exception)<|docstring|>Clean up any exited workers and start replacements for them.<|endoftext|>
d3c8d548b828a913438cb4eed4b17a03dac8f65ae71d9447ec5c92b1e4bc759e
def apply(self, func, args=(), kwds={}): '\n Equivalent of `func(*args, **kwds)`.\n Pool must be running.\n ' return self.apply_async(func, args, kwds).get()
Equivalent of `func(*args, **kwds)`. Pool must be running.
Lib/multiprocessing/pool.py
apply
tomKPZ/cpython
52,316
python
def apply(self, func, args=(), kwds={}): '\n Equivalent of `func(*args, **kwds)`.\n Pool must be running.\n ' return self.apply_async(func, args, kwds).get()
def apply(self, func, args=(), kwds={}): '\n Equivalent of `func(*args, **kwds)`.\n Pool must be running.\n ' return self.apply_async(func, args, kwds).get()<|docstring|>Equivalent of `func(*args, **kwds)`. Pool must be running.<|endoftext|>
2fca1462109cbbe67b0285dbddb3fa4bead6046cdc3ea0017fc326f1dba6c6cc
def map(self, func, iterable, chunksize=None): '\n Apply `func` to each element in `iterable`, collecting the results\n in a list that is returned.\n ' return self._map_async(func, iterable, mapstar, chunksize).get()
Apply `func` to each element in `iterable`, collecting the results in a list that is returned.
Lib/multiprocessing/pool.py
map
tomKPZ/cpython
52,316
python
def map(self, func, iterable, chunksize=None): '\n Apply `func` to each element in `iterable`, collecting the results\n in a list that is returned.\n ' return self._map_async(func, iterable, mapstar, chunksize).get()
def map(self, func, iterable, chunksize=None): '\n Apply `func` to each element in `iterable`, collecting the results\n in a list that is returned.\n ' return self._map_async(func, iterable, mapstar, chunksize).get()<|docstring|>Apply `func` to each element in `iterable`, collecting the results in a list that is returned.<|endoftext|>
d39de38be68cca8f23a913dfb7ad89d8a80893d04cb0634854b1a2d115082ad9
def starmap(self, func, iterable, chunksize=None): '\n Like `map()` method but the elements of the `iterable` are expected to\n be iterables as well and will be unpacked as arguments. Hence\n `func` and (a, b) becomes func(a, b).\n ' return self._map_async(func, iterable, starmapstar, chunksize).get()
Like `map()` method but the elements of the `iterable` are expected to be iterables as well and will be unpacked as arguments. Hence `func` and (a, b) becomes func(a, b).
Lib/multiprocessing/pool.py
starmap
tomKPZ/cpython
52,316
python
def starmap(self, func, iterable, chunksize=None): '\n Like `map()` method but the elements of the `iterable` are expected to\n be iterables as well and will be unpacked as arguments. Hence\n `func` and (a, b) becomes func(a, b).\n ' return self._map_async(func, iterable, starmapstar, chunksize).get()
def starmap(self, func, iterable, chunksize=None): '\n Like `map()` method but the elements of the `iterable` are expected to\n be iterables as well and will be unpacked as arguments. Hence\n `func` and (a, b) becomes func(a, b).\n ' return self._map_async(func, iterable, starmapstar, chunksize).get()<|docstring|>Like `map()` method but the elements of the `iterable` are expected to be iterables as well and will be unpacked as arguments. Hence `func` and (a, b) becomes func(a, b).<|endoftext|>
1af3456263f4661a15285a9d7f19cc3abfa1a9d35a81d85788586f435acf9ee8
def starmap_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n Asynchronous version of `starmap()` method.\n ' return self._map_async(func, iterable, starmapstar, chunksize, callback, error_callback)
Asynchronous version of `starmap()` method.
Lib/multiprocessing/pool.py
starmap_async
tomKPZ/cpython
52,316
python
def starmap_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n \n ' return self._map_async(func, iterable, starmapstar, chunksize, callback, error_callback)
def starmap_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n \n ' return self._map_async(func, iterable, starmapstar, chunksize, callback, error_callback)<|docstring|>Asynchronous version of `starmap()` method.<|endoftext|>
b63c23cab800832b09fbb7f58b41f6870faef6133a688d344eac36925f6bf7cc
def _guarded_task_generation(self, result_job, func, iterable): 'Provides a generator of tasks for imap and imap_unordered with\n appropriate handling for iterables which throw exceptions during\n iteration.' try: i = (- 1) for (i, x) in enumerate(iterable): (yield (result_job, i, func, (x,), {})) except Exception as e: (yield (result_job, (i + 1), _helper_reraises_exception, (e,), {}))
Provides a generator of tasks for imap and imap_unordered with appropriate handling for iterables which throw exceptions during iteration.
Lib/multiprocessing/pool.py
_guarded_task_generation
tomKPZ/cpython
52,316
python
def _guarded_task_generation(self, result_job, func, iterable): 'Provides a generator of tasks for imap and imap_unordered with\n appropriate handling for iterables which throw exceptions during\n iteration.' try: i = (- 1) for (i, x) in enumerate(iterable): (yield (result_job, i, func, (x,), {})) except Exception as e: (yield (result_job, (i + 1), _helper_reraises_exception, (e,), {}))
def _guarded_task_generation(self, result_job, func, iterable): 'Provides a generator of tasks for imap and imap_unordered with\n appropriate handling for iterables which throw exceptions during\n iteration.' try: i = (- 1) for (i, x) in enumerate(iterable): (yield (result_job, i, func, (x,), {})) except Exception as e: (yield (result_job, (i + 1), _helper_reraises_exception, (e,), {}))<|docstring|>Provides a generator of tasks for imap and imap_unordered with appropriate handling for iterables which throw exceptions during iteration.<|endoftext|>
26271f09239e832c179e37d2f902bec80e9bad697aca25b8777c42daf74f4ea9
def imap(self, func, iterable, chunksize=1): '\n Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.\n ' self._check_running() if (chunksize == 1): result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0:n}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)
Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
Lib/multiprocessing/pool.py
imap
tomKPZ/cpython
52,316
python
def imap(self, func, iterable, chunksize=1): '\n \n ' self._check_running() if (chunksize == 1): result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0:n}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)
def imap(self, func, iterable, chunksize=1): '\n \n ' self._check_running() if (chunksize == 1): result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0:n}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)<|docstring|>Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.<|endoftext|>
1d9b168550abb8aa6191750ca23b099348860646594dd417162fff824b866fea
def imap_unordered(self, func, iterable, chunksize=1): '\n Like `imap()` method but ordering of results is arbitrary.\n ' self._check_running() if (chunksize == 1): result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0!r}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)
Like `imap()` method but ordering of results is arbitrary.
Lib/multiprocessing/pool.py
imap_unordered
tomKPZ/cpython
52,316
python
def imap_unordered(self, func, iterable, chunksize=1): '\n \n ' self._check_running() if (chunksize == 1): result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0!r}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)
def imap_unordered(self, func, iterable, chunksize=1): '\n \n ' self._check_running() if (chunksize == 1): result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, func, iterable), result._set_length)) return result else: if (chunksize < 1): raise ValueError('Chunksize must be 1+, not {0!r}'.format(chunksize)) task_batches = Pool._get_tasks(func, iterable, chunksize) result = IMapUnorderedIterator(self) self._taskqueue.put((self._guarded_task_generation(result._job, mapstar, task_batches), result._set_length)) return (item for chunk in result for item in chunk)<|docstring|>Like `imap()` method but ordering of results is arbitrary.<|endoftext|>
a30d8e2748b6834d95c746c1c4bdcb19fed201ffb7ed3c2738a8eabc9b0b783d
def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None): '\n Asynchronous version of `apply()` method.\n ' self._check_running() result = ApplyResult(self, callback, error_callback) self._taskqueue.put(([(result._job, 0, func, args, kwds)], None)) return result
Asynchronous version of `apply()` method.
Lib/multiprocessing/pool.py
apply_async
tomKPZ/cpython
52,316
python
def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None): '\n \n ' self._check_running() result = ApplyResult(self, callback, error_callback) self._taskqueue.put(([(result._job, 0, func, args, kwds)], None)) return result
def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None): '\n \n ' self._check_running() result = ApplyResult(self, callback, error_callback) self._taskqueue.put(([(result._job, 0, func, args, kwds)], None)) return result<|docstring|>Asynchronous version of `apply()` method.<|endoftext|>
3e14b0e8ad2dd7917ac1f5612f482ff90985bfa444e0fad8e23cd64877458b64
def map_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n Asynchronous version of `map()` method.\n ' return self._map_async(func, iterable, mapstar, chunksize, callback, error_callback)
Asynchronous version of `map()` method.
Lib/multiprocessing/pool.py
map_async
tomKPZ/cpython
52,316
python
def map_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n \n ' return self._map_async(func, iterable, mapstar, chunksize, callback, error_callback)
def map_async(self, func, iterable, chunksize=None, callback=None, error_callback=None): '\n \n ' return self._map_async(func, iterable, mapstar, chunksize, callback, error_callback)<|docstring|>Asynchronous version of `map()` method.<|endoftext|>
88ebbf9f5183b9df6da970267162d50122f7ec0cc7f44d9fb07fe4390cc1b127
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, error_callback=None): '\n Helper function to implement map, starmap and their async counterparts.\n ' self._check_running() if (not hasattr(iterable, '__len__')): iterable = list(iterable) if (chunksize is None): (chunksize, extra) = divmod(len(iterable), (len(self._pool) * 4)) if extra: chunksize += 1 if (len(iterable) == 0): chunksize = 0 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self, chunksize, len(iterable), callback, error_callback=error_callback) self._taskqueue.put((self._guarded_task_generation(result._job, mapper, task_batches), None)) return result
Helper function to implement map, starmap and their async counterparts.
Lib/multiprocessing/pool.py
_map_async
tomKPZ/cpython
52,316
python
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, error_callback=None): '\n \n ' self._check_running() if (not hasattr(iterable, '__len__')): iterable = list(iterable) if (chunksize is None): (chunksize, extra) = divmod(len(iterable), (len(self._pool) * 4)) if extra: chunksize += 1 if (len(iterable) == 0): chunksize = 0 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self, chunksize, len(iterable), callback, error_callback=error_callback) self._taskqueue.put((self._guarded_task_generation(result._job, mapper, task_batches), None)) return result
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, error_callback=None): '\n \n ' self._check_running() if (not hasattr(iterable, '__len__')): iterable = list(iterable) if (chunksize is None): (chunksize, extra) = divmod(len(iterable), (len(self._pool) * 4)) if extra: chunksize += 1 if (len(iterable) == 0): chunksize = 0 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self, chunksize, len(iterable), callback, error_callback=error_callback) self._taskqueue.put((self._guarded_task_generation(result._job, mapper, task_batches), None)) return result<|docstring|>Helper function to implement map, starmap and their async counterparts.<|endoftext|>
44459c36ec73392e293f7e2e205f9c89ba98c289a14c19d9b603f7e7fdee0c09
def forwards(self, orm): 'Write your forwards methods here.' for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('admin:', 'control:') channel.db_lock_storage = lockstring channel.save()
Write your forwards methods here.
src/comms/migrations/0004_changing_lock_comm_admin2control.py
forwards
reddcoin-project/ReddConnect
2
python
def forwards(self, orm): for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('admin:', 'control:') channel.db_lock_storage = lockstring channel.save()
def forwards(self, orm): for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('admin:', 'control:') channel.db_lock_storage = lockstring channel.save()<|docstring|>Write your forwards methods here.<|endoftext|>
d07ccc3e5babb54c5c47209cad176fce3acbab200016ee07c4a6885f281181fd
def backwards(self, orm): 'Write your backwards methods here.' for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('control:', 'admin:') channel.db_lock_storage = lockstring channel.save()
Write your backwards methods here.
src/comms/migrations/0004_changing_lock_comm_admin2control.py
backwards
reddcoin-project/ReddConnect
2
python
def backwards(self, orm): for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('control:', 'admin:') channel.db_lock_storage = lockstring channel.save()
def backwards(self, orm): for channel in orm.Channel.objects.all(): lockstring = channel.db_lock_storage lockstring = lockstring.replace('control:', 'admin:') channel.db_lock_storage = lockstring channel.save()<|docstring|>Write your backwards methods here.<|endoftext|>
c484ce345880bfd259ee7038e5f1806a77f187c22b15d620a17d60ccab118429
def register_mujoco_environments(): 'Register softlearning mujoco environments.' for mujoco_environment in MUJOCO_ENVIRONMENT_SPECS: gym.register(**mujoco_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MUJOCO_ENVIRONMENT_SPECS)) return gym_ids
Register softlearning mujoco environments.
softlearning/environments/gym/__init__.py
register_mujoco_environments
nflu/softlearning
0
python
def register_mujoco_environments(): for mujoco_environment in MUJOCO_ENVIRONMENT_SPECS: gym.register(**mujoco_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MUJOCO_ENVIRONMENT_SPECS)) return gym_ids
def register_mujoco_environments(): for mujoco_environment in MUJOCO_ENVIRONMENT_SPECS: gym.register(**mujoco_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MUJOCO_ENVIRONMENT_SPECS)) return gym_ids<|docstring|>Register softlearning mujoco environments.<|endoftext|>
f868faaf01774d3245f43a3162a5521e3a651e6179ab1224916cf12074b6b878
def register_general_environments(): "Register gym environments that don't fall under a specific category." for general_environment in GENERAL_ENVIRONMENT_SPECS: gym.register(**general_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in GENERAL_ENVIRONMENT_SPECS)) return gym_ids
Register gym environments that don't fall under a specific category.
softlearning/environments/gym/__init__.py
register_general_environments
nflu/softlearning
0
python
def register_general_environments(): for general_environment in GENERAL_ENVIRONMENT_SPECS: gym.register(**general_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in GENERAL_ENVIRONMENT_SPECS)) return gym_ids
def register_general_environments(): for general_environment in GENERAL_ENVIRONMENT_SPECS: gym.register(**general_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in GENERAL_ENVIRONMENT_SPECS)) return gym_ids<|docstring|>Register gym environments that don't fall under a specific category.<|endoftext|>
a9677809e8d9b92675eebe59ba6ddb4e10125b6d9719e3037ca6220596d11b3f
def register_multiworld_environments(): 'Register custom environments from multiworld package.' for multiworld_environment in MULTIWORLD_ENVIRONMENT_SPECS: gym.register(**multiworld_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MULTIWORLD_ENVIRONMENT_SPECS)) return gym_ids
Register custom environments from multiworld package.
softlearning/environments/gym/__init__.py
register_multiworld_environments
nflu/softlearning
0
python
def register_multiworld_environments(): for multiworld_environment in MULTIWORLD_ENVIRONMENT_SPECS: gym.register(**multiworld_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MULTIWORLD_ENVIRONMENT_SPECS)) return gym_ids
def register_multiworld_environments(): for multiworld_environment in MULTIWORLD_ENVIRONMENT_SPECS: gym.register(**multiworld_environment) gym_ids = tuple((environment_spec['id'] for environment_spec in MULTIWORLD_ENVIRONMENT_SPECS)) return gym_ids<|docstring|>Register custom environments from multiworld package.<|endoftext|>
74a17867325badc32f4ee8ab2e33a5c026582dfa030fc7d1a6c973726bd285d0
def build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None): 'Configure the build behavior by setting config variables. This function\n will be deprecated in TVM v0.7. Instead, we should directly use\n tvm.transform.PassContext.\n\n Parameters\n ----------\n opt_level: int, optional\n Optimization level. The optimization pass name and level are as the\n following:\n\n .. code-block:: python\n\n OPT_PASS_LEVEL = {\n "SimplifyInference": 0,\n "OpFusion": 1,\n "FoldConstant": 2,\n "FoldScaleAxis": 3,\n "AlterOpLayout": 3,\n "CanonicalizeOps": 3,\n "CanonicalizeCast": 3,\n "EliminateCommonSubexpr": 3,\n "CombineParallelConv2D": 4,\n "CombineParallelDense": 4,\n "CombineParallelBatchMatmul": 4,\n "FastMath": 4\n }\n\n required_pass: set of str, optional\n Optimization passes that are required regardless of optimization level.\n\n disabled_pass: set of str, optional\n Optimization passes to be disabled during optimization.\n\n trace: Callable[[IRModule, PassInfo, bool], None]\n A tracing function for debugging or introspection.\n\n Returns\n -------\n pass_context: PassContext\n The pass context for optimizations.\n ' warnings.warn('relay.build_config will be deprecated. Please use tvm.transform.PassContext directly', DeprecationWarning) return tvm.transform.PassContext(opt_level, required_pass, disabled_pass, trace)
Configure the build behavior by setting config variables. This function will be deprecated in TVM v0.7. Instead, we should directly use tvm.transform.PassContext. Parameters ---------- opt_level: int, optional Optimization level. The optimization pass name and level are as the following: .. code-block:: python OPT_PASS_LEVEL = { "SimplifyInference": 0, "OpFusion": 1, "FoldConstant": 2, "FoldScaleAxis": 3, "AlterOpLayout": 3, "CanonicalizeOps": 3, "CanonicalizeCast": 3, "EliminateCommonSubexpr": 3, "CombineParallelConv2D": 4, "CombineParallelDense": 4, "CombineParallelBatchMatmul": 4, "FastMath": 4 } required_pass: set of str, optional Optimization passes that are required regardless of optimization level. disabled_pass: set of str, optional Optimization passes to be disabled during optimization. trace: Callable[[IRModule, PassInfo, bool], None] A tracing function for debugging or introspection. Returns ------- pass_context: PassContext The pass context for optimizations.
python/tvm/relay/transform/transform.py
build_config
ryanstout/tvm
2,084
python
def build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None): 'Configure the build behavior by setting config variables. This function\n will be deprecated in TVM v0.7. Instead, we should directly use\n tvm.transform.PassContext.\n\n Parameters\n ----------\n opt_level: int, optional\n Optimization level. The optimization pass name and level are as the\n following:\n\n .. code-block:: python\n\n OPT_PASS_LEVEL = {\n "SimplifyInference": 0,\n "OpFusion": 1,\n "FoldConstant": 2,\n "FoldScaleAxis": 3,\n "AlterOpLayout": 3,\n "CanonicalizeOps": 3,\n "CanonicalizeCast": 3,\n "EliminateCommonSubexpr": 3,\n "CombineParallelConv2D": 4,\n "CombineParallelDense": 4,\n "CombineParallelBatchMatmul": 4,\n "FastMath": 4\n }\n\n required_pass: set of str, optional\n Optimization passes that are required regardless of optimization level.\n\n disabled_pass: set of str, optional\n Optimization passes to be disabled during optimization.\n\n trace: Callable[[IRModule, PassInfo, bool], None]\n A tracing function for debugging or introspection.\n\n Returns\n -------\n pass_context: PassContext\n The pass context for optimizations.\n ' warnings.warn('relay.build_config will be deprecated. Please use tvm.transform.PassContext directly', DeprecationWarning) return tvm.transform.PassContext(opt_level, required_pass, disabled_pass, trace)
def build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None): 'Configure the build behavior by setting config variables. This function\n will be deprecated in TVM v0.7. Instead, we should directly use\n tvm.transform.PassContext.\n\n Parameters\n ----------\n opt_level: int, optional\n Optimization level. The optimization pass name and level are as the\n following:\n\n .. code-block:: python\n\n OPT_PASS_LEVEL = {\n "SimplifyInference": 0,\n "OpFusion": 1,\n "FoldConstant": 2,\n "FoldScaleAxis": 3,\n "AlterOpLayout": 3,\n "CanonicalizeOps": 3,\n "CanonicalizeCast": 3,\n "EliminateCommonSubexpr": 3,\n "CombineParallelConv2D": 4,\n "CombineParallelDense": 4,\n "CombineParallelBatchMatmul": 4,\n "FastMath": 4\n }\n\n required_pass: set of str, optional\n Optimization passes that are required regardless of optimization level.\n\n disabled_pass: set of str, optional\n Optimization passes to be disabled during optimization.\n\n trace: Callable[[IRModule, PassInfo, bool], None]\n A tracing function for debugging or introspection.\n\n Returns\n -------\n pass_context: PassContext\n The pass context for optimizations.\n ' warnings.warn('relay.build_config will be deprecated. Please use tvm.transform.PassContext directly', DeprecationWarning) return tvm.transform.PassContext(opt_level, required_pass, disabled_pass, trace)<|docstring|>Configure the build behavior by setting config variables. This function will be deprecated in TVM v0.7. Instead, we should directly use tvm.transform.PassContext. Parameters ---------- opt_level: int, optional Optimization level. The optimization pass name and level are as the following: .. code-block:: python OPT_PASS_LEVEL = { "SimplifyInference": 0, "OpFusion": 1, "FoldConstant": 2, "FoldScaleAxis": 3, "AlterOpLayout": 3, "CanonicalizeOps": 3, "CanonicalizeCast": 3, "EliminateCommonSubexpr": 3, "CombineParallelConv2D": 4, "CombineParallelDense": 4, "CombineParallelBatchMatmul": 4, "FastMath": 4 } required_pass: set of str, optional Optimization passes that are required regardless of optimization level. disabled_pass: set of str, optional Optimization passes to be disabled during optimization. trace: Callable[[IRModule, PassInfo, bool], None] A tracing function for debugging or introspection. Returns ------- pass_context: PassContext The pass context for optimizations.<|endoftext|>
115ffedf395eb19b8740d3a93e6e80d802af2538ce040bea59b39ed4b88b6c6f
def InferType(): 'Infer the type of an expr.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered type inference pass.\n ' return _ffi_api.InferType()
Infer the type of an expr. Returns ------- ret : tvm.transform.Pass The registered type inference pass.
python/tvm/relay/transform/transform.py
InferType
ryanstout/tvm
2,084
python
def InferType(): 'Infer the type of an expr.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered type inference pass.\n ' return _ffi_api.InferType()
def InferType(): 'Infer the type of an expr.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered type inference pass.\n ' return _ffi_api.InferType()<|docstring|>Infer the type of an expr. Returns ------- ret : tvm.transform.Pass The registered type inference pass.<|endoftext|>
981441dfddd88f2a00ed55c4424d60b895e9ea808355acdbd9819843031fc03b
def FoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense. This pass will\n invoke both forward and backward scale folding.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to fold expressions.\n\n Note\n ----\n Internally, we will call backward_fold_scale_axis before using\n forward_fold_scale_axis as backward folding targets the common conv->bn\n pattern.\n ' return _ffi_api.FoldScaleAxis()
Fold the scaling of axis into weights of conv2d/dense. This pass will invoke both forward and backward scale folding. Returns ------- ret : tvm.transform.Pass The registered pass to fold expressions. Note ---- Internally, we will call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern.
python/tvm/relay/transform/transform.py
FoldScaleAxis
ryanstout/tvm
2,084
python
def FoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense. This pass will\n invoke both forward and backward scale folding.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to fold expressions.\n\n Note\n ----\n Internally, we will call backward_fold_scale_axis before using\n forward_fold_scale_axis as backward folding targets the common conv->bn\n pattern.\n ' return _ffi_api.FoldScaleAxis()
def FoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense. This pass will\n invoke both forward and backward scale folding.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to fold expressions.\n\n Note\n ----\n Internally, we will call backward_fold_scale_axis before using\n forward_fold_scale_axis as backward folding targets the common conv->bn\n pattern.\n ' return _ffi_api.FoldScaleAxis()<|docstring|>Fold the scaling of axis into weights of conv2d/dense. This pass will invoke both forward and backward scale folding. Returns ------- ret : tvm.transform.Pass The registered pass to fold expressions. Note ---- Internally, we will call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern.<|endoftext|>
1e5dc9bdedcce20121d7a0e04271b98a739eaa79b2e4347e5c0a0e6b3dc8204d
def BackwardFoldScaleAxis(): 'Backward fold axis scaling into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to backward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis as backward folding targets the common\n conv->bn pattern.\n ' return _ffi_api.BackwardFoldScaleAxis()
Backward fold axis scaling into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern.
python/tvm/relay/transform/transform.py
BackwardFoldScaleAxis
ryanstout/tvm
2,084
python
def BackwardFoldScaleAxis(): 'Backward fold axis scaling into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to backward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis as backward folding targets the common\n conv->bn pattern.\n ' return _ffi_api.BackwardFoldScaleAxis()
def BackwardFoldScaleAxis(): 'Backward fold axis scaling into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to backward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis as backward folding targets the common\n conv->bn pattern.\n ' return _ffi_api.BackwardFoldScaleAxis()<|docstring|>Backward fold axis scaling into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern.<|endoftext|>
f113c151ac98226c0b5f52ecff69e874ba74c1499297bcf1346502d95a48252b
def RemoveUnusedFunctions(entry_functions=None): 'Remove unused global relay functions in a relay module.\n\n Parameters\n ----------\n entry_functions: list[string]\n The set of entry functions to start from.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to remove unused functions.\n ' if (entry_functions is None): entry_functions = ['main'] return _ffi_api.RemoveUnusedFunctions(entry_functions)
Remove unused global relay functions in a relay module. Parameters ---------- entry_functions: list[string] The set of entry functions to start from. Returns ------- ret : tvm.transform.Pass The registered pass to remove unused functions.
python/tvm/relay/transform/transform.py
RemoveUnusedFunctions
ryanstout/tvm
2,084
python
def RemoveUnusedFunctions(entry_functions=None): 'Remove unused global relay functions in a relay module.\n\n Parameters\n ----------\n entry_functions: list[string]\n The set of entry functions to start from.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to remove unused functions.\n ' if (entry_functions is None): entry_functions = ['main'] return _ffi_api.RemoveUnusedFunctions(entry_functions)
def RemoveUnusedFunctions(entry_functions=None): 'Remove unused global relay functions in a relay module.\n\n Parameters\n ----------\n entry_functions: list[string]\n The set of entry functions to start from.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to remove unused functions.\n ' if (entry_functions is None): entry_functions = ['main'] return _ffi_api.RemoveUnusedFunctions(entry_functions)<|docstring|>Remove unused global relay functions in a relay module. Parameters ---------- entry_functions: list[string] The set of entry functions to start from. Returns ------- ret : tvm.transform.Pass The registered pass to remove unused functions.<|endoftext|>
905f9e994c14d1a781d54d7fd75e285306e12f2866f94a94200fb8ab0af5124e
def ForwardFoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to forward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis, as backward folding targets the\n common conv->bn pattern.\n ' return _ffi_api.ForwardFoldScaleAxis()
Fold the scaling of axis into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to forward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis, as backward folding targets the common conv->bn pattern.
python/tvm/relay/transform/transform.py
ForwardFoldScaleAxis
ryanstout/tvm
2,084
python
def ForwardFoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to forward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis, as backward folding targets the\n common conv->bn pattern.\n ' return _ffi_api.ForwardFoldScaleAxis()
def ForwardFoldScaleAxis(): 'Fold the scaling of axis into weights of conv2d/dense.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass to forward fold expressions.\n\n Note\n ----\n It is recommended to call backward_fold_scale_axis\n before using forward_fold_scale_axis, as backward folding targets the\n common conv->bn pattern.\n ' return _ffi_api.ForwardFoldScaleAxis()<|docstring|>Fold the scaling of axis into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to forward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis, as backward folding targets the common conv->bn pattern.<|endoftext|>
db9609bded525bd7f0a471dca003ed6c8cbe2530247ea4018cc6f86c2f83ece2
def SimplifyInference(): 'Simplify the data-flow graph for inference phase. An simplified expression\n which is semantically equal to the input expression will be returned.\n\n Note that batch norms will only be simplified if their result is indexed at\n tuple index 0.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform operator simplification.\n\n ' return _ffi_api.SimplifyInference()
Simplify the data-flow graph for inference phase. An simplified expression which is semantically equal to the input expression will be returned. Note that batch norms will only be simplified if their result is indexed at tuple index 0. Returns ------- ret: tvm.transform.Pass The registered pass to perform operator simplification.
python/tvm/relay/transform/transform.py
SimplifyInference
ryanstout/tvm
2,084
python
def SimplifyInference(): 'Simplify the data-flow graph for inference phase. An simplified expression\n which is semantically equal to the input expression will be returned.\n\n Note that batch norms will only be simplified if their result is indexed at\n tuple index 0.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform operator simplification.\n\n ' return _ffi_api.SimplifyInference()
def SimplifyInference(): 'Simplify the data-flow graph for inference phase. An simplified expression\n which is semantically equal to the input expression will be returned.\n\n Note that batch norms will only be simplified if their result is indexed at\n tuple index 0.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform operator simplification.\n\n ' return _ffi_api.SimplifyInference()<|docstring|>Simplify the data-flow graph for inference phase. An simplified expression which is semantically equal to the input expression will be returned. Note that batch norms will only be simplified if their result is indexed at tuple index 0. Returns ------- ret: tvm.transform.Pass The registered pass to perform operator simplification.<|endoftext|>
e997f4b7d0596c1f9a4a5ac974b7ee034fd08dbfd9ebc3eb0f26bc90b2011e1b
def FastMath(): 'Converts the expensive non linear functions to their fast but approximate counterparts.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform fast math operations.\n ' return _ffi_api.FastMath()
Converts the expensive non linear functions to their fast but approximate counterparts. Returns ------- ret: tvm.transform.Pass The registered pass to perform fast math operations.
python/tvm/relay/transform/transform.py
FastMath
ryanstout/tvm
2,084
python
def FastMath(): 'Converts the expensive non linear functions to their fast but approximate counterparts.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform fast math operations.\n ' return _ffi_api.FastMath()
def FastMath(): 'Converts the expensive non linear functions to their fast but approximate counterparts.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass to perform fast math operations.\n ' return _ffi_api.FastMath()<|docstring|>Converts the expensive non linear functions to their fast but approximate counterparts. Returns ------- ret: tvm.transform.Pass The registered pass to perform fast math operations.<|endoftext|>
625956641230efb70ca5ce41e805d40c9e8f6daebad0c9669104daf873fa3888
def CanonicalizeOps(): 'Canonicalize special operators to basic operators.\n This can simplify followed analysis, e.g. expanding bias_add to\n expand_dims and broadcast_add.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass performing the canonicalization.\n ' return _ffi_api.CanonicalizeOps()
Canonicalize special operators to basic operators. This can simplify followed analysis, e.g. expanding bias_add to expand_dims and broadcast_add. Returns ------- ret: tvm.transform.Pass The registered pass performing the canonicalization.
python/tvm/relay/transform/transform.py
CanonicalizeOps
ryanstout/tvm
2,084
python
def CanonicalizeOps(): 'Canonicalize special operators to basic operators.\n This can simplify followed analysis, e.g. expanding bias_add to\n expand_dims and broadcast_add.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass performing the canonicalization.\n ' return _ffi_api.CanonicalizeOps()
def CanonicalizeOps(): 'Canonicalize special operators to basic operators.\n This can simplify followed analysis, e.g. expanding bias_add to\n expand_dims and broadcast_add.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass performing the canonicalization.\n ' return _ffi_api.CanonicalizeOps()<|docstring|>Canonicalize special operators to basic operators. This can simplify followed analysis, e.g. expanding bias_add to expand_dims and broadcast_add. Returns ------- ret: tvm.transform.Pass The registered pass performing the canonicalization.<|endoftext|>
09675cd3535d64c1c8077bcac4535664ef8fbc7974e9145b2ce376a5fbf846b4
def DeadCodeElimination(inline_once=False, ignore_impurity=False): 'Remove expressions that do not have any users (dead code).\n\n Parameters\n ----------\n inline_once: Optional[Bool]\n Whether to inline a binding that is referenced exactly once.\n ignore_impurity: Optional[Bool]\n Whether to ignore possible side-effects in let-bound expressions.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eliminates the dead code in a Relay program.\n ' return _ffi_api.DeadCodeElimination(inline_once, ignore_impurity)
Remove expressions that do not have any users (dead code). Parameters ---------- inline_once: Optional[Bool] Whether to inline a binding that is referenced exactly once. ignore_impurity: Optional[Bool] Whether to ignore possible side-effects in let-bound expressions. Returns ------- ret: tvm.transform.Pass The registered pass that eliminates the dead code in a Relay program.
python/tvm/relay/transform/transform.py
DeadCodeElimination
ryanstout/tvm
2,084
python
def DeadCodeElimination(inline_once=False, ignore_impurity=False): 'Remove expressions that do not have any users (dead code).\n\n Parameters\n ----------\n inline_once: Optional[Bool]\n Whether to inline a binding that is referenced exactly once.\n ignore_impurity: Optional[Bool]\n Whether to ignore possible side-effects in let-bound expressions.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eliminates the dead code in a Relay program.\n ' return _ffi_api.DeadCodeElimination(inline_once, ignore_impurity)
def DeadCodeElimination(inline_once=False, ignore_impurity=False): 'Remove expressions that do not have any users (dead code).\n\n Parameters\n ----------\n inline_once: Optional[Bool]\n Whether to inline a binding that is referenced exactly once.\n ignore_impurity: Optional[Bool]\n Whether to ignore possible side-effects in let-bound expressions.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eliminates the dead code in a Relay program.\n ' return _ffi_api.DeadCodeElimination(inline_once, ignore_impurity)<|docstring|>Remove expressions that do not have any users (dead code). Parameters ---------- inline_once: Optional[Bool] Whether to inline a binding that is referenced exactly once. ignore_impurity: Optional[Bool] Whether to ignore possible side-effects in let-bound expressions. Returns ------- ret: tvm.transform.Pass The registered pass that eliminates the dead code in a Relay program.<|endoftext|>
f85a5295b5efd7d4f1598d6bbb7664ff8a5cd3b3068668b930701fe4d5538916
def LazyGradientInit(): 'Reduces memory usage of gradient tensors\n\n Parameters\n ----------\n\n Returns\n -------\n ret: tvm.transform.Pass\n A pass which delays and/or reduces memory allocation,\n by lazily allocating 0 or one filled tensors.\n ' return _ffi_api.LazyGradientInit()
Reduces memory usage of gradient tensors Parameters ---------- Returns ------- ret: tvm.transform.Pass A pass which delays and/or reduces memory allocation, by lazily allocating 0 or one filled tensors.
python/tvm/relay/transform/transform.py
LazyGradientInit
ryanstout/tvm
2,084
python
def LazyGradientInit(): 'Reduces memory usage of gradient tensors\n\n Parameters\n ----------\n\n Returns\n -------\n ret: tvm.transform.Pass\n A pass which delays and/or reduces memory allocation,\n by lazily allocating 0 or one filled tensors.\n ' return _ffi_api.LazyGradientInit()
def LazyGradientInit(): 'Reduces memory usage of gradient tensors\n\n Parameters\n ----------\n\n Returns\n -------\n ret: tvm.transform.Pass\n A pass which delays and/or reduces memory allocation,\n by lazily allocating 0 or one filled tensors.\n ' return _ffi_api.LazyGradientInit()<|docstring|>Reduces memory usage of gradient tensors Parameters ---------- Returns ------- ret: tvm.transform.Pass A pass which delays and/or reduces memory allocation, by lazily allocating 0 or one filled tensors.<|endoftext|>
30de09dc9f1035668dc035706dff445963606a02e6603c70c6453ae8077875ad
def FoldConstantExpr(expr, mod): 'Fold the constant expressions in a Relay program.\n Parameters\n ----------\n expr: Expr\n The expression to fold\n mod: IRModule\n The module the expr lives in (for global calls)\n\n Returns\n -------\n new_expr: Expr\n The expr after Constant Folding\n ' return _ffi_api.FoldConstantExpr(expr, mod)
Fold the constant expressions in a Relay program. Parameters ---------- expr: Expr The expression to fold mod: IRModule The module the expr lives in (for global calls) Returns ------- new_expr: Expr The expr after Constant Folding
python/tvm/relay/transform/transform.py
FoldConstantExpr
ryanstout/tvm
2,084
python
def FoldConstantExpr(expr, mod): 'Fold the constant expressions in a Relay program.\n Parameters\n ----------\n expr: Expr\n The expression to fold\n mod: IRModule\n The module the expr lives in (for global calls)\n\n Returns\n -------\n new_expr: Expr\n The expr after Constant Folding\n ' return _ffi_api.FoldConstantExpr(expr, mod)
def FoldConstantExpr(expr, mod): 'Fold the constant expressions in a Relay program.\n Parameters\n ----------\n expr: Expr\n The expression to fold\n mod: IRModule\n The module the expr lives in (for global calls)\n\n Returns\n -------\n new_expr: Expr\n The expr after Constant Folding\n ' return _ffi_api.FoldConstantExpr(expr, mod)<|docstring|>Fold the constant expressions in a Relay program. Parameters ---------- expr: Expr The expression to fold mod: IRModule The module the expr lives in (for global calls) Returns ------- new_expr: Expr The expr after Constant Folding<|endoftext|>
d81c61e2c09d3f972ce3198bfcbfdb23980d4f4ae71d44b2dfa98a1802a84ce3
def FoldConstant(): 'Fold the constant expressions in a Relay program.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for constant folding.\n ' return _ffi_api.FoldConstant()
Fold the constant expressions in a Relay program. Returns ------- ret : tvm.transform.Pass The registered pass for constant folding.
python/tvm/relay/transform/transform.py
FoldConstant
ryanstout/tvm
2,084
python
def FoldConstant(): 'Fold the constant expressions in a Relay program.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for constant folding.\n ' return _ffi_api.FoldConstant()
def FoldConstant(): 'Fold the constant expressions in a Relay program.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for constant folding.\n ' return _ffi_api.FoldConstant()<|docstring|>Fold the constant expressions in a Relay program. Returns ------- ret : tvm.transform.Pass The registered pass for constant folding.<|endoftext|>
2988cc28473876109826d1005bf3a965300100e7f74d5e48c61d692f1746f5ba
def FuseOps(fuse_opt_level=(- 1)): 'Fuse operators in an expr to a larger operator according to some rules.\n\n Parameters\n ----------\n fuse_opt_level : int\n The level of fuse optimization. -1 indicates that the level will be\n inferred from pass context.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator fusion.\n ' return _ffi_api.FuseOps(fuse_opt_level)
Fuse operators in an expr to a larger operator according to some rules. Parameters ---------- fuse_opt_level : int The level of fuse optimization. -1 indicates that the level will be inferred from pass context. Returns ------- ret : tvm.transform.Pass The registered pass for operator fusion.
python/tvm/relay/transform/transform.py
FuseOps
ryanstout/tvm
2,084
python
def FuseOps(fuse_opt_level=(- 1)): 'Fuse operators in an expr to a larger operator according to some rules.\n\n Parameters\n ----------\n fuse_opt_level : int\n The level of fuse optimization. -1 indicates that the level will be\n inferred from pass context.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator fusion.\n ' return _ffi_api.FuseOps(fuse_opt_level)
def FuseOps(fuse_opt_level=(- 1)): 'Fuse operators in an expr to a larger operator according to some rules.\n\n Parameters\n ----------\n fuse_opt_level : int\n The level of fuse optimization. -1 indicates that the level will be\n inferred from pass context.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator fusion.\n ' return _ffi_api.FuseOps(fuse_opt_level)<|docstring|>Fuse operators in an expr to a larger operator according to some rules. Parameters ---------- fuse_opt_level : int The level of fuse optimization. -1 indicates that the level will be inferred from pass context. Returns ------- ret : tvm.transform.Pass The registered pass for operator fusion.<|endoftext|>
b1c909ad0baeb703b87dcb0e4b47def800633bfff77a2ccd2ed33f5fa40069e8
def DefuseOps(): 'The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the\n program before FuseOps. (i.e., x == DefuseOps(FuseOps(x)))\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator defusion.\n ' return _ffi_api.DefuseOps()
The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the program before FuseOps. (i.e., x == DefuseOps(FuseOps(x))) Returns ------- ret : tvm.transform.Pass The registered pass for operator defusion.
python/tvm/relay/transform/transform.py
DefuseOps
ryanstout/tvm
2,084
python
def DefuseOps(): 'The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the\n program before FuseOps. (i.e., x == DefuseOps(FuseOps(x)))\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator defusion.\n ' return _ffi_api.DefuseOps()
def DefuseOps(): 'The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the\n program before FuseOps. (i.e., x == DefuseOps(FuseOps(x)))\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for operator defusion.\n ' return _ffi_api.DefuseOps()<|docstring|>The inverse operation of FuseOps. It transforms a fused program returned by FuseOps into the program before FuseOps. (i.e., x == DefuseOps(FuseOps(x))) Returns ------- ret : tvm.transform.Pass The registered pass for operator defusion.<|endoftext|>
e484dce1e1e5734501033578d24043e97927f8ebf21f2748e75b5d134a29d2bf
def CombineParallelConv2D(min_num_branches=3): 'Combine multiple conv2d operators into one.\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel conv2d operators.\n ' return _ffi_api.CombineParallelConv2D(min_num_branches)
Combine multiple conv2d operators into one. Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel conv2d operators.
python/tvm/relay/transform/transform.py
CombineParallelConv2D
ryanstout/tvm
2,084
python
def CombineParallelConv2D(min_num_branches=3): 'Combine multiple conv2d operators into one.\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel conv2d operators.\n ' return _ffi_api.CombineParallelConv2D(min_num_branches)
def CombineParallelConv2D(min_num_branches=3): 'Combine multiple conv2d operators into one.\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel conv2d operators.\n ' return _ffi_api.CombineParallelConv2D(min_num_branches)<|docstring|>Combine multiple conv2d operators into one. Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel conv2d operators.<|endoftext|>
4bf3545776068b94bbb0f1c25730eb94a9f77bb2a36c549fdb381a2293c608a5
def CombineParallelDense(min_num_branches=3, to_batch=True): 'Combine multiple dense operators into one. For example:\n\n .. code-block\n data\n / dense (2,2) dense (2,2)\n | |\n elemwise/bcast (2,2) elemwise/bcast (2,2)\n\n Would become:\n\n .. code-block\n\n data\n |\n batch_matmul+elemwise/bcast (2,2,2)\n\n or (if to_batch=False)\n\n .. code-block\n\n data\n |\n dense+elemwise/bcast (2,2+2)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n to_batch_matmul : bool\n If True, combine parallel dense ops into batch_matmul op.\n If False, combine parallel dense ops into dense op.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelDense(min_num_branches, to_batch)
Combine multiple dense operators into one. For example: .. code-block data / dense (2,2) dense (2,2) | | elemwise/bcast (2,2) elemwise/bcast (2,2) Would become: .. code-block data | batch_matmul+elemwise/bcast (2,2,2) or (if to_batch=False) .. code-block data | dense+elemwise/bcast (2,2+2) Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. to_batch_matmul : bool If True, combine parallel dense ops into batch_matmul op. If False, combine parallel dense ops into dense op. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators.
python/tvm/relay/transform/transform.py
CombineParallelDense
ryanstout/tvm
2,084
python
def CombineParallelDense(min_num_branches=3, to_batch=True): 'Combine multiple dense operators into one. For example:\n\n .. code-block\n data\n / dense (2,2) dense (2,2)\n | |\n elemwise/bcast (2,2) elemwise/bcast (2,2)\n\n Would become:\n\n .. code-block\n\n data\n |\n batch_matmul+elemwise/bcast (2,2,2)\n\n or (if to_batch=False)\n\n .. code-block\n\n data\n |\n dense+elemwise/bcast (2,2+2)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n to_batch_matmul : bool\n If True, combine parallel dense ops into batch_matmul op.\n If False, combine parallel dense ops into dense op.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelDense(min_num_branches, to_batch)
def CombineParallelDense(min_num_branches=3, to_batch=True): 'Combine multiple dense operators into one. For example:\n\n .. code-block\n data\n / dense (2,2) dense (2,2)\n | |\n elemwise/bcast (2,2) elemwise/bcast (2,2)\n\n Would become:\n\n .. code-block\n\n data\n |\n batch_matmul+elemwise/bcast (2,2,2)\n\n or (if to_batch=False)\n\n .. code-block\n\n data\n |\n dense+elemwise/bcast (2,2+2)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n to_batch_matmul : bool\n If True, combine parallel dense ops into batch_matmul op.\n If False, combine parallel dense ops into dense op.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelDense(min_num_branches, to_batch)<|docstring|>Combine multiple dense operators into one. For example: .. code-block data / dense (2,2) dense (2,2) | | elemwise/bcast (2,2) elemwise/bcast (2,2) Would become: .. code-block data | batch_matmul+elemwise/bcast (2,2,2) or (if to_batch=False) .. code-block data | dense+elemwise/bcast (2,2+2) Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. to_batch_matmul : bool If True, combine parallel dense ops into batch_matmul op. If False, combine parallel dense ops into dense op. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators.<|endoftext|>
46b833f561047d351619e98912b90bcd54971d3c10378cbef461a60a2f638176
def CombineParallelBatchMatmul(min_num_branches=3): 'Combine multiple batch matmul operators into one. For example:\n\n .. code-block\n data (1, 2, 3)\n / batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3))\n | |\n elemwise/bcast (1, 2, 4) elemwise/bcast (1, 2, 5)\n\n Would become:\n\n .. code-block\n\n data (1, 2, 3)\n |\n batch_matmul(data, (1, 4+5, 3))\n |\n elemwise/bcast (1 ,2, 4+5)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelBatchMatmul(min_num_branches)
Combine multiple batch matmul operators into one. For example: .. code-block data (1, 2, 3) / batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3)) | | elemwise/bcast (1, 2, 4) elemwise/bcast (1, 2, 5) Would become: .. code-block data (1, 2, 3) | batch_matmul(data, (1, 4+5, 3)) | elemwise/bcast (1 ,2, 4+5) Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators.
python/tvm/relay/transform/transform.py
CombineParallelBatchMatmul
ryanstout/tvm
2,084
python
def CombineParallelBatchMatmul(min_num_branches=3): 'Combine multiple batch matmul operators into one. For example:\n\n .. code-block\n data (1, 2, 3)\n / batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3))\n | |\n elemwise/bcast (1, 2, 4) elemwise/bcast (1, 2, 5)\n\n Would become:\n\n .. code-block\n\n data (1, 2, 3)\n |\n batch_matmul(data, (1, 4+5, 3))\n |\n elemwise/bcast (1 ,2, 4+5)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelBatchMatmul(min_num_branches)
def CombineParallelBatchMatmul(min_num_branches=3): 'Combine multiple batch matmul operators into one. For example:\n\n .. code-block\n data (1, 2, 3)\n / batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3))\n | |\n elemwise/bcast (1, 2, 4) elemwise/bcast (1, 2, 5)\n\n Would become:\n\n .. code-block\n\n data (1, 2, 3)\n |\n batch_matmul(data, (1, 4+5, 3))\n |\n elemwise/bcast (1 ,2, 4+5)\n\n Parameters\n ----------\n min_num_branches : int\n The minimum number of required parallel branches for performing this\n optimization.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that combines parallel dense operators.\n ' return _ffi_api.CombineParallelBatchMatmul(min_num_branches)<|docstring|>Combine multiple batch matmul operators into one. For example: .. code-block data (1, 2, 3) / batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3)) | | elemwise/bcast (1, 2, 4) elemwise/bcast (1, 2, 5) Would become: .. code-block data (1, 2, 3) | batch_matmul(data, (1, 4+5, 3)) | elemwise/bcast (1 ,2, 4+5) Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators.<|endoftext|>
570d091df3999fe615544da69e3832b14d8cd95e4551b63187d3cbba48e8f105
def BatchingOps(): 'Batching parallel operators into one for Conv2D, Dense and BatchMatmul.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The sequential pass which apply batching for different operator types.\n ' return tvm.transform.Sequential([CombineParallelConv2D(), CombineParallelDense(), CombineParallelBatchMatmul()])
Batching parallel operators into one for Conv2D, Dense and BatchMatmul. Returns ------- ret: tvm.transform.Pass The sequential pass which apply batching for different operator types.
python/tvm/relay/transform/transform.py
BatchingOps
ryanstout/tvm
2,084
python
def BatchingOps(): 'Batching parallel operators into one for Conv2D, Dense and BatchMatmul.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The sequential pass which apply batching for different operator types.\n ' return tvm.transform.Sequential([CombineParallelConv2D(), CombineParallelDense(), CombineParallelBatchMatmul()])
def BatchingOps(): 'Batching parallel operators into one for Conv2D, Dense and BatchMatmul.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The sequential pass which apply batching for different operator types.\n ' return tvm.transform.Sequential([CombineParallelConv2D(), CombineParallelDense(), CombineParallelBatchMatmul()])<|docstring|>Batching parallel operators into one for Conv2D, Dense and BatchMatmul. Returns ------- ret: tvm.transform.Pass The sequential pass which apply batching for different operator types.<|endoftext|>
7da211ded90a8b449b03a67c7456131d89f1995ceeaf2c182e5313892854a0e5
def AlterOpLayout(): 'Alternate the layouts of operators or replace primitive operators with\n other expressions.\n This pass can be used for computing convolution in custom layouts or\n other general weight pre-transformation.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that alters the layout of operators.\n ' return _ffi_api.AlterOpLayout()
Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. Returns ------- ret : tvm.transform.Pass The registered pass that alters the layout of operators.
python/tvm/relay/transform/transform.py
AlterOpLayout
ryanstout/tvm
2,084
python
def AlterOpLayout(): 'Alternate the layouts of operators or replace primitive operators with\n other expressions.\n This pass can be used for computing convolution in custom layouts or\n other general weight pre-transformation.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that alters the layout of operators.\n ' return _ffi_api.AlterOpLayout()
def AlterOpLayout(): 'Alternate the layouts of operators or replace primitive operators with\n other expressions.\n This pass can be used for computing convolution in custom layouts or\n other general weight pre-transformation.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that alters the layout of operators.\n ' return _ffi_api.AlterOpLayout()<|docstring|>Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. Returns ------- ret : tvm.transform.Pass The registered pass that alters the layout of operators.<|endoftext|>
2abccd61482fe59a0b68773c36b332752ca2e46d37ab8dfd4e4ee6847df13c4e
def ConvertLayout(desired_layouts): 'Given a dest layout, this pass transforms the expr such that most of the ops input data\n layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms,\n one at the start and one at the end.\n\n This pass is not a part of relay.build and is expected to be called between framework-relay\n parser and relay.build call. This is very helpful for hardware backends that support/prefer only\n type of data layout.\n\n RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009\n\n This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define\n new layouts for conv2d ops for now. Most of the other operators try to adapt to their input\n layout using the InferCorrectLayout infrastructure.\n\n Parameters\n ----------\n desired_layouts : map of op_name to list of layouts\n Specify a mapping of operator names to a list of layouts to convert to, in the order\n defined by the operator. An example for nn.conv2d could be: {"nn.conv2d", ["NHWC", "OHWI]},\n where the first item in the list specifies the data layout and the second specifies the\n kernel layout.\n\n Returns\n -------\n pass: FunctionPass\n The pass.\n ' return _ffi_api.ConvertLayout(desired_layouts)
Given a dest layout, this pass transforms the expr such that most of the ops input data layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms, one at the start and one at the end. This pass is not a part of relay.build and is expected to be called between framework-relay parser and relay.build call. This is very helpful for hardware backends that support/prefer only type of data layout. RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009 This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define new layouts for conv2d ops for now. Most of the other operators try to adapt to their input layout using the InferCorrectLayout infrastructure. Parameters ---------- desired_layouts : map of op_name to list of layouts Specify a mapping of operator names to a list of layouts to convert to, in the order defined by the operator. An example for nn.conv2d could be: {"nn.conv2d", ["NHWC", "OHWI]}, where the first item in the list specifies the data layout and the second specifies the kernel layout. Returns ------- pass: FunctionPass The pass.
python/tvm/relay/transform/transform.py
ConvertLayout
ryanstout/tvm
2,084
python
def ConvertLayout(desired_layouts): 'Given a dest layout, this pass transforms the expr such that most of the ops input data\n layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms,\n one at the start and one at the end.\n\n This pass is not a part of relay.build and is expected to be called between framework-relay\n parser and relay.build call. This is very helpful for hardware backends that support/prefer only\n type of data layout.\n\n RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009\n\n This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define\n new layouts for conv2d ops for now. Most of the other operators try to adapt to their input\n layout using the InferCorrectLayout infrastructure.\n\n Parameters\n ----------\n desired_layouts : map of op_name to list of layouts\n Specify a mapping of operator names to a list of layouts to convert to, in the order\n defined by the operator. An example for nn.conv2d could be: {"nn.conv2d", ["NHWC", "OHWI]},\n where the first item in the list specifies the data layout and the second specifies the\n kernel layout.\n\n Returns\n -------\n pass: FunctionPass\n The pass.\n ' return _ffi_api.ConvertLayout(desired_layouts)
def ConvertLayout(desired_layouts): 'Given a dest layout, this pass transforms the expr such that most of the ops input data\n layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms,\n one at the start and one at the end.\n\n This pass is not a part of relay.build and is expected to be called between framework-relay\n parser and relay.build call. This is very helpful for hardware backends that support/prefer only\n type of data layout.\n\n RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009\n\n This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define\n new layouts for conv2d ops for now. Most of the other operators try to adapt to their input\n layout using the InferCorrectLayout infrastructure.\n\n Parameters\n ----------\n desired_layouts : map of op_name to list of layouts\n Specify a mapping of operator names to a list of layouts to convert to, in the order\n defined by the operator. An example for nn.conv2d could be: {"nn.conv2d", ["NHWC", "OHWI]},\n where the first item in the list specifies the data layout and the second specifies the\n kernel layout.\n\n Returns\n -------\n pass: FunctionPass\n The pass.\n ' return _ffi_api.ConvertLayout(desired_layouts)<|docstring|>Given a dest layout, this pass transforms the expr such that most of the ops input data layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms, one at the start and one at the end. This pass is not a part of relay.build and is expected to be called between framework-relay parser and relay.build call. This is very helpful for hardware backends that support/prefer only type of data layout. RFC - https://discuss.tvm.apache.org/t/layout-conversion-pass/4009 This pass uses most of the AlterOpLayout and InferCorrectLayout infrastructure. We can define new layouts for conv2d ops for now. Most of the other operators try to adapt to their input layout using the InferCorrectLayout infrastructure. Parameters ---------- desired_layouts : map of op_name to list of layouts Specify a mapping of operator names to a list of layouts to convert to, in the order defined by the operator. An example for nn.conv2d could be: {"nn.conv2d", ["NHWC", "OHWI]}, where the first item in the list specifies the data layout and the second specifies the kernel layout. Returns ------- pass: FunctionPass The pass.<|endoftext|>
d420744fb9853efc03870637d115c6c70f371dd12ba23777ba2e3fad9881ce64
def Legalize(legalize_map_attr_name='FTVMLegalize'): "Legalizes an expression with another expression.\n This pass can be used to replace an expr with another expr for target\n dependent optimizations. For example, one expr, though semnatically\n equivalent to the other, can have better performance on a target. This pass\n can be used to legalize the expr in a target-dependent manner.\n\n Parameters\n ----------\n legalize_map_attr_name : str\n The Op's attr name which corresponds to the legalize rule function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that rewrites an expr.\n " return _ffi_api.Legalize(legalize_map_attr_name)
Legalizes an expression with another expression. This pass can be used to replace an expr with another expr for target dependent optimizations. For example, one expr, though semnatically equivalent to the other, can have better performance on a target. This pass can be used to legalize the expr in a target-dependent manner. Parameters ---------- legalize_map_attr_name : str The Op's attr name which corresponds to the legalize rule function. Returns ------- ret : tvm.transform.Pass The registered pass that rewrites an expr.
python/tvm/relay/transform/transform.py
Legalize
ryanstout/tvm
2,084
python
def Legalize(legalize_map_attr_name='FTVMLegalize'): "Legalizes an expression with another expression.\n This pass can be used to replace an expr with another expr for target\n dependent optimizations. For example, one expr, though semnatically\n equivalent to the other, can have better performance on a target. This pass\n can be used to legalize the expr in a target-dependent manner.\n\n Parameters\n ----------\n legalize_map_attr_name : str\n The Op's attr name which corresponds to the legalize rule function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that rewrites an expr.\n " return _ffi_api.Legalize(legalize_map_attr_name)
def Legalize(legalize_map_attr_name='FTVMLegalize'): "Legalizes an expression with another expression.\n This pass can be used to replace an expr with another expr for target\n dependent optimizations. For example, one expr, though semnatically\n equivalent to the other, can have better performance on a target. This pass\n can be used to legalize the expr in a target-dependent manner.\n\n Parameters\n ----------\n legalize_map_attr_name : str\n The Op's attr name which corresponds to the legalize rule function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that rewrites an expr.\n " return _ffi_api.Legalize(legalize_map_attr_name)<|docstring|>Legalizes an expression with another expression. This pass can be used to replace an expr with another expr for target dependent optimizations. For example, one expr, though semnatically equivalent to the other, can have better performance on a target. This pass can be used to legalize the expr in a target-dependent manner. Parameters ---------- legalize_map_attr_name : str The Op's attr name which corresponds to the legalize rule function. Returns ------- ret : tvm.transform.Pass The registered pass that rewrites an expr.<|endoftext|>
4c181262edd2c26464714761f5608bd4ebabf078ded29eec6ef3354421ff6036
def MergeComposite(pattern_table): "Merge multiple operators into a single composite relay function.\n\n Parameters\n ----------\n pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]]\n A list of (pattern_name, pattern, check) tuples.\n The order of the patterns in the list will determine the order\n of priority in which they are matched.\n 'check' is a function to check whether an extracted pattern matches.\n It can be implemented by pattern writer but if not specified it will\n always return True.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges operators into a single composite\n relay function.\n " pattern_names = [] patterns = [] checks = [] for tup in pattern_table: if (len(tup) == 2): (pattern_name, pattern) = tup check = (lambda extract: True) elif (len(tup) == 3): (pattern_name, pattern, check) = tup pattern_names.append(pattern_name) patterns.append(pattern) checks.append(check) return _ffi_api.MergeComposite(pattern_names, patterns, *checks)
Merge multiple operators into a single composite relay function. Parameters ---------- pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]] A list of (pattern_name, pattern, check) tuples. The order of the patterns in the list will determine the order of priority in which they are matched. 'check' is a function to check whether an extracted pattern matches. It can be implemented by pattern writer but if not specified it will always return True. Returns ------- ret : tvm.transform.Pass The registered pass that merges operators into a single composite relay function.
python/tvm/relay/transform/transform.py
MergeComposite
ryanstout/tvm
2,084
python
def MergeComposite(pattern_table): "Merge multiple operators into a single composite relay function.\n\n Parameters\n ----------\n pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]]\n A list of (pattern_name, pattern, check) tuples.\n The order of the patterns in the list will determine the order\n of priority in which they are matched.\n 'check' is a function to check whether an extracted pattern matches.\n It can be implemented by pattern writer but if not specified it will\n always return True.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges operators into a single composite\n relay function.\n " pattern_names = [] patterns = [] checks = [] for tup in pattern_table: if (len(tup) == 2): (pattern_name, pattern) = tup check = (lambda extract: True) elif (len(tup) == 3): (pattern_name, pattern, check) = tup pattern_names.append(pattern_name) patterns.append(pattern) checks.append(check) return _ffi_api.MergeComposite(pattern_names, patterns, *checks)
def MergeComposite(pattern_table): "Merge multiple operators into a single composite relay function.\n\n Parameters\n ----------\n pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]]\n A list of (pattern_name, pattern, check) tuples.\n The order of the patterns in the list will determine the order\n of priority in which they are matched.\n 'check' is a function to check whether an extracted pattern matches.\n It can be implemented by pattern writer but if not specified it will\n always return True.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges operators into a single composite\n relay function.\n " pattern_names = [] patterns = [] checks = [] for tup in pattern_table: if (len(tup) == 2): (pattern_name, pattern) = tup check = (lambda extract: True) elif (len(tup) == 3): (pattern_name, pattern, check) = tup pattern_names.append(pattern_name) patterns.append(pattern) checks.append(check) return _ffi_api.MergeComposite(pattern_names, patterns, *checks)<|docstring|>Merge multiple operators into a single composite relay function. Parameters ---------- pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]] A list of (pattern_name, pattern, check) tuples. The order of the patterns in the list will determine the order of priority in which they are matched. 'check' is a function to check whether an extracted pattern matches. It can be implemented by pattern writer but if not specified it will always return True. Returns ------- ret : tvm.transform.Pass The registered pass that merges operators into a single composite relay function.<|endoftext|>
88d938f1f8638ca6d7f76be7b1c20d20522849aa293bf455dd72fa605cf7dd3a
def MergeCompilerRegions(): 'Merge together compiler regions.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges compiler regions.\n ' return _ffi_api.MergeCompilerRegions()
Merge together compiler regions. Returns ------- ret : tvm.transform.Pass The registered pass that merges compiler regions.
python/tvm/relay/transform/transform.py
MergeCompilerRegions
ryanstout/tvm
2,084
python
def MergeCompilerRegions(): 'Merge together compiler regions.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges compiler regions.\n ' return _ffi_api.MergeCompilerRegions()
def MergeCompilerRegions(): 'Merge together compiler regions.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that merges compiler regions.\n ' return _ffi_api.MergeCompilerRegions()<|docstring|>Merge together compiler regions. Returns ------- ret : tvm.transform.Pass The registered pass that merges compiler regions.<|endoftext|>
750fcb2cf12f9980201a0d17c1921e51c79b0690f987b90d688efa42bab39742
def ToANormalForm(): "Turn Graph Normal Form expression into A Normal Form Expression.\n The scope of the root expression is the global scope.\n The scope of any non root expression is the least common ancestor of all it's scope.\n Values are ordered by post-DFS order in each scope.\n\n Returns\n -------\n ret : Union[tvm.transform.Pass, tvm.relay.Expr]\n The registered pass that transforms an expression into A Normal Form.\n " return _ffi_api.ToANormalForm()
Turn Graph Normal Form expression into A Normal Form Expression. The scope of the root expression is the global scope. The scope of any non root expression is the least common ancestor of all it's scope. Values are ordered by post-DFS order in each scope. Returns ------- ret : Union[tvm.transform.Pass, tvm.relay.Expr] The registered pass that transforms an expression into A Normal Form.
python/tvm/relay/transform/transform.py
ToANormalForm
ryanstout/tvm
2,084
python
def ToANormalForm(): "Turn Graph Normal Form expression into A Normal Form Expression.\n The scope of the root expression is the global scope.\n The scope of any non root expression is the least common ancestor of all it's scope.\n Values are ordered by post-DFS order in each scope.\n\n Returns\n -------\n ret : Union[tvm.transform.Pass, tvm.relay.Expr]\n The registered pass that transforms an expression into A Normal Form.\n " return _ffi_api.ToANormalForm()
def ToANormalForm(): "Turn Graph Normal Form expression into A Normal Form Expression.\n The scope of the root expression is the global scope.\n The scope of any non root expression is the least common ancestor of all it's scope.\n Values are ordered by post-DFS order in each scope.\n\n Returns\n -------\n ret : Union[tvm.transform.Pass, tvm.relay.Expr]\n The registered pass that transforms an expression into A Normal Form.\n " return _ffi_api.ToANormalForm()<|docstring|>Turn Graph Normal Form expression into A Normal Form Expression. The scope of the root expression is the global scope. The scope of any non root expression is the least common ancestor of all it's scope. Values are ordered by post-DFS order in each scope. Returns ------- ret : Union[tvm.transform.Pass, tvm.relay.Expr] The registered pass that transforms an expression into A Normal Form.<|endoftext|>
f1231ad5fb262d4cb04418e8b1c0322266ab8672cf4f3ea6b5b995e8c3c1b37e
def ToANormalFormExpr(e): 'ToANormalForm, but on expression level.\n\n Parameters\n ----------\n e : Expr\n The graph expression.\n\n Returns\n -------\n ret : Expr\n The transformed expresion.\n ' return _ffi_api.ToANormalFormExpr(e)
ToANormalForm, but on expression level. Parameters ---------- e : Expr The graph expression. Returns ------- ret : Expr The transformed expresion.
python/tvm/relay/transform/transform.py
ToANormalFormExpr
ryanstout/tvm
2,084
python
def ToANormalFormExpr(e): 'ToANormalForm, but on expression level.\n\n Parameters\n ----------\n e : Expr\n The graph expression.\n\n Returns\n -------\n ret : Expr\n The transformed expresion.\n ' return _ffi_api.ToANormalFormExpr(e)
def ToANormalFormExpr(e): 'ToANormalForm, but on expression level.\n\n Parameters\n ----------\n e : Expr\n The graph expression.\n\n Returns\n -------\n ret : Expr\n The transformed expresion.\n ' return _ffi_api.ToANormalFormExpr(e)<|docstring|>ToANormalForm, but on expression level. Parameters ---------- e : Expr The graph expression. Returns ------- ret : Expr The transformed expresion.<|endoftext|>
bf45c26f6ce8abfe2313fb569e8152f453dc459fa46cadab09444b222bd9b5af
def ToBasicBlockNormalForm(): 'Turn an expression to Basic Block Normal Form.\n We define a block as a group of expressions implied by the scope structure.\n Each graph node can only belong to a single block.\n For any value that is being used in multiple blocks, it has to be referred\n by a Var which is defined in a block, whose scope is the least common ancestor\n of blocks this value is used.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that transforms an expression into Basic Block Normal Form.\n ' return _ffi_api.ToBasicBlockNormalForm()
Turn an expression to Basic Block Normal Form. We define a block as a group of expressions implied by the scope structure. Each graph node can only belong to a single block. For any value that is being used in multiple blocks, it has to be referred by a Var which is defined in a block, whose scope is the least common ancestor of blocks this value is used. Returns ------- ret: tvm.transform.Pass The registered pass that transforms an expression into Basic Block Normal Form.
python/tvm/relay/transform/transform.py
ToBasicBlockNormalForm
ryanstout/tvm
2,084
python
def ToBasicBlockNormalForm(): 'Turn an expression to Basic Block Normal Form.\n We define a block as a group of expressions implied by the scope structure.\n Each graph node can only belong to a single block.\n For any value that is being used in multiple blocks, it has to be referred\n by a Var which is defined in a block, whose scope is the least common ancestor\n of blocks this value is used.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that transforms an expression into Basic Block Normal Form.\n ' return _ffi_api.ToBasicBlockNormalForm()
def ToBasicBlockNormalForm(): 'Turn an expression to Basic Block Normal Form.\n We define a block as a group of expressions implied by the scope structure.\n Each graph node can only belong to a single block.\n For any value that is being used in multiple blocks, it has to be referred\n by a Var which is defined in a block, whose scope is the least common ancestor\n of blocks this value is used.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that transforms an expression into Basic Block Normal Form.\n ' return _ffi_api.ToBasicBlockNormalForm()<|docstring|>Turn an expression to Basic Block Normal Form. We define a block as a group of expressions implied by the scope structure. Each graph node can only belong to a single block. For any value that is being used in multiple blocks, it has to be referred by a Var which is defined in a block, whose scope is the least common ancestor of blocks this value is used. Returns ------- ret: tvm.transform.Pass The registered pass that transforms an expression into Basic Block Normal Form.<|endoftext|>
ef6db505eabe47bbf60602f50018ef9f1957f885d482ce0b9b4549adc677e897
def ToCPS(expr, mod=None): '\n Turn expression into continuation passing style(CPS).\n\n Every intermediate compute will be passed to a continuation.\n\n Returns\n -------\n result: tvm.transform.Pass\n The registered pass that transforms an expression into CPS.\n ' return _ffi_api.to_cps(expr, mod)
Turn expression into continuation passing style(CPS). Every intermediate compute will be passed to a continuation. Returns ------- result: tvm.transform.Pass The registered pass that transforms an expression into CPS.
python/tvm/relay/transform/transform.py
ToCPS
ryanstout/tvm
2,084
python
def ToCPS(expr, mod=None): '\n Turn expression into continuation passing style(CPS).\n\n Every intermediate compute will be passed to a continuation.\n\n Returns\n -------\n result: tvm.transform.Pass\n The registered pass that transforms an expression into CPS.\n ' return _ffi_api.to_cps(expr, mod)
def ToCPS(expr, mod=None): '\n Turn expression into continuation passing style(CPS).\n\n Every intermediate compute will be passed to a continuation.\n\n Returns\n -------\n result: tvm.transform.Pass\n The registered pass that transforms an expression into CPS.\n ' return _ffi_api.to_cps(expr, mod)<|docstring|>Turn expression into continuation passing style(CPS). Every intermediate compute will be passed to a continuation. Returns ------- result: tvm.transform.Pass The registered pass that transforms an expression into CPS.<|endoftext|>
28eece49ac3c359d7da65e31ae75d4e395600c5500cd0be7c15141591da1c613
def EtaExpand(expand_constructor=False, expand_global_var=False): 'Add abstraction over a constructor or global variable bound to a function\n\n Parameters\n ----------\n expand_constructor: bool\n Whether to expand constructors.\n\n expand_global_var: bool\n Whether to expand global variables.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eta expands an expression.\n ' return _ffi_api.EtaExpand(expand_constructor, expand_global_var)
Add abstraction over a constructor or global variable bound to a function Parameters ---------- expand_constructor: bool Whether to expand constructors. expand_global_var: bool Whether to expand global variables. Returns ------- ret: tvm.transform.Pass The registered pass that eta expands an expression.
python/tvm/relay/transform/transform.py
EtaExpand
ryanstout/tvm
2,084
python
def EtaExpand(expand_constructor=False, expand_global_var=False): 'Add abstraction over a constructor or global variable bound to a function\n\n Parameters\n ----------\n expand_constructor: bool\n Whether to expand constructors.\n\n expand_global_var: bool\n Whether to expand global variables.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eta expands an expression.\n ' return _ffi_api.EtaExpand(expand_constructor, expand_global_var)
def EtaExpand(expand_constructor=False, expand_global_var=False): 'Add abstraction over a constructor or global variable bound to a function\n\n Parameters\n ----------\n expand_constructor: bool\n Whether to expand constructors.\n\n expand_global_var: bool\n Whether to expand global variables.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that eta expands an expression.\n ' return _ffi_api.EtaExpand(expand_constructor, expand_global_var)<|docstring|>Add abstraction over a constructor or global variable bound to a function Parameters ---------- expand_constructor: bool Whether to expand constructors. expand_global_var: bool Whether to expand global variables. Returns ------- ret: tvm.transform.Pass The registered pass that eta expands an expression.<|endoftext|>
ff42b8aea15fe85a462f463fa320a4b08c6f1258b9f8d45e5226d5bd73394543
def ToGraphNormalForm(): 'Turn a Relay program in A Normal Form into Graph Normal Form\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that transforms an expression into Graph Normal Form.\n ' return _ffi_api.ToGraphNormalForm()
Turn a Relay program in A Normal Form into Graph Normal Form Returns ------- ret : tvm.transform.Pass The registered pass that transforms an expression into Graph Normal Form.
python/tvm/relay/transform/transform.py
ToGraphNormalForm
ryanstout/tvm
2,084
python
def ToGraphNormalForm(): 'Turn a Relay program in A Normal Form into Graph Normal Form\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that transforms an expression into Graph Normal Form.\n ' return _ffi_api.ToGraphNormalForm()
def ToGraphNormalForm(): 'Turn a Relay program in A Normal Form into Graph Normal Form\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that transforms an expression into Graph Normal Form.\n ' return _ffi_api.ToGraphNormalForm()<|docstring|>Turn a Relay program in A Normal Form into Graph Normal Form Returns ------- ret : tvm.transform.Pass The registered pass that transforms an expression into Graph Normal Form.<|endoftext|>
be0613ec5f58ecab6b68791dda1ed06361efbc43487dbfdaa893e5c04c04080b
def EliminateCommonSubexpr(fskip=None): 'Eliminate common subexpressions.\n\n Parameters\n ----------\n fskip: Callable\n The callback function that decides whether an expression should be\n skipped.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that eliminates common subexpressions.\n ' return _ffi_api.EliminateCommonSubexpr(fskip)
Eliminate common subexpressions. Parameters ---------- fskip: Callable The callback function that decides whether an expression should be skipped. Returns ------- ret : tvm.transform.Pass The registered pass that eliminates common subexpressions.
python/tvm/relay/transform/transform.py
EliminateCommonSubexpr
ryanstout/tvm
2,084
python
def EliminateCommonSubexpr(fskip=None): 'Eliminate common subexpressions.\n\n Parameters\n ----------\n fskip: Callable\n The callback function that decides whether an expression should be\n skipped.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that eliminates common subexpressions.\n ' return _ffi_api.EliminateCommonSubexpr(fskip)
def EliminateCommonSubexpr(fskip=None): 'Eliminate common subexpressions.\n\n Parameters\n ----------\n fskip: Callable\n The callback function that decides whether an expression should be\n skipped.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that eliminates common subexpressions.\n ' return _ffi_api.EliminateCommonSubexpr(fskip)<|docstring|>Eliminate common subexpressions. Parameters ---------- fskip: Callable The callback function that decides whether an expression should be skipped. Returns ------- ret : tvm.transform.Pass The registered pass that eliminates common subexpressions.<|endoftext|>
7e6b22d6efa8577169e6ece8d2c9f08670188f3dc79e0e4a29e810f6f66f28a5
def PartialEvaluate(): 'Evaluate the static fragment of the code.\n\n Note\n ----\n This transformation could be either `Module -> Module` or `Expr -> Expr`.\n It will directly transform the input expression to a new one if the target\n expression is provided. Otherwise, it will rely on the pass manager to\n carry out transformation.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs partial evaluation on an expression.\n ' return _ffi_api.PartialEvaluate()
Evaluate the static fragment of the code. Note ---- This transformation could be either `Module -> Module` or `Expr -> Expr`. It will directly transform the input expression to a new one if the target expression is provided. Otherwise, it will rely on the pass manager to carry out transformation. Returns ------- ret: tvm.transform.Pass The registered pass that performs partial evaluation on an expression.
python/tvm/relay/transform/transform.py
PartialEvaluate
ryanstout/tvm
2,084
python
def PartialEvaluate(): 'Evaluate the static fragment of the code.\n\n Note\n ----\n This transformation could be either `Module -> Module` or `Expr -> Expr`.\n It will directly transform the input expression to a new one if the target\n expression is provided. Otherwise, it will rely on the pass manager to\n carry out transformation.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs partial evaluation on an expression.\n ' return _ffi_api.PartialEvaluate()
def PartialEvaluate(): 'Evaluate the static fragment of the code.\n\n Note\n ----\n This transformation could be either `Module -> Module` or `Expr -> Expr`.\n It will directly transform the input expression to a new one if the target\n expression is provided. Otherwise, it will rely on the pass manager to\n carry out transformation.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs partial evaluation on an expression.\n ' return _ffi_api.PartialEvaluate()<|docstring|>Evaluate the static fragment of the code. Note ---- This transformation could be either `Module -> Module` or `Expr -> Expr`. It will directly transform the input expression to a new one if the target expression is provided. Otherwise, it will rely on the pass manager to carry out transformation. Returns ------- ret: tvm.transform.Pass The registered pass that performs partial evaluation on an expression.<|endoftext|>
a0b46e1bc2a094d3bc671c51556c77f953aab251232502048d73a6fe33261508
def CanonicalizeCast(): '\n Canonicalize cast expressions to make operator fusion more efficient.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that canonicalizes cast expression.\n ' return _ffi_api.CanonicalizeCast()
Canonicalize cast expressions to make operator fusion more efficient. Returns ------- ret : tvm.transform.Pass The registered pass that canonicalizes cast expression.
python/tvm/relay/transform/transform.py
CanonicalizeCast
ryanstout/tvm
2,084
python
def CanonicalizeCast(): '\n Canonicalize cast expressions to make operator fusion more efficient.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that canonicalizes cast expression.\n ' return _ffi_api.CanonicalizeCast()
def CanonicalizeCast(): '\n Canonicalize cast expressions to make operator fusion more efficient.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that canonicalizes cast expression.\n ' return _ffi_api.CanonicalizeCast()<|docstring|>Canonicalize cast expressions to make operator fusion more efficient. Returns ------- ret : tvm.transform.Pass The registered pass that canonicalizes cast expression.<|endoftext|>
bcb2a0fb3ed792b5df7c76afc8b007723bca703b6dd73e8e60e359b9468eb2e4
def LambdaLift(): '\n Lift the closure to global function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that lifts the lambda function.\n ' return _ffi_api.LambdaLift()
Lift the closure to global function. Returns ------- ret : tvm.transform.Pass The registered pass that lifts the lambda function.
python/tvm/relay/transform/transform.py
LambdaLift
ryanstout/tvm
2,084
python
def LambdaLift(): '\n Lift the closure to global function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that lifts the lambda function.\n ' return _ffi_api.LambdaLift()
def LambdaLift(): '\n Lift the closure to global function.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass that lifts the lambda function.\n ' return _ffi_api.LambdaLift()<|docstring|>Lift the closure to global function. Returns ------- ret : tvm.transform.Pass The registered pass that lifts the lambda function.<|endoftext|>
8cca06485b237a836d3f37f6ba509c665872483ced9a10f4ef83d4c7853dc482
def PartitionGraph(mod_name='default', bind_constants=True): 'Partition a Relay program into regions that can be executed on different\n backends.\n\n Parameters\n ----------\n mod_name : string\n Controls the prefix of the name of each partitioned subraph.\n If `mod_name` is None, then `tvmgen_` prefix is used.\n Otherwise, `tvmgen_mod_name_` prefix is used.\n\n bind_constants: bool\n Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs\n to maintain the bound constants; Otherwise the constants will be maintained by\n the metadata module. So it is recommended for C-source based codegens to\n set bind_constants=False to avoid embedding large constants in a C source file.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that partitions the Relay program.\n ' mod_name = mangle_module_name(mod_name) return _ffi_api.PartitionGraph(mod_name, bind_constants)
Partition a Relay program into regions that can be executed on different backends. Parameters ---------- mod_name : string Controls the prefix of the name of each partitioned subraph. If `mod_name` is None, then `tvmgen_` prefix is used. Otherwise, `tvmgen_mod_name_` prefix is used. bind_constants: bool Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs to maintain the bound constants; Otherwise the constants will be maintained by the metadata module. So it is recommended for C-source based codegens to set bind_constants=False to avoid embedding large constants in a C source file. Returns ------- ret: tvm.transform.Pass The registered pass that partitions the Relay program.
python/tvm/relay/transform/transform.py
PartitionGraph
ryanstout/tvm
2,084
python
def PartitionGraph(mod_name='default', bind_constants=True): 'Partition a Relay program into regions that can be executed on different\n backends.\n\n Parameters\n ----------\n mod_name : string\n Controls the prefix of the name of each partitioned subraph.\n If `mod_name` is None, then `tvmgen_` prefix is used.\n Otherwise, `tvmgen_mod_name_` prefix is used.\n\n bind_constants: bool\n Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs\n to maintain the bound constants; Otherwise the constants will be maintained by\n the metadata module. So it is recommended for C-source based codegens to\n set bind_constants=False to avoid embedding large constants in a C source file.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that partitions the Relay program.\n ' mod_name = mangle_module_name(mod_name) return _ffi_api.PartitionGraph(mod_name, bind_constants)
def PartitionGraph(mod_name='default', bind_constants=True): 'Partition a Relay program into regions that can be executed on different\n backends.\n\n Parameters\n ----------\n mod_name : string\n Controls the prefix of the name of each partitioned subraph.\n If `mod_name` is None, then `tvmgen_` prefix is used.\n Otherwise, `tvmgen_mod_name_` prefix is used.\n\n bind_constants: bool\n Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs\n to maintain the bound constants; Otherwise the constants will be maintained by\n the metadata module. So it is recommended for C-source based codegens to\n set bind_constants=False to avoid embedding large constants in a C source file.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that partitions the Relay program.\n ' mod_name = mangle_module_name(mod_name) return _ffi_api.PartitionGraph(mod_name, bind_constants)<|docstring|>Partition a Relay program into regions that can be executed on different backends. Parameters ---------- mod_name : string Controls the prefix of the name of each partitioned subraph. If `mod_name` is None, then `tvmgen_` prefix is used. Otherwise, `tvmgen_mod_name_` prefix is used. bind_constants: bool Whether or not to bind constants in partitioned subgraphs. Note that the codegen needs to maintain the bound constants; Otherwise the constants will be maintained by the metadata module. So it is recommended for C-source based codegens to set bind_constants=False to avoid embedding large constants in a C source file. Returns ------- ret: tvm.transform.Pass The registered pass that partitions the Relay program.<|endoftext|>
591cee9e53b1e4845d251302026e0aa0e811b20cedf7bf06f25a2d272471cb57
def AnnotateTarget(targets, include_non_call_ops=True): 'Annotate ops in an experession with a provied compiler/target and then\n use it for codegen.\n\n Parameters\n ----------\n targets : str or List[str]\n The list of target compilers used for codegen.\n include_non_call_ops : boolean\n If True then non-call ops also will be annotated with targets\n If False then non-call ops will not be processed\n\n Returns\n -------\n ret : tvm.transform.Pass\n The annotated pass that wrapps ops with subgraph_start and\n subgraph_end.\n ' if isinstance(targets, str): targets = [targets] return _ffi_api.AnnotateTarget([tvm.runtime.container.String(t) for t in targets], include_non_call_ops)
Annotate ops in an experession with a provied compiler/target and then use it for codegen. Parameters ---------- targets : str or List[str] The list of target compilers used for codegen. include_non_call_ops : boolean If True then non-call ops also will be annotated with targets If False then non-call ops will not be processed Returns ------- ret : tvm.transform.Pass The annotated pass that wrapps ops with subgraph_start and subgraph_end.
python/tvm/relay/transform/transform.py
AnnotateTarget
ryanstout/tvm
2,084
python
def AnnotateTarget(targets, include_non_call_ops=True): 'Annotate ops in an experession with a provied compiler/target and then\n use it for codegen.\n\n Parameters\n ----------\n targets : str or List[str]\n The list of target compilers used for codegen.\n include_non_call_ops : boolean\n If True then non-call ops also will be annotated with targets\n If False then non-call ops will not be processed\n\n Returns\n -------\n ret : tvm.transform.Pass\n The annotated pass that wrapps ops with subgraph_start and\n subgraph_end.\n ' if isinstance(targets, str): targets = [targets] return _ffi_api.AnnotateTarget([tvm.runtime.container.String(t) for t in targets], include_non_call_ops)
def AnnotateTarget(targets, include_non_call_ops=True): 'Annotate ops in an experession with a provied compiler/target and then\n use it for codegen.\n\n Parameters\n ----------\n targets : str or List[str]\n The list of target compilers used for codegen.\n include_non_call_ops : boolean\n If True then non-call ops also will be annotated with targets\n If False then non-call ops will not be processed\n\n Returns\n -------\n ret : tvm.transform.Pass\n The annotated pass that wrapps ops with subgraph_start and\n subgraph_end.\n ' if isinstance(targets, str): targets = [targets] return _ffi_api.AnnotateTarget([tvm.runtime.container.String(t) for t in targets], include_non_call_ops)<|docstring|>Annotate ops in an experession with a provied compiler/target and then use it for codegen. Parameters ---------- targets : str or List[str] The list of target compilers used for codegen. include_non_call_ops : boolean If True then non-call ops also will be annotated with targets If False then non-call ops will not be processed Returns ------- ret : tvm.transform.Pass The annotated pass that wrapps ops with subgraph_start and subgraph_end.<|endoftext|>
d5881bb56504386455de5e309dde66d100224556fcbc1b7e022c03b932eb6722
def DynamicToStatic(): 'If possible, convert tvm.relay.dynamic* ops to static versions\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for dynamic->static conversion.\n ' return _ffi_api.DynamicToStatic()
If possible, convert tvm.relay.dynamic* ops to static versions Returns ------- ret : tvm.transform.Pass The registered pass for dynamic->static conversion.
python/tvm/relay/transform/transform.py
DynamicToStatic
ryanstout/tvm
2,084
python
def DynamicToStatic(): 'If possible, convert tvm.relay.dynamic* ops to static versions\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for dynamic->static conversion.\n ' return _ffi_api.DynamicToStatic()
def DynamicToStatic(): 'If possible, convert tvm.relay.dynamic* ops to static versions\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered pass for dynamic->static conversion.\n ' return _ffi_api.DynamicToStatic()<|docstring|>If possible, convert tvm.relay.dynamic* ops to static versions Returns ------- ret : tvm.transform.Pass The registered pass for dynamic->static conversion.<|endoftext|>
e41eb81ba196e0e5e2377a95e3233ab6cb9b15ee0559568f3270fec8865527d9
def Inline(): 'Perform inlining on the given Relay IR module. The global functions that\n are marked as `inline` should be always inlined. A cost model will be\n needed in the future to decide if it is profitable to inline the function.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs inlining for a Relay IR module.\n ' return _ffi_api.Inline()
Perform inlining on the given Relay IR module. The global functions that are marked as `inline` should be always inlined. A cost model will be needed in the future to decide if it is profitable to inline the function. Returns ------- ret: tvm.transform.Pass The registered pass that performs inlining for a Relay IR module.
python/tvm/relay/transform/transform.py
Inline
ryanstout/tvm
2,084
python
def Inline(): 'Perform inlining on the given Relay IR module. The global functions that\n are marked as `inline` should be always inlined. A cost model will be\n needed in the future to decide if it is profitable to inline the function.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs inlining for a Relay IR module.\n ' return _ffi_api.Inline()
def Inline(): 'Perform inlining on the given Relay IR module. The global functions that\n are marked as `inline` should be always inlined. A cost model will be\n needed in the future to decide if it is profitable to inline the function.\n\n Returns\n -------\n ret: tvm.transform.Pass\n The registered pass that performs inlining for a Relay IR module.\n ' return _ffi_api.Inline()<|docstring|>Perform inlining on the given Relay IR module. The global functions that are marked as `inline` should be always inlined. A cost model will be needed in the future to decide if it is profitable to inline the function. Returns ------- ret: tvm.transform.Pass The registered pass that performs inlining for a Relay IR module.<|endoftext|>
14e2fd2cbb5c656b09f730fd195baaa764987e6ae9d0384fcfbff9ef6483d66b
def gradient(expr, mod=None, mode='higher_order'): "\n Transform the input function,\n returning a function that calculate the original result,\n paired with gradient of the input.\n\n Parameters\n ----------\n expr : tvm.relay.Expr\n The input expression, which is a Function or a GlobalVar.\n\n mod : Optional[tvm.IRModule]\n\n mode : Optional[String]\n The mode of the automatic differentiation algorithm.\n 'first_order' only works on first order code, but will not produce\n reference nor closure.\n 'higher_order' works on all code using reference and closure.\n\n Returns\n -------\n expr : tvm.relay.Expr\n The transformed expression.\n " if (mode == 'first_order'): warnings.warn('using transform.gradient for first-order AD is deprecated, please use theFirstOrderGradient module pass', DeprecationWarning) if (mod is not None): raise RuntimeError('to run first-order AD on a module, please use the FirstOrderGradient module pass.') return FirstOrderGradient()(tvm.IRModule.from_expr(expr))['main'] if (mode == 'higher_order'): return _ffi_api.gradient(expr, mod) raise Exception('unknown mode')
Transform the input function, returning a function that calculate the original result, paired with gradient of the input. Parameters ---------- expr : tvm.relay.Expr The input expression, which is a Function or a GlobalVar. mod : Optional[tvm.IRModule] mode : Optional[String] The mode of the automatic differentiation algorithm. 'first_order' only works on first order code, but will not produce reference nor closure. 'higher_order' works on all code using reference and closure. Returns ------- expr : tvm.relay.Expr The transformed expression.
python/tvm/relay/transform/transform.py
gradient
ryanstout/tvm
2,084
python
def gradient(expr, mod=None, mode='higher_order'): "\n Transform the input function,\n returning a function that calculate the original result,\n paired with gradient of the input.\n\n Parameters\n ----------\n expr : tvm.relay.Expr\n The input expression, which is a Function or a GlobalVar.\n\n mod : Optional[tvm.IRModule]\n\n mode : Optional[String]\n The mode of the automatic differentiation algorithm.\n 'first_order' only works on first order code, but will not produce\n reference nor closure.\n 'higher_order' works on all code using reference and closure.\n\n Returns\n -------\n expr : tvm.relay.Expr\n The transformed expression.\n " if (mode == 'first_order'): warnings.warn('using transform.gradient for first-order AD is deprecated, please use theFirstOrderGradient module pass', DeprecationWarning) if (mod is not None): raise RuntimeError('to run first-order AD on a module, please use the FirstOrderGradient module pass.') return FirstOrderGradient()(tvm.IRModule.from_expr(expr))['main'] if (mode == 'higher_order'): return _ffi_api.gradient(expr, mod) raise Exception('unknown mode')
def gradient(expr, mod=None, mode='higher_order'): "\n Transform the input function,\n returning a function that calculate the original result,\n paired with gradient of the input.\n\n Parameters\n ----------\n expr : tvm.relay.Expr\n The input expression, which is a Function or a GlobalVar.\n\n mod : Optional[tvm.IRModule]\n\n mode : Optional[String]\n The mode of the automatic differentiation algorithm.\n 'first_order' only works on first order code, but will not produce\n reference nor closure.\n 'higher_order' works on all code using reference and closure.\n\n Returns\n -------\n expr : tvm.relay.Expr\n The transformed expression.\n " if (mode == 'first_order'): warnings.warn('using transform.gradient for first-order AD is deprecated, please use theFirstOrderGradient module pass', DeprecationWarning) if (mod is not None): raise RuntimeError('to run first-order AD on a module, please use the FirstOrderGradient module pass.') return FirstOrderGradient()(tvm.IRModule.from_expr(expr))['main'] if (mode == 'higher_order'): return _ffi_api.gradient(expr, mod) raise Exception('unknown mode')<|docstring|>Transform the input function, returning a function that calculate the original result, paired with gradient of the input. Parameters ---------- expr : tvm.relay.Expr The input expression, which is a Function or a GlobalVar. mod : Optional[tvm.IRModule] mode : Optional[String] The mode of the automatic differentiation algorithm. 'first_order' only works on first order code, but will not produce reference nor closure. 'higher_order' works on all code using reference and closure. Returns ------- expr : tvm.relay.Expr The transformed expression.<|endoftext|>
5844eac2ab3498f6ffca120bb0e20550f13963694688c7f91e6162d1e230253b
def FirstOrderGradient(): '\n Transforms all global functions in the module to return the original result, paired with the\n gradients of the inputs. This pass transforms each global function independently and does not\n support interprocedural AD. Additionally, this pass does not support any control-flow or\n references, and should only be used on pure data-flow graphs.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered FirstOrderGradient pass.\n ' return _ffi_api.FirstOrderGradient()
Transforms all global functions in the module to return the original result, paired with the gradients of the inputs. This pass transforms each global function independently and does not support interprocedural AD. Additionally, this pass does not support any control-flow or references, and should only be used on pure data-flow graphs. Returns ------- ret : tvm.transform.Pass The registered FirstOrderGradient pass.
python/tvm/relay/transform/transform.py
FirstOrderGradient
ryanstout/tvm
2,084
python
def FirstOrderGradient(): '\n Transforms all global functions in the module to return the original result, paired with the\n gradients of the inputs. This pass transforms each global function independently and does not\n support interprocedural AD. Additionally, this pass does not support any control-flow or\n references, and should only be used on pure data-flow graphs.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered FirstOrderGradient pass.\n ' return _ffi_api.FirstOrderGradient()
def FirstOrderGradient(): '\n Transforms all global functions in the module to return the original result, paired with the\n gradients of the inputs. This pass transforms each global function independently and does not\n support interprocedural AD. Additionally, this pass does not support any control-flow or\n references, and should only be used on pure data-flow graphs.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered FirstOrderGradient pass.\n ' return _ffi_api.FirstOrderGradient()<|docstring|>Transforms all global functions in the module to return the original result, paired with the gradients of the inputs. This pass transforms each global function independently and does not support interprocedural AD. Additionally, this pass does not support any control-flow or references, and should only be used on pure data-flow graphs. Returns ------- ret : tvm.transform.Pass The registered FirstOrderGradient pass.<|endoftext|>
4e6377696240572ba9b334aa5a70156ed45055d6b48b6b9c2692e4323499910a
def Defunctionalization(func, mod): "\n Performs defunctionalization on func,\n transforming func from a higher-order program to a first-order program.\n\n At each call site, the function is cloned and type parameters are substituted in.\n Function arguments are encoded as datatypes\n and additional apply functions are used for application.\n\n Parameters\n ----------\n func : tvm.relay.Function\n The input function, which should not be polymorphic or be higher-order.\n This is because all types must be known and we can't encode function arguments\n to the program itself.\n\n mod : tvm.IRModule\n The IRModule containing function and type definitions,\n which is also mutated during this pass.\n\n Returns\n -------\n expr : tvm.relay.Function\n The output function.\n " return _ffi_api.Defunctionalization(func, mod)
Performs defunctionalization on func, transforming func from a higher-order program to a first-order program. At each call site, the function is cloned and type parameters are substituted in. Function arguments are encoded as datatypes and additional apply functions are used for application. Parameters ---------- func : tvm.relay.Function The input function, which should not be polymorphic or be higher-order. This is because all types must be known and we can't encode function arguments to the program itself. mod : tvm.IRModule The IRModule containing function and type definitions, which is also mutated during this pass. Returns ------- expr : tvm.relay.Function The output function.
python/tvm/relay/transform/transform.py
Defunctionalization
ryanstout/tvm
2,084
python
def Defunctionalization(func, mod): "\n Performs defunctionalization on func,\n transforming func from a higher-order program to a first-order program.\n\n At each call site, the function is cloned and type parameters are substituted in.\n Function arguments are encoded as datatypes\n and additional apply functions are used for application.\n\n Parameters\n ----------\n func : tvm.relay.Function\n The input function, which should not be polymorphic or be higher-order.\n This is because all types must be known and we can't encode function arguments\n to the program itself.\n\n mod : tvm.IRModule\n The IRModule containing function and type definitions,\n which is also mutated during this pass.\n\n Returns\n -------\n expr : tvm.relay.Function\n The output function.\n " return _ffi_api.Defunctionalization(func, mod)
def Defunctionalization(func, mod): "\n Performs defunctionalization on func,\n transforming func from a higher-order program to a first-order program.\n\n At each call site, the function is cloned and type parameters are substituted in.\n Function arguments are encoded as datatypes\n and additional apply functions are used for application.\n\n Parameters\n ----------\n func : tvm.relay.Function\n The input function, which should not be polymorphic or be higher-order.\n This is because all types must be known and we can't encode function arguments\n to the program itself.\n\n mod : tvm.IRModule\n The IRModule containing function and type definitions,\n which is also mutated during this pass.\n\n Returns\n -------\n expr : tvm.relay.Function\n The output function.\n " return _ffi_api.Defunctionalization(func, mod)<|docstring|>Performs defunctionalization on func, transforming func from a higher-order program to a first-order program. At each call site, the function is cloned and type parameters are substituted in. Function arguments are encoded as datatypes and additional apply functions are used for application. Parameters ---------- func : tvm.relay.Function The input function, which should not be polymorphic or be higher-order. This is because all types must be known and we can't encode function arguments to the program itself. mod : tvm.IRModule The IRModule containing function and type definitions, which is also mutated during this pass. Returns ------- expr : tvm.relay.Function The output function.<|endoftext|>
017ce03cf7f978473286e8390f0bf222f964a648aeaf428e6bc6aab4ce62b441
def to_cps(func, mod=None): '\n Turn expression into CPS expression.\n\n Every intermediate compute will be passed to a continuation.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function.\n\n mod: Optional[tvm.IRModule]\n The global module.\n\n Returns\n -------\n result: tvm.relay.Function\n The output function.\n ' use_mod = (mod if (mod is not None) else tvm.ir.IRModule()) return _ffi_api.to_cps(func, use_mod)
Turn expression into CPS expression. Every intermediate compute will be passed to a continuation. Parameters ---------- func: tvm.relay.Function The input function. mod: Optional[tvm.IRModule] The global module. Returns ------- result: tvm.relay.Function The output function.
python/tvm/relay/transform/transform.py
to_cps
ryanstout/tvm
2,084
python
def to_cps(func, mod=None): '\n Turn expression into CPS expression.\n\n Every intermediate compute will be passed to a continuation.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function.\n\n mod: Optional[tvm.IRModule]\n The global module.\n\n Returns\n -------\n result: tvm.relay.Function\n The output function.\n ' use_mod = (mod if (mod is not None) else tvm.ir.IRModule()) return _ffi_api.to_cps(func, use_mod)
def to_cps(func, mod=None): '\n Turn expression into CPS expression.\n\n Every intermediate compute will be passed to a continuation.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function.\n\n mod: Optional[tvm.IRModule]\n The global module.\n\n Returns\n -------\n result: tvm.relay.Function\n The output function.\n ' use_mod = (mod if (mod is not None) else tvm.ir.IRModule()) return _ffi_api.to_cps(func, use_mod)<|docstring|>Turn expression into CPS expression. Every intermediate compute will be passed to a continuation. Parameters ---------- func: tvm.relay.Function The input function. mod: Optional[tvm.IRModule] The global module. Returns ------- result: tvm.relay.Function The output function.<|endoftext|>
27963b974b2912593046ec770e38c4801b7930194b879467d48725b47051c37a
def un_cps(func): '\n Turn an cps function into a Function without the continuation argument.\n\n Note that this will not give the exact same interface as before cps:\n If the input/output is higher order, they will still be in cps form.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function\n\n Returns\n -------\n result: tvm.relay.Function\n The output function\n ' return _ffi_api.un_cps(func)
Turn an cps function into a Function without the continuation argument. Note that this will not give the exact same interface as before cps: If the input/output is higher order, they will still be in cps form. Parameters ---------- func: tvm.relay.Function The input function Returns ------- result: tvm.relay.Function The output function
python/tvm/relay/transform/transform.py
un_cps
ryanstout/tvm
2,084
python
def un_cps(func): '\n Turn an cps function into a Function without the continuation argument.\n\n Note that this will not give the exact same interface as before cps:\n If the input/output is higher order, they will still be in cps form.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function\n\n Returns\n -------\n result: tvm.relay.Function\n The output function\n ' return _ffi_api.un_cps(func)
def un_cps(func): '\n Turn an cps function into a Function without the continuation argument.\n\n Note that this will not give the exact same interface as before cps:\n If the input/output is higher order, they will still be in cps form.\n\n Parameters\n ----------\n func: tvm.relay.Function\n The input function\n\n Returns\n -------\n result: tvm.relay.Function\n The output function\n ' return _ffi_api.un_cps(func)<|docstring|>Turn an cps function into a Function without the continuation argument. Note that this will not give the exact same interface as before cps: If the input/output is higher order, they will still be in cps form. Parameters ---------- func: tvm.relay.Function The input function Returns ------- result: tvm.relay.Function The output function<|endoftext|>
7224869d50e2cc0eb87d827dcfe477e1382f147e119fb6528dd88c10d8d0948b
def _wrap_class_function_pass(pass_cls, pass_info): 'Wrap a python class as function pass' class PyFunctionPass(FunctionPass): 'Internal wrapper class to create a class instance.' def __init__(self, *args, **kwargs): self.handle = None inst = pass_cls(*args, **kwargs) def _pass_func(func, mod, ctx): return inst.transform_function(func, mod, ctx) self.__init_handle_by_constructor__(_ffi_api.MakeFunctionPass, _pass_func, pass_info) self._inst = inst def __getattr__(self, name): return self._inst.__getattribute__(name) functools.update_wrapper(PyFunctionPass.__init__, pass_cls.__init__) PyFunctionPass.__name__ = pass_cls.__name__ PyFunctionPass.__doc__ = pass_cls.__doc__ PyFunctionPass.__module__ = pass_cls.__module__ return PyFunctionPass
Wrap a python class as function pass
python/tvm/relay/transform/transform.py
_wrap_class_function_pass
ryanstout/tvm
2,084
python
def _wrap_class_function_pass(pass_cls, pass_info): class PyFunctionPass(FunctionPass): 'Internal wrapper class to create a class instance.' def __init__(self, *args, **kwargs): self.handle = None inst = pass_cls(*args, **kwargs) def _pass_func(func, mod, ctx): return inst.transform_function(func, mod, ctx) self.__init_handle_by_constructor__(_ffi_api.MakeFunctionPass, _pass_func, pass_info) self._inst = inst def __getattr__(self, name): return self._inst.__getattribute__(name) functools.update_wrapper(PyFunctionPass.__init__, pass_cls.__init__) PyFunctionPass.__name__ = pass_cls.__name__ PyFunctionPass.__doc__ = pass_cls.__doc__ PyFunctionPass.__module__ = pass_cls.__module__ return PyFunctionPass
def _wrap_class_function_pass(pass_cls, pass_info): class PyFunctionPass(FunctionPass): 'Internal wrapper class to create a class instance.' def __init__(self, *args, **kwargs): self.handle = None inst = pass_cls(*args, **kwargs) def _pass_func(func, mod, ctx): return inst.transform_function(func, mod, ctx) self.__init_handle_by_constructor__(_ffi_api.MakeFunctionPass, _pass_func, pass_info) self._inst = inst def __getattr__(self, name): return self._inst.__getattribute__(name) functools.update_wrapper(PyFunctionPass.__init__, pass_cls.__init__) PyFunctionPass.__name__ = pass_cls.__name__ PyFunctionPass.__doc__ = pass_cls.__doc__ PyFunctionPass.__module__ = pass_cls.__module__ return PyFunctionPass<|docstring|>Wrap a python class as function pass<|endoftext|>
488833a0ac98d3b60f2c1f541f150ef23de5253f4f135a176ef615d5eaa4e208
def function_pass(pass_func=None, opt_level=None, name=None, required=None): 'Decorate a function pass.\n\n This function returns a callback when pass_func\n is provided. Otherwise, it returns the created function pass using the\n given optimization function.\n\n Parameters\n ----------\n pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]]\n The transformation function or class.\n\n opt_level : int\n The optimization level of this module pass.\n\n name : Optional[str]\n The name of the function pass. The name could be empty. In this case, the\n name of the optimization function will be used as the pass name.\n\n required : Optional[List[str]]\n The list of passes that the module pass is dependent on.\n\n Returns\n -------\n create_function_pass : Union[Callable, FunctionPass]\n\n A decorator will be returned if pass_func is not provided,\n otherwise return the decorated result.\n The returned decorator has two behaviors depending on the input:\n A new FunctionPass will be returned when we decorate a pass function.\n A new FunctionPass class will be returned when we decorate a class type.\n\n Examples\n --------\n The following code block decorates a function pass class.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=1)\n class TestReplaceFunc:\n def __init__(self, new_func):\n self.new_func = new_func\n\n def transform_function(self, func, mod, ctx):\n # just for demo purposes\n # transform func to new_func\n return self.new_func\n\n x = relay.var("x", shape=(10, 20))\n f1 = relay.Function([x], x)\n f2 = relay.Function([x], relay.log(x))\n # fpass is now a special pass that replaces every\n # function to f1\n fpass = TestReplaceFunc(f1)\n # now every function in input_mod is replaced by f1\n res_mod = fpass(input_mod)\n\n\n The following code creates a function pass by decorating\n a user defined transform function.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=2)\n def transform(func, mod, ctx):\n # my transformations here.\n return func\n\n function_pass = transform\n assert isinstance(function_pass, transform.FunctionPass)\n assert function_pass.info.opt_level == 2\n\n # Given a module m, the optimization could be invoked as the follwoing:\n updated_mod = function_pass(m)\n # Now constant folding should have been applied to every function in\n # the provided module m. And the updated module will be returned.\n ' if (opt_level is None): raise ValueError('Please provide opt_level for the function pass.') required = (required if required else []) if (not isinstance(required, (list, tuple))): raise TypeError(('Required is expected to be the type of ' + 'list/tuple.')) def create_function_pass(pass_arg): 'Internal function that creates a function pass' fname = (name if name else pass_arg.__name__) info = tvm.transform.PassInfo(opt_level, fname, required) if inspect.isclass(pass_arg): return _wrap_class_function_pass(pass_arg, info) if (not isinstance(pass_arg, (types.FunctionType, types.LambdaType))): raise TypeError('pass_func must be a callable for Module pass') return _ffi_api.MakeFunctionPass(pass_arg, info) if pass_func: return create_function_pass(pass_func) return create_function_pass
Decorate a function pass. This function returns a callback when pass_func is provided. Otherwise, it returns the created function pass using the given optimization function. Parameters ---------- pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]] The transformation function or class. opt_level : int The optimization level of this module pass. name : Optional[str] The name of the function pass. The name could be empty. In this case, the name of the optimization function will be used as the pass name. required : Optional[List[str]] The list of passes that the module pass is dependent on. Returns ------- create_function_pass : Union[Callable, FunctionPass] A decorator will be returned if pass_func is not provided, otherwise return the decorated result. The returned decorator has two behaviors depending on the input: A new FunctionPass will be returned when we decorate a pass function. A new FunctionPass class will be returned when we decorate a class type. Examples -------- The following code block decorates a function pass class. .. code-block:: python @relay.transform.function_pass(opt_level=1) class TestReplaceFunc: def __init__(self, new_func): self.new_func = new_func def transform_function(self, func, mod, ctx): # just for demo purposes # transform func to new_func return self.new_func x = relay.var("x", shape=(10, 20)) f1 = relay.Function([x], x) f2 = relay.Function([x], relay.log(x)) # fpass is now a special pass that replaces every # function to f1 fpass = TestReplaceFunc(f1) # now every function in input_mod is replaced by f1 res_mod = fpass(input_mod) The following code creates a function pass by decorating a user defined transform function. .. code-block:: python @relay.transform.function_pass(opt_level=2) def transform(func, mod, ctx): # my transformations here. return func function_pass = transform assert isinstance(function_pass, transform.FunctionPass) assert function_pass.info.opt_level == 2 # Given a module m, the optimization could be invoked as the follwoing: updated_mod = function_pass(m) # Now constant folding should have been applied to every function in # the provided module m. And the updated module will be returned.
python/tvm/relay/transform/transform.py
function_pass
ryanstout/tvm
2,084
python
def function_pass(pass_func=None, opt_level=None, name=None, required=None): 'Decorate a function pass.\n\n This function returns a callback when pass_func\n is provided. Otherwise, it returns the created function pass using the\n given optimization function.\n\n Parameters\n ----------\n pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]]\n The transformation function or class.\n\n opt_level : int\n The optimization level of this module pass.\n\n name : Optional[str]\n The name of the function pass. The name could be empty. In this case, the\n name of the optimization function will be used as the pass name.\n\n required : Optional[List[str]]\n The list of passes that the module pass is dependent on.\n\n Returns\n -------\n create_function_pass : Union[Callable, FunctionPass]\n\n A decorator will be returned if pass_func is not provided,\n otherwise return the decorated result.\n The returned decorator has two behaviors depending on the input:\n A new FunctionPass will be returned when we decorate a pass function.\n A new FunctionPass class will be returned when we decorate a class type.\n\n Examples\n --------\n The following code block decorates a function pass class.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=1)\n class TestReplaceFunc:\n def __init__(self, new_func):\n self.new_func = new_func\n\n def transform_function(self, func, mod, ctx):\n # just for demo purposes\n # transform func to new_func\n return self.new_func\n\n x = relay.var("x", shape=(10, 20))\n f1 = relay.Function([x], x)\n f2 = relay.Function([x], relay.log(x))\n # fpass is now a special pass that replaces every\n # function to f1\n fpass = TestReplaceFunc(f1)\n # now every function in input_mod is replaced by f1\n res_mod = fpass(input_mod)\n\n\n The following code creates a function pass by decorating\n a user defined transform function.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=2)\n def transform(func, mod, ctx):\n # my transformations here.\n return func\n\n function_pass = transform\n assert isinstance(function_pass, transform.FunctionPass)\n assert function_pass.info.opt_level == 2\n\n # Given a module m, the optimization could be invoked as the follwoing:\n updated_mod = function_pass(m)\n # Now constant folding should have been applied to every function in\n # the provided module m. And the updated module will be returned.\n ' if (opt_level is None): raise ValueError('Please provide opt_level for the function pass.') required = (required if required else []) if (not isinstance(required, (list, tuple))): raise TypeError(('Required is expected to be the type of ' + 'list/tuple.')) def create_function_pass(pass_arg): 'Internal function that creates a function pass' fname = (name if name else pass_arg.__name__) info = tvm.transform.PassInfo(opt_level, fname, required) if inspect.isclass(pass_arg): return _wrap_class_function_pass(pass_arg, info) if (not isinstance(pass_arg, (types.FunctionType, types.LambdaType))): raise TypeError('pass_func must be a callable for Module pass') return _ffi_api.MakeFunctionPass(pass_arg, info) if pass_func: return create_function_pass(pass_func) return create_function_pass
def function_pass(pass_func=None, opt_level=None, name=None, required=None): 'Decorate a function pass.\n\n This function returns a callback when pass_func\n is provided. Otherwise, it returns the created function pass using the\n given optimization function.\n\n Parameters\n ----------\n pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]]\n The transformation function or class.\n\n opt_level : int\n The optimization level of this module pass.\n\n name : Optional[str]\n The name of the function pass. The name could be empty. In this case, the\n name of the optimization function will be used as the pass name.\n\n required : Optional[List[str]]\n The list of passes that the module pass is dependent on.\n\n Returns\n -------\n create_function_pass : Union[Callable, FunctionPass]\n\n A decorator will be returned if pass_func is not provided,\n otherwise return the decorated result.\n The returned decorator has two behaviors depending on the input:\n A new FunctionPass will be returned when we decorate a pass function.\n A new FunctionPass class will be returned when we decorate a class type.\n\n Examples\n --------\n The following code block decorates a function pass class.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=1)\n class TestReplaceFunc:\n def __init__(self, new_func):\n self.new_func = new_func\n\n def transform_function(self, func, mod, ctx):\n # just for demo purposes\n # transform func to new_func\n return self.new_func\n\n x = relay.var("x", shape=(10, 20))\n f1 = relay.Function([x], x)\n f2 = relay.Function([x], relay.log(x))\n # fpass is now a special pass that replaces every\n # function to f1\n fpass = TestReplaceFunc(f1)\n # now every function in input_mod is replaced by f1\n res_mod = fpass(input_mod)\n\n\n The following code creates a function pass by decorating\n a user defined transform function.\n\n .. code-block:: python\n\n @relay.transform.function_pass(opt_level=2)\n def transform(func, mod, ctx):\n # my transformations here.\n return func\n\n function_pass = transform\n assert isinstance(function_pass, transform.FunctionPass)\n assert function_pass.info.opt_level == 2\n\n # Given a module m, the optimization could be invoked as the follwoing:\n updated_mod = function_pass(m)\n # Now constant folding should have been applied to every function in\n # the provided module m. And the updated module will be returned.\n ' if (opt_level is None): raise ValueError('Please provide opt_level for the function pass.') required = (required if required else []) if (not isinstance(required, (list, tuple))): raise TypeError(('Required is expected to be the type of ' + 'list/tuple.')) def create_function_pass(pass_arg): 'Internal function that creates a function pass' fname = (name if name else pass_arg.__name__) info = tvm.transform.PassInfo(opt_level, fname, required) if inspect.isclass(pass_arg): return _wrap_class_function_pass(pass_arg, info) if (not isinstance(pass_arg, (types.FunctionType, types.LambdaType))): raise TypeError('pass_func must be a callable for Module pass') return _ffi_api.MakeFunctionPass(pass_arg, info) if pass_func: return create_function_pass(pass_func) return create_function_pass<|docstring|>Decorate a function pass. This function returns a callback when pass_func is provided. Otherwise, it returns the created function pass using the given optimization function. Parameters ---------- pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]] The transformation function or class. opt_level : int The optimization level of this module pass. name : Optional[str] The name of the function pass. The name could be empty. In this case, the name of the optimization function will be used as the pass name. required : Optional[List[str]] The list of passes that the module pass is dependent on. Returns ------- create_function_pass : Union[Callable, FunctionPass] A decorator will be returned if pass_func is not provided, otherwise return the decorated result. The returned decorator has two behaviors depending on the input: A new FunctionPass will be returned when we decorate a pass function. A new FunctionPass class will be returned when we decorate a class type. Examples -------- The following code block decorates a function pass class. .. code-block:: python @relay.transform.function_pass(opt_level=1) class TestReplaceFunc: def __init__(self, new_func): self.new_func = new_func def transform_function(self, func, mod, ctx): # just for demo purposes # transform func to new_func return self.new_func x = relay.var("x", shape=(10, 20)) f1 = relay.Function([x], x) f2 = relay.Function([x], relay.log(x)) # fpass is now a special pass that replaces every # function to f1 fpass = TestReplaceFunc(f1) # now every function in input_mod is replaced by f1 res_mod = fpass(input_mod) The following code creates a function pass by decorating a user defined transform function. .. code-block:: python @relay.transform.function_pass(opt_level=2) def transform(func, mod, ctx): # my transformations here. return func function_pass = transform assert isinstance(function_pass, transform.FunctionPass) assert function_pass.info.opt_level == 2 # Given a module m, the optimization could be invoked as the follwoing: updated_mod = function_pass(m) # Now constant folding should have been applied to every function in # the provided module m. And the updated module will be returned.<|endoftext|>
7be60eab918d618241097c3566f0263c3e7b3bed7e0b16b3c04beb602d31cc70
def DenseToSparse(weight_name, weight_shape): '\n Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense```\n This pass is used in ```data_dep_optimization.bsr_dense```\n Parameters of this pass is generated by ```analysis.sparse_dense.process_params```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.DenseToSparse(weight_name, weight_shape)
Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense``` This pass is used in ```data_dep_optimization.bsr_dense``` Parameters of this pass is generated by ```analysis.sparse_dense.process_params``` Parameters ---------- weight_name: Array[String] Names of weights which qualified sparse contrains weight_shape: Array[Array[IntImm]] Weights shape in BSR format. Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.
python/tvm/relay/transform/transform.py
DenseToSparse
ryanstout/tvm
2,084
python
def DenseToSparse(weight_name, weight_shape): '\n Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense```\n This pass is used in ```data_dep_optimization.bsr_dense```\n Parameters of this pass is generated by ```analysis.sparse_dense.process_params```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.DenseToSparse(weight_name, weight_shape)
def DenseToSparse(weight_name, weight_shape): '\n Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense```\n This pass is used in ```data_dep_optimization.bsr_dense```\n Parameters of this pass is generated by ```analysis.sparse_dense.process_params```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.DenseToSparse(weight_name, weight_shape)<|docstring|>Rewrite qualified ```nn.dense operation``` to ```nn.sparse_dense``` This pass is used in ```data_dep_optimization.bsr_dense``` Parameters of this pass is generated by ```analysis.sparse_dense.process_params``` Parameters ---------- weight_name: Array[String] Names of weights which qualified sparse contrains weight_shape: Array[Array[IntImm]] Weights shape in BSR format. Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.<|endoftext|>
b5bc2928a76744a102ab48f4557e61a48e7f549f3cd5c900269d2965b4b610e2
def Conv2dToSparse(weight_name, weight_shape, layout, kernel_size): '\n Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n layout : str\n layout of data\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse(weight_name, weight_shape, layout, kernel_size)
Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d``` Parameters ---------- weight_name: Array[String] Names of weights which qualified sparse contrains weight_shape: Array[Array[IntImm]] Weights shape in BSR format. layout : str layout of data Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.
python/tvm/relay/transform/transform.py
Conv2dToSparse
ryanstout/tvm
2,084
python
def Conv2dToSparse(weight_name, weight_shape, layout, kernel_size): '\n Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n layout : str\n layout of data\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse(weight_name, weight_shape, layout, kernel_size)
def Conv2dToSparse(weight_name, weight_shape, layout, kernel_size): '\n Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified sparse contrains\n\n weight_shape: Array[Array[IntImm]]\n Weights shape in BSR format.\n\n layout : str\n layout of data\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse(weight_name, weight_shape, layout, kernel_size)<|docstring|>Rewrite qualified ```nn.conv2d operation``` to ```nn.sparse_conv2d``` Parameters ---------- weight_name: Array[String] Names of weights which qualified sparse contrains weight_shape: Array[Array[IntImm]] Weights shape in BSR format. layout : str layout of data Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.<|endoftext|>
8b017cedebd2c0e5cb457a8dcedd415332f0e740b8d1567734044f5eb0f8d4fd
def Conv2dToSparse2(layout, kernel_size, blocksize, sparsity_threshold): '\n Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n layout : str\n layout of data\n\n kernel_size : int\n kernel size of conv2d\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse2(layout, kernel_size, *blocksize, sparsity_threshold)
Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d``` Parameters ---------- layout : str layout of data kernel_size : int kernel size of conv2d Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.
python/tvm/relay/transform/transform.py
Conv2dToSparse2
ryanstout/tvm
2,084
python
def Conv2dToSparse2(layout, kernel_size, blocksize, sparsity_threshold): '\n Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n layout : str\n layout of data\n\n kernel_size : int\n kernel size of conv2d\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse2(layout, kernel_size, *blocksize, sparsity_threshold)
def Conv2dToSparse2(layout, kernel_size, blocksize, sparsity_threshold): '\n Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d```\n\n Parameters\n ----------\n layout : str\n layout of data\n\n kernel_size : int\n kernel size of conv2d\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered DenseToSparse pass.\n ' return _ffi_api.Conv2dToSparse2(layout, kernel_size, *blocksize, sparsity_threshold)<|docstring|>Rewrite freezed ```nn.conv2d``` operation to ```nn.sparse_conv2d``` Parameters ---------- layout : str layout of data kernel_size : int kernel size of conv2d Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass.<|endoftext|>
6c9b4d9edb0e20b97dd129dc02d35a91ca5fa530324e9501481fd411c2d22f29
def SimplifyFCTranspose(target_weight_name): '\n Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)```\n This pass is used in ```data_dep_optimization.simplify_fc_transpose```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))```\n This parameter is generated by ```analysis.search_fc_transpose``` function\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyFCTranspose pass.\n ' return _ffi_api.SimplifyFCTranspose(target_weight_name)
Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)``` This pass is used in ```data_dep_optimization.simplify_fc_transpose``` Parameters ---------- weight_name: Array[String] Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))``` This parameter is generated by ```analysis.search_fc_transpose``` function Returns ------- ret : tvm.transform.Pass The registered SimplifyFCTranspose pass.
python/tvm/relay/transform/transform.py
SimplifyFCTranspose
ryanstout/tvm
2,084
python
def SimplifyFCTranspose(target_weight_name): '\n Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)```\n This pass is used in ```data_dep_optimization.simplify_fc_transpose```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))```\n This parameter is generated by ```analysis.search_fc_transpose``` function\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyFCTranspose pass.\n ' return _ffi_api.SimplifyFCTranspose(target_weight_name)
def SimplifyFCTranspose(target_weight_name): '\n Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)```\n This pass is used in ```data_dep_optimization.simplify_fc_transpose```\n\n Parameters\n ----------\n weight_name: Array[String]\n Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))```\n This parameter is generated by ```analysis.search_fc_transpose``` function\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyFCTranspose pass.\n ' return _ffi_api.SimplifyFCTranspose(target_weight_name)<|docstring|>Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)``` This pass is used in ```data_dep_optimization.simplify_fc_transpose``` Parameters ---------- weight_name: Array[String] Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))``` This parameter is generated by ```analysis.search_fc_transpose``` function Returns ------- ret : tvm.transform.Pass The registered SimplifyFCTranspose pass.<|endoftext|>
db61c367a5181906f60306a18d548003fad6fcb9b28868816f3bd4e7a8c579c0
def SimplifyExpr(): '\n Simplify the Relay expression, including merging consecutive reshapes.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.SimplifyExpr()
Simplify the Relay expression, including merging consecutive reshapes. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass.
python/tvm/relay/transform/transform.py
SimplifyExpr
ryanstout/tvm
2,084
python
def SimplifyExpr(): '\n Simplify the Relay expression, including merging consecutive reshapes.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.SimplifyExpr()
def SimplifyExpr(): '\n Simplify the Relay expression, including merging consecutive reshapes.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.SimplifyExpr()<|docstring|>Simplify the Relay expression, including merging consecutive reshapes. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass.<|endoftext|>
4a62119ed36afb3d4f4a37946550c66e50fd7cead26951d5a068cb3352e8af09
def PlanDevices(config): '\n Uses existing "on_device" and "device_copy" calls to infer the virtual device on which\n every Relay sub-expression should run and the result stored. Captures the result of that\n analysis using new "on_device" and "device_copy" calls. Sub-expressions which are\n not otherwise constrained are assigned to the default primitive virtual device describe by\n config. However data and computations which must be hosted on a CPU (such as shapes and\n shape functions) use the host virtual device of the config.\n\n Parameters\n ----------\n config : tvm.CompilationConfig\n The compilation configuration, specifying available targets and default devices.\n\n Returns\n -------\n ret : tvm.transforms.Pass\n The pass.\n ' return _ffi_api.PlanDevices(config)
Uses existing "on_device" and "device_copy" calls to infer the virtual device on which every Relay sub-expression should run and the result stored. Captures the result of that analysis using new "on_device" and "device_copy" calls. Sub-expressions which are not otherwise constrained are assigned to the default primitive virtual device describe by config. However data and computations which must be hosted on a CPU (such as shapes and shape functions) use the host virtual device of the config. Parameters ---------- config : tvm.CompilationConfig The compilation configuration, specifying available targets and default devices. Returns ------- ret : tvm.transforms.Pass The pass.
python/tvm/relay/transform/transform.py
PlanDevices
ryanstout/tvm
2,084
python
def PlanDevices(config): '\n Uses existing "on_device" and "device_copy" calls to infer the virtual device on which\n every Relay sub-expression should run and the result stored. Captures the result of that\n analysis using new "on_device" and "device_copy" calls. Sub-expressions which are\n not otherwise constrained are assigned to the default primitive virtual device describe by\n config. However data and computations which must be hosted on a CPU (such as shapes and\n shape functions) use the host virtual device of the config.\n\n Parameters\n ----------\n config : tvm.CompilationConfig\n The compilation configuration, specifying available targets and default devices.\n\n Returns\n -------\n ret : tvm.transforms.Pass\n The pass.\n ' return _ffi_api.PlanDevices(config)
def PlanDevices(config): '\n Uses existing "on_device" and "device_copy" calls to infer the virtual device on which\n every Relay sub-expression should run and the result stored. Captures the result of that\n analysis using new "on_device" and "device_copy" calls. Sub-expressions which are\n not otherwise constrained are assigned to the default primitive virtual device describe by\n config. However data and computations which must be hosted on a CPU (such as shapes and\n shape functions) use the host virtual device of the config.\n\n Parameters\n ----------\n config : tvm.CompilationConfig\n The compilation configuration, specifying available targets and default devices.\n\n Returns\n -------\n ret : tvm.transforms.Pass\n The pass.\n ' return _ffi_api.PlanDevices(config)<|docstring|>Uses existing "on_device" and "device_copy" calls to infer the virtual device on which every Relay sub-expression should run and the result stored. Captures the result of that analysis using new "on_device" and "device_copy" calls. Sub-expressions which are not otherwise constrained are assigned to the default primitive virtual device describe by config. However data and computations which must be hosted on a CPU (such as shapes and shape functions) use the host virtual device of the config. Parameters ---------- config : tvm.CompilationConfig The compilation configuration, specifying available targets and default devices. Returns ------- ret : tvm.transforms.Pass The pass.<|endoftext|>
0a0d1c0fb11eeb76ead8404f9baa86ee94755b63fbd423f3f4df66cb33d5297a
def FoldExplicitPadding(): '\n FoldExplicitPadding finds explict padding before an op that can support\n implicit padding and fuses them.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered ImplicitPadding pass.\n ' return _ffi_api.FoldExplicitPadding()
FoldExplicitPadding finds explict padding before an op that can support implicit padding and fuses them. Returns ------- ret : tvm.transform.Pass The registered ImplicitPadding pass.
python/tvm/relay/transform/transform.py
FoldExplicitPadding
ryanstout/tvm
2,084
python
def FoldExplicitPadding(): '\n FoldExplicitPadding finds explict padding before an op that can support\n implicit padding and fuses them.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered ImplicitPadding pass.\n ' return _ffi_api.FoldExplicitPadding()
def FoldExplicitPadding(): '\n FoldExplicitPadding finds explict padding before an op that can support\n implicit padding and fuses them.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered ImplicitPadding pass.\n ' return _ffi_api.FoldExplicitPadding()<|docstring|>FoldExplicitPadding finds explict padding before an op that can support implicit padding and fuses them. Returns ------- ret : tvm.transform.Pass The registered ImplicitPadding pass.<|endoftext|>
5d82f6264b471ddb37bc342c7a2bd8fdbe3e7ec4f3511cd73003e691e53a1518
def AnnotateSpans(): '\n Annotate a program with span information by first generating its textual\n representation and then parsing it back into a Relay AST annotated with\n span information.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered AnnotateSpans pass.\n ' return _ffi_api.AnnotateSpans()
Annotate a program with span information by first generating its textual representation and then parsing it back into a Relay AST annotated with span information. Returns ------- ret : tvm.transform.Pass The registered AnnotateSpans pass.
python/tvm/relay/transform/transform.py
AnnotateSpans
ryanstout/tvm
2,084
python
def AnnotateSpans(): '\n Annotate a program with span information by first generating its textual\n representation and then parsing it back into a Relay AST annotated with\n span information.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered AnnotateSpans pass.\n ' return _ffi_api.AnnotateSpans()
def AnnotateSpans(): '\n Annotate a program with span information by first generating its textual\n representation and then parsing it back into a Relay AST annotated with\n span information.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered AnnotateSpans pass.\n ' return _ffi_api.AnnotateSpans()<|docstring|>Annotate a program with span information by first generating its textual representation and then parsing it back into a Relay AST annotated with span information. Returns ------- ret : tvm.transform.Pass The registered AnnotateSpans pass.<|endoftext|>
7316ffd50c72e91a76561ef03ccdc814dd47483bb4c882ee5b8b2705fcee25f5
def FakeQuantizationToInteger(hard_fail=False): '\n Find regions of the graph of the form\n\n .. code-block:: text\n\n x w\n | |\n dq dq\n \\ /\n op1\n |\n op2\n |\n q\n\n where ``q == qnn.quantize`` and ``dq = qnn.dequantize``\n and rewrite them into integer versions of ``op1`` and ``op2``\n\n Rules for rewriting indivdual ops are in fake_quantization_to_integer.py\n\n Parameters\n ----------\n hard_fail : boolean\n How do deal with errors during graph rewriting.\n If true, raise an error.\n If false, skip rewriting the subgraph.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.FakeQuantizationToInteger(hard_fail)
Find regions of the graph of the form .. code-block:: text x w | | dq dq \ / op1 | op2 | q where ``q == qnn.quantize`` and ``dq = qnn.dequantize`` and rewrite them into integer versions of ``op1`` and ``op2`` Rules for rewriting indivdual ops are in fake_quantization_to_integer.py Parameters ---------- hard_fail : boolean How do deal with errors during graph rewriting. If true, raise an error. If false, skip rewriting the subgraph. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass.
python/tvm/relay/transform/transform.py
FakeQuantizationToInteger
ryanstout/tvm
2,084
python
def FakeQuantizationToInteger(hard_fail=False): '\n Find regions of the graph of the form\n\n .. code-block:: text\n\n x w\n | |\n dq dq\n \\ /\n op1\n |\n op2\n |\n q\n\n where ``q == qnn.quantize`` and ``dq = qnn.dequantize``\n and rewrite them into integer versions of ``op1`` and ``op2``\n\n Rules for rewriting indivdual ops are in fake_quantization_to_integer.py\n\n Parameters\n ----------\n hard_fail : boolean\n How do deal with errors during graph rewriting.\n If true, raise an error.\n If false, skip rewriting the subgraph.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.FakeQuantizationToInteger(hard_fail)
def FakeQuantizationToInteger(hard_fail=False): '\n Find regions of the graph of the form\n\n .. code-block:: text\n\n x w\n | |\n dq dq\n \\ /\n op1\n |\n op2\n |\n q\n\n where ``q == qnn.quantize`` and ``dq = qnn.dequantize``\n and rewrite them into integer versions of ``op1`` and ``op2``\n\n Rules for rewriting indivdual ops are in fake_quantization_to_integer.py\n\n Parameters\n ----------\n hard_fail : boolean\n How do deal with errors during graph rewriting.\n If true, raise an error.\n If false, skip rewriting the subgraph.\n\n Returns\n -------\n ret : tvm.transform.Pass\n The registered SimplifyExpr pass.\n ' return _ffi_api.FakeQuantizationToInteger(hard_fail)<|docstring|>Find regions of the graph of the form .. code-block:: text x w | | dq dq \ / op1 | op2 | q where ``q == qnn.quantize`` and ``dq = qnn.dequantize`` and rewrite them into integer versions of ``op1`` and ``op2`` Rules for rewriting indivdual ops are in fake_quantization_to_integer.py Parameters ---------- hard_fail : boolean How do deal with errors during graph rewriting. If true, raise an error. If false, skip rewriting the subgraph. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass.<|endoftext|>