id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
17,101 | def check_id(data, task_id):
assert data[task_id]["task_id"] == f"HumanEval/{task_id}"
def fix(data):
check_id(data, 116)
data[116]["contract"] = (
'\n assert isinstance(arr, list), "invalid inputs" # $_CONTRACT_$'
+ '\n assert all(isinstance(x, int) and x >= 0 for x in arr), "invalid... | null |
17,102 | import json
import os
import pickle
from os import PathLike
from typing import List
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from evalplus.data import get_human_eval_plus
from evalplus.eval import estimate_pass_at_k
def passk_rel_drop(task2bvs_old, task2bvs_new):
# old_rate:
# d... | null |
17,103 | import json
import os
import pickle
from os import PathLike
from typing import List
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from evalplus.data import get_human_eval_plus
from evalplus.eval import estimate_pass_at_k
SUCCESS = "success"
def get_data(paths: List[PathLike]):
task2bvs_o... | null |
17,104 | import argparse
import json
import os
from typing import Any, Dict, List
from rich.progress import track
from evalplus.eval.utils import swallow_io
from evalplus.evaluate import evaluate
from tools.tsr.utils import (
clean,
execute_cmd,
get_cmd_output,
get_problems,
get_task_ids,
to_path,
)
def... | null |
17,105 | import argparse
import json
import os
from typing import Any, Dict, List
from rich.progress import track
from evalplus.eval.utils import swallow_io
from evalplus.evaluate import evaluate
from tools.tsr.utils import (
clean,
execute_cmd,
get_cmd_output,
get_problems,
get_task_ids,
to_path,
)
def... | null |
17,106 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,107 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,108 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,109 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,110 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,111 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,112 | import argparse
import json
import os
import pickle
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from rich.progress import track
from evalplus.data import write_jsonl
from tools.tsr.coverage_init import collect_coverage_in... | null |
17,113 | import argparse
import json
import os
import numpy as np
from termcolor import cprint
from evalplus.eval import estimate_pass_at_k
def analyze_resfile(resfile):
before_summary = {}
after_summary = {}
res = json.load(open(resfile))["eval"]
total = []
before_pass = []
after_pass = []
for v i... | null |
17,114 | import argparse
import json
import os
import numpy as np
from termcolor import cprint
from evalplus.eval import estimate_pass_at_k
def align_ampersands(str1, str2):
"""
This function takes two strings containing various "&" characters and transforms them so that the indices of "&"
are aligned. This is usefu... | null |
17,115 | import argparse
import json
import os
import numpy as np
from termcolor import cprint
from evalplus.eval import estimate_pass_at_k
TEMPS = [0.2, 0.4, 0.6, 0.8]
def rich_print(before_summary, after_summary, bfgreedy, afgreedy):
from rich.console import Console
from rich.table import Table
console = Console... | null |
17,116 | import json
import os
from evalplus.data import get_human_eval_plus
from evalplus.gen.util import trusted_exec
def execute(code, input_list) -> bool:
try:
trusted_exec(code, [input_list], entry_point)
except Exception as e:
assert str(e) == "invalid inputs"
return False
return True | null |
17,117 | import json
import os
from evalplus.data import get_human_eval_plus
from evalplus.gen.util import trusted_exec
def write(new_input_dict):
with open(new_input_path, "a") as f:
f.write(json.dumps(new_input_dict) + "\n") | null |
17,118 | import ast
import re
import traceback
from typing import List, Optional
def syntax_check(code, verbose=False):
try:
ast.parse(code)
return True
except (SyntaxError, MemoryError):
if verbose:
traceback.print_exc()
return False
def remove_unindented_lines(code, protect_... | null |
17,119 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
CACHE_DIR = user_cache_dir("evalplus")
def get_dataset_metadata(name, version, mini):
assert name in ["HumanEvalPlus", "MbppPlus"], f"Unknown/unsupported dataset... | null |
17,120 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
CACHE_DIR = user_cache_dir("evalplus")
def make_cache(gzip_url, cache_path):
# Check if human eval file exists in CACHE_DIR
if not os.path.exists(cache_path)... | null |
17,121 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
The provided code snippet includes necessary dependencies for implementing the `write_jsonl` function. Write a Python function `def write_jsonl( filename: str, d... | Writes an iterable of dictionaries to jsonl |
17,122 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
def stream_jsonl(filename: str) -> Iterable[Dict]:
"""
Parses each jsonl line and yields it as a dictionary
"""
if filename.endswith(".gz"):
w... | We accept two formats of inputs. + `sample.jsonl` which is the format from HumanEval, i.e., {task_id, completion}. + A folder which contains sub-folders named after the task_id. Each sub-folder contains samples named in `[?].py` where `?` is the solution id starting with 0. Different from `sample.jsonl`, the solutions ... |
17,123 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
def write_directory(directory: PathLike, data: Iterable[Dict]):
os.makedirs(directory, exist_ok=True)
counters = {}
for sample in data:
assert "s... | null |
17,124 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
def completeness_check(name, plus):
for task_id, task in plus.items():
for key in [
"prompt",
"contract",
"canonical_... | null |
17,125 | import gzip
import json
import os
from os import PathLike
from typing import Dict, Iterable
import tempdir
import wget
from appdirs import user_cache_dir
def to_raw(string):
return string.encode("unicode-escape").decode().replace("\\\\", "\\") | null |
17,126 | import hashlib
import json
import os
from typing import Dict
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
def _ready_human_eval_plus_path(mini=False) -> str:
if HUMANEVAL_OVERRIDE_PATH:
return HUMANEVAL_OVERRIDE_PATH
... | Get the hash of HumanEvalPlus. Returns: str: The hash of HumanEvalPlus |
17,127 | import hashlib
import json
import os
from typing import Dict
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
def _ready_human_eval_plus_path(mini=False) -> str:
if HUMANEVAL_OVERRIDE_PATH:
return HUMANEVAL_OVERRIDE_PATH
... | Get HumanEvalPlus locally. Args: err_incomplete (bool, optional): Whether to raise error if HumanEvalPlus is not complete. Defaults to True. mini (bool, optional): Whether to use the mini version of HumanEvalPlus. Defaults to False. Returns: List[Dict[str, str]]: List of dicts with keys "task_id", "prompt", "contract",... |
17,128 | import hashlib
import json
import os
from typing import Dict
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
The provided code snippet includes necessary dependencies for implementing the `get_human_eval` function. Write a Python fu... | Get HumanEval from OpenAI's github repo and return as a list of parsed dicts. Returns: List[Dict[str, str]]: List of dicts with keys "prompt", "test", "entry_point" Notes: "task_id" is the identifier string for the task. "prompt" is the prompt to be used for the task (function signature with docstrings). "test" is test... |
17,129 | import hashlib
import json
import os
from typing import Dict
import wget
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
def mbpp_serialize_inputs(task_id: str, inputs: list) -> list:
task_id = int(task_id.split("/")[-1])
i... | null |
17,130 | import hashlib
import json
import os
from typing import Dict
import wget
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
The provided code snippet includes necessary dependencies for implementing the `get_mbpp` function. Write a Pyt... | Get sanitized MBPP from Google's Github repo. |
17,131 | import hashlib
import json
import os
from typing import Dict
import wget
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
def _ready_mbpp_plus_path(mini=False) -> str:
assert mini is False, "Mini version of MBPP+ is not available ... | null |
17,132 | import hashlib
import json
import os
from typing import Dict
import wget
from evalplus.data.utils import (
CACHE_DIR,
completeness_check,
get_dataset_metadata,
make_cache,
stream_jsonl,
)
def _ready_mbpp_plus_path(mini=False) -> str:
assert mini is False, "Mini version of MBPP+ is not available ... | Get the hash of MbppPlus. Returns: str: The hash of MbppPlus |
17,133 | import math
import multiprocessing
import time
from typing import Any, List, Union
from evalplus.data import get_human_eval_plus
from evalplus.eval.utils import (
TimeoutException,
create_tempdir,
reliability_guard,
swallow_io,
time_limit,
)
MAX_WARMUP_LIMIT = 5
RUN_REPEAT = 25
def execute_for_runti... | null |
17,134 | import argparse
import importlib
import inspect
import multiprocessing
import os
import sys
from io import StringIO
from typing import Any, Callable, List, Union
import coverage
from evalplus.data import get_human_eval_plus
from evalplus.data.utils import to_raw
from evalplus.eval.utils import reliability_guard, swallo... | Parameters: * dataset: {None, "HumanEval", "HumanEvalPlus"} * task_id: ralated to dataset * impl: {"canonical", source code} * inputs: {"base_inputs", list} * mode: {"branch"}, will support "line" for coverage-guided LLM test generation |
17,135 | import signal
import time
from typing import Dict
import openai
from openai.types.chat import ChatCompletion
def make_request(
client: openai.Client,
message: str,
model: str,
max_tokens: int = 512,
temperature: float = 1,
n: int = 1,
**kwargs
) -> ChatCompletion:
def handler(signum, frame):... | null |
17,136 | import argparse
import json
import os
from evalplus.data.mbpp import mbpp_serialize_inputs
from evalplus.gen.chatgpt_gen import ChatGPTGen
from evalplus.gen.type_mut import TypedMutGen
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
r... | null |
17,137 | import argparse
import json
import multiprocessing
import os
import pickle
import threading
import time
from collections import Counter, defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union
from warnings imp... | null |
17,138 | import contextlib
import faulthandler
import io
import os
import platform
import signal
import tempfile
from typing import Optional
class WriteOnlyStringIO(io.StringIO):
"""StringIO that throws an exception when it's read from"""
def read(self, *args, **kwargs):
raise IOError
def readline(self, *arg... | null |
17,139 | import contextlib
import faulthandler
import io
import os
import platform
import signal
import tempfile
from typing import Optional
class TimeoutException(Exception):
pass
def time_limit(seconds: float):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.setitimer(signa... | null |
17,140 | import contextlib
import faulthandler
import io
import os
import platform
import signal
import tempfile
from typing import Optional
def chdir(root):
if root == ".":
yield
return
cwd = os.getcwd()
os.chdir(root)
try:
yield
except BaseException as exc:
raise exc
fin... | null |
17,141 | import contextlib
import faulthandler
import io
import os
import platform
import signal
import tempfile
from typing import Optional
def chdir(root):
if root == ".":
yield
return
cwd = os.getcwd()
os.chdir(root)
try:
yield
except BaseException as exc:
raise exc
fin... | This disables various destructive functions and prevents the generated code from interfering with the test (e.g. fork bomb, killing other processes, removing filesystem files, etc.) WARNING This function is NOT a security sandbox. Untrusted code, including, model- generated code, should not be blindly executed outside ... |
17,142 | import math
The provided code snippet includes necessary dependencies for implementing the `_poly` function. Write a Python function `def _poly(xs: list, x: float)` to solve the following problem:
Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n
Here is t... | Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n |
17,143 | import ast
import gradio as gr
import os
import re
import json
import logging
import torch
from datetime import datetime
from threading import Thread
from typing import Optional
from transformers import TextIteratorStreamer
from functools import partial
from huggingface_hub import CommitScheduler
from uuid import uuid4... | null |
17,144 | import re
import os
SITE_PKG_ERROR_PREFIX = f'File {PYTHON_PREFIX}/lib/python3.10/'
def get_error_header(traceback_str):
lines = traceback_str.split('\n')
for line in lines:
if 'Error:' in line:
return line
return '' # Return None if no error message is found
def clean_error_msg(error_... | null |
17,145 | import glob
import json
import subprocess
import os
import multiprocessing
import re
import argparse
zeros_pattern = r"^0+\s"
OPT = ["O0", "O1", "O2", "O3"]
def write_to_file(file_path, data):
with multiprocessing.Lock():
with open(file_path, "a") as f:
json.dump(data, f)
f.write("... | null |
17,146 | import glob
import json
import subprocess
import os
import multiprocessing
import re
import argparse
def parse_args():
parser = argparse.ArgumentParser(
description="Compile C files and generate JSONL output."
)
parser.add_argument(
"--root",
required=True,
help="Root direct... | null |
17,147 | import subprocess
import asyncio
from transformers import AutoTokenizer
import os
import json
from loguru import logger
import traceback
from argparse import ArgumentParser
from pathlib import Path
import sys
from tqdm import tqdm
from server.text_generation import TextGenerationServer, TextGenerationClient
import mult... | null |
17,148 | import subprocess
import asyncio
from transformers import AutoTokenizer
import os
import json
from loguru import logger
import traceback
from argparse import ArgumentParser
from pathlib import Path
import sys
from tqdm import tqdm
from server.text_generation import TextGenerationServer, TextGenerationClient
import mult... | null |
17,149 | import subprocess
from transformers import AutoTokenizer, AutoModelForCausalLM
import argparse
import os
import torch
import re
import json
from tqdm import tqdm, trange
os.environ["TOKENIZERS_PARALLELISM"] = "false"
with open(args.data_path,'r') as f:
data_all = json.load(f)
with open('results.txt','a') as f:
... | null |
17,150 | import glob
import platform
import subprocess
import os
from os import path
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CUDNN_HOME, CppExtension, CUDAExtension
def fetch_requirements():
with open("requirements.txt") as f:
reqs = f.read().strip()... | null |
17,151 | import glob
import platform
import subprocess
import os
from os import path
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CUDNN_HOME, CppExtension, CUDAExtension
def get_version():
this_dir = path.dirname(path.abspath(__file__))
if os.getenv("BUILD_VE... | null |
17,152 | import glob
import platform
import subprocess
import os
from os import path
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CUDNN_HOME, CppExtension, CUDAExtension
torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
assert torch_ver >= [1, 8], "Requir... | null |
17,153 | import logging
import functools
import threading
import dataclasses
import torch
from sfast.utils.copy import (tree_copy_, tree_copy, shadow_copy,
can_be_perfectly_copied)
from sfast.hooks.module_jit_hook import (apply_to_all_modules, apply_to_module)
def get_requires_grad_from_tensors(x)... | null |
17,154 | import logging
import functools
import threading
import dataclasses
import torch
from sfast.utils.copy import (tree_copy_, tree_copy, shadow_copy,
can_be_perfectly_copied)
from sfast.hooks.module_jit_hook import (apply_to_all_modules, apply_to_module)
def can_be_perfectly_copied(obj):
... | null |
17,155 | import logging
import functools
import threading
import dataclasses
import torch
from sfast.utils.copy import (tree_copy_, tree_copy, shadow_copy,
can_be_perfectly_copied)
from sfast.hooks.module_jit_hook import (apply_to_all_modules, apply_to_module)
class AutoGraphCraphCompiler:
def ... | null |
17,156 | from typing import Optional
import torch
from xformers.ops import (memory_efficient_attention, AttentionOp)
from xformers import ops
from sfast.utils.custom_python_operator import register_custom_python_operator
STR_OP_MAP = {v: k for k, v in OP_STR_MAP.items()}
def xformers_memory_efficient_attention_torch_op(
... | null |
17,157 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
if stack is None:
stack = [(None, m)]
if filter_func(stack):
if inplace:
patch_func(m)
else:
m = patch_func(m)
for name, ch... | null |
17,158 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
if stack is None:
stack = [(None, m)]
if filter_func(stack):
if inplace:
patch_func(m)
else:
m = patch_func(m)
for name, ch... | null |
17,159 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
class TritonGroupNorm(nn.Module):
def __init__(self, module):
def forward(self, x, *args, **kwargs):
def patch_group_norm(m):
from torch.nn import GroupNorm
from .native import Triton... | null |
17,160 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
if stack is None:
stack = [(None, m)]
if filter_func(stack):
if inplace:
patch_func(m)
else:
m = patch_func(m)
for name, ch... | null |
17,161 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
if stack is None:
stack = [(None, m)]
if filter_func(stack):
if inplace:
patch_func(m)
else:
m = patch_func(m)
for name, ch... | null |
17,162 | from sfast.utils.patch import patch_module
def patch_module(m, filter_func, patch_func, stack=None, inplace=False):
if stack is None:
stack = [(None, m)]
if filter_func(stack):
if inplace:
patch_func(m)
else:
m = patch_func(m)
for name, ch... | null |
17,163 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,164 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,165 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,166 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,167 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,168 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,169 | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward
aten = torch.ops.aten
... | null |
17,170 | import torch
import triton
import triton.language as tl
from sfast.utils.copy_func import copy_func
from . import activation
from .utils import welford_combine
def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2):
delta = mean_2 - mean_1
new_weight = weight_1 + weight_2
# w2_over_w = weight_... | null |
17,171 | import torch
import triton
import triton.language as tl
from sfast.utils.copy_func import copy_func
from . import activation
from .utils import welford_combine
def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2):
def group_norm_4d_channels_last_forward_collect_stats_kernel_stage_2(
cluster_mean_pt... | null |
17,172 | import torch
try:
from torch._prims_common import suggest_memory_format
except ImportError:
from sfast.utils.memory_format import suggest_memory_format
import triton
import triton.language as tl
from sfast.utils.copy_func import copy_func
from . import activation
from .utils import welford_combine
def group_nor... | null |
17,173 | import torch
try:
from torch._prims_common import suggest_memory_format
except ImportError:
from sfast.utils.memory_format import suggest_memory_format
import triton
import triton.language as tl
from sfast.utils.copy_func import copy_func
from . import activation
from .utils import welford_combine
group_norm_fo... | null |
17,174 | import functools
import operator
import torch
import triton
import triton.language as tl
from .utils import welford_combine
def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2):
delta = mean_2 - mean_1
new_weight = weight_1 + weight_2
# w2_over_w = weight_2 / new_weight
w2_over_w = tl.wh... | null |
17,175 | import functools
import operator
import torch
import triton
import triton.language as tl
from .utils import welford_combine
def _layer_norm_bwd_dx_fused(
DX, # pointer to the input gradient
DY, # pointer to the output gradient
DW, # pointer to the partial sum of weights gradient
DB, ... | null |
17,176 | import functools
import operator
import torch
import triton
import triton.language as tl
from .utils import welford_combine
def _layer_norm_bwd_dwdb(
DW, # pointer to the partial sum of weights gradient
DB, # pointer to the partial sum of biases gradient
FINAL_DW, # pointer to the weights gr... | null |
17,177 | import functools
import operator
import torch
import triton
import triton.language as tl
from .utils import welford_combine
layer_norm = LayerNorm.apply
def test_layer_norm(M, N, dtype, eps=1e-5, device='cuda'):
# create data
x_shape = (M, N)
w_shape = (x_shape[-1], )
weight = torch.ran... | null |
17,178 | import functools
import operator
import torch
import triton
import triton.language as tl
from .utils import welford_combine
layer_norm = LayerNorm.apply
def bench_layer_norm(M,
N,
dtype,
provider,
mode='backward',
... | null |
17,179 | import heapq
import torch
import triton
import triton.language as tl
def estimate_conv_time(
# backend, device,
num_warps,
num_stages,
x,
BATCH,
IN_C,
IN_H,
IN_W,
KERNEL_N,
KERNEL_H,
KERNEL_W,
OUT_H,
OUT_W,
BLOCK_M,
BLOCK_K,
BLOCK_N,
debug=False,
*... | null |
17,180 | import heapq
import torch
import triton
import triton.language as tl
def _unpack(idx, order, shape):
if torch.is_tensor(idx):
_12 = torch.div(idx, shape[order[0]], rounding_mode="trunc")
_0 = idx % shape[order[0]]
_2 = torch.div(_12, shape[order[1]], rounding_mode="trunc")
_1 = _12 ... | null |
17,181 | import heapq
import torch
import triton
import triton.language as tl
The provided code snippet includes necessary dependencies for implementing the `_kernel_delta_x_hwc` function. Write a Python function `def _kernel_delta_x_hwc( x, w, bias, y, # stride of tensor stride_xn, stride_xc, s... | each program instance computes a [BLOCK_BATCH, BLOCK_N, BLOCK_H, BLOCK_W] block of y |
17,182 | import heapq
import torch
import triton
import triton.language as tl
The provided code snippet includes necessary dependencies for implementing the `_kernel_delta_x` function. Write a Python function `def _kernel_delta_x( x, w, bias, y, # stride of tensor stride_xn, stride_xc, stride_xh... | each program instance computes a [BLOCK_BATCH, BLOCK_N, BLOCK_H, BLOCK_W] block of y |
17,183 | import triton
import triton.language as tl
def silu(x):
return x * tl.sigmoid(x.to(tl.float32)).to(x.dtype) | null |
17,184 | import triton
import triton.language as tl
def relu(x):
return tl.max(x, 0.0) | null |
17,185 | import triton
import triton.language as tl
def gelu(x):
return 0.5 * x * (1.0 + tl.tanh(0.7978845608028654 *
(x + 0.044715 * x * x * x))) | null |
17,186 | import torch
import triton
import triton.language as tl
from itertools import product
def copy(dst, src):
def test_transpose(x):
print('--------------------------------')
print('Input Shape: ', x.shape)
print('Input Bytes: ', x.numel() * x.element_size())
begin = time.time()
tra... | null |
17,187 | import functools
import torch
from torch._dynamo.backends.registry import register_backend
from torch._dynamo.backends.common import aot_autograd, fake_tensor_unsupported
from functorch.compile import make_boxed_compiler
from sfast.jit.trace_helper import trace_with_kwargs
def sfast_jit_script(gm, example_inputs, *, t... | null |
17,188 | import functools
import torch
from torch._dynamo.backends.registry import register_backend
from torch._dynamo.backends.common import aot_autograd, fake_tensor_unsupported
from functorch.compile import make_boxed_compiler
from sfast.jit.trace_helper import trace_with_kwargs
def gen_jit_aot_compiler(compiler, ts_compiler... | null |
17,189 | import functools
import torch
from torch._dynamo.backends.registry import register_backend
from torch._dynamo.backends.common import aot_autograd, fake_tensor_unsupported
from functorch.compile import make_boxed_compiler
from sfast.jit.trace_helper import trace_with_kwargs
def gen_jit_aot_compiler(compiler, ts_compiler... | null |
17,190 | import functools
from .backends.registry import _lazy_import
def _lazy_import():
from .. import backends
from torch._dynamo.utils import import_submodule
import_submodule(backends) | null |
17,191 | import logging
import inspect
import functools
import threading
import torch
from sfast.utils import flat_tensors
from sfast.utils.copy import tree_copy
from sfast.hooks.module_jit_hook import (apply_to_all_modules, apply_to_module)
from .utils import better_trace
def can_io_obj_be_perfectly_traced(obj):
return fl... | null |
17,192 | import logging
import torch
def jit_pass_optimize_contiguous(graph):
if hasattr(torch.ops.sfast_triton, 'contiguous'):
torch._C._jit_pass_custom_pattern_based_rewrite_graph(
'''
graph(%1, %2):
%x = aten::contiguous(%1, %2)
return (%x)''', '''
graph(%1, %2):
%x = sfast_triton::contig... | null |
17,193 | import io
import functools
import cProfile
import pstats
def with_cProfile(*amount, out_func=None, file=None):
def _with_cProfile(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
pr = cProfile.Profile()
try:
retval = pr.runcall(func, *args, **kwa... | null |
17,194 | import torch
def device_has_tensor_core():
if torch.cuda.is_available():
major, minor = torch.cuda.get_device_capability()
return major >= 7
return False | null |
17,195 | import torch
def device_has_capability(major, minor):
if torch.cuda.is_available():
major_, minor_ = torch.cuda.get_device_capability()
return (major_, minor_) >= (major, minor)
return False | null |
17,196 | import torch
import sfast
registered_custom_python_operator_names = set()
def register_custom_python_operator(schema, callable):
name = torch._C.parse_schema(schema).name
if name in registered_custom_python_operator_names:
return
sfast._C._jit_register_custom_python_operator(schema, callable)
r... | null |
17,197 | import contextlib
import packaging.version
from functorch.compile import (aot_function, aot_module)
import torch
def no_fake_tensor():
if packaging.version.parse(
torch.__version__) >= packaging.version.parse("2.0.0"):
from torch._functorch import config
use_fake_tensor = config.use_fa... | null |
17,198 | import contextlib
import packaging.version
from functorch.compile import (aot_function, aot_module)
import torch
def get_compiler_fn(title=None):
def aot_printer(fn):
if isinstance(fn, torch.nn.Module):
return aot_module(fn,
fw_compiler=get_compiler_fn("Forward Code:"),
... | null |
17,199 | import logging
import torch
from torch.utils._python_dispatch import TorchDispatchMode
def with_dispatch_mode(dispatch_mode):
def decorator(func):
def wrapper(*args, **kwargs):
with dispatch_mode():
return func(*args, **kwargs)
return wrapper
return decorator | null |
17,200 | from __future__ import print_function
import base64
import os
import sys
def print_osc(terminal):
if terminal.startswith('screen') or terminal.startswith('tmux'):
print_partial("\033Ptmux;\033\033]")
else:
print_partial("\033]")
def print_st(terminal):
if terminal.startswith('screen') or ter... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.