id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
189,441
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict def parse_cookie_string(cookie_string): cookie = SimpleCookie() cookie.load(cookie_string)...
null
189,442
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict _no_elapse_chars = re.compile(r"([「」『』《》“”'\"()()]|(?<!-)-(?!-))", re.UNICODE) def calculate_tts_e...
null
189,443
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict tions = ("。", "?", "!", ";", "\n", "?", "!", ";") async def split_sentences(text_stream: AsyncIter...
null
189,444
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict def find_key_by_partial_string(dictionary: dict[str, str], partial_key: str) -> str: for key, ...
null
189,445
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict The provided code snippet includes necessary dependencies for implementing the `validate_proxy` fu...
Do a simple validation of the http proxy string.
189,446
from __future__ import annotations import os import re import socket from http.cookies import SimpleCookie from typing import AsyncIterator from urllib.parse import urlparse from requests.utils import cookiejar_from_dict def get_hostname() -> str: if "XIAOGPT_HOSTNAME" in os.environ: return os.environ["XIA...
null
189,447
from __future__ import annotations from langchain.agents import AgentType, Tool, initialize_agent from langchain.callbacks.base import BaseCallbackHandler from langchain.chains import LLMMathChain from langchain.schema.memory import BaseMemory from langchain_community.chat_models import ChatOpenAI from langchain_commun...
null
189,448
import os import copy import json import torch import logging import argparse import torch.distributed as dist from tqdm import tqdm from accelerate import Accelerator from torch.utils.data import Dataset, DataLoader from torch.utils.tensorboard import SummaryWriter from transformers import set_seed, get_cosine_schedul...
null
189,449
from accelerate import init_empty_weights, load_checkpoint_and_dispatch from transformers.generation.utils import logger from huggingface_hub import snapshot_download import mdtex2html import gradio as gr import argparse import warnings import torch import os def postprocess(self, y): if y is None: return ...
null
189,450
from accelerate import init_empty_weights, load_checkpoint_and_dispatch from transformers.generation.utils import logger from huggingface_hub import snapshot_download import mdtex2html import gradio as gr import argparse import warnings import torch import os tokenizer = MossTokenizer.from_pretrained(args.model_name) m...
null
189,451
from accelerate import init_empty_weights, load_checkpoint_and_dispatch from transformers.generation.utils import logger from huggingface_hub import snapshot_download import mdtex2html import gradio as gr import argparse import warnings import torch import os gr.Chatbot.postprocess = postprocess with gr.Blocks() as dem...
null
189,452
from accelerate import init_empty_weights, load_checkpoint_and_dispatch from transformers.generation.utils import logger from huggingface_hub import snapshot_download import mdtex2html import gradio as gr import argparse import warnings import torch import os def reset_state(): return [], []
null
189,453
import argparse import os from fastapi import FastAPI, Request import torch import warnings import uvicorn, json, datetime import uuid from huggingface_hub import snapshot_download from transformers.generation.utils import logger from accelerate import init_empty_weights, load_checkpoint_and_dispatch print(model_path) ...
null
189,454
import argparse import os import platform import warnings import torch import jittor as jt from huggingface_hub import snapshot_download from transformers.generation.utils import logger from transformers import AutoTokenizer, AutoConfig from models_jittor import MossForCausalLM, generate from models_jittor import load_...
null
189,455
import argparse import os import time import streamlit as st import torch from accelerate import init_empty_weights, load_checkpoint_and_dispatch from huggingface_hub import snapshot_download from transformers import StoppingCriteriaList from models.configuration_moss import MossConfig from models.modeling_moss import ...
null
189,456
import argparse import os import time import streamlit as st import torch from accelerate import init_empty_weights, load_checkpoint_and_dispatch from huggingface_hub import snapshot_download from transformers import StoppingCriteriaList from models.configuration_moss import MossConfig from models.modeling_moss import ...
null
189,457
import argparse import os import time import streamlit as st import torch from accelerate import init_empty_weights, load_checkpoint_and_dispatch from huggingface_hub import snapshot_download from transformers import StoppingCriteriaList from models.configuration_moss import MossConfig from models.modeling_moss import ...
null
189,458
import argparse import os import platform import warnings import torch from accelerate import init_empty_weights, load_checkpoint_and_dispatch from huggingface_hub import snapshot_download from transformers.generation.utils import logger from models.configuration_moss import MossConfig from models.modeling_moss import ...
null
189,459
import builtins import math import time from typing import Dict import triton class Autotuner(triton.KernelInterface): def __init__(self, fn, arg_names, configs, key, reset_to_zero, prune_configs_by: Dict = None, nearest_power_of_two: bool = False): ''' :param prune_configs_by: a dict of functions that are used to...
Decorator for auto-tuning a :code:`triton.jit`'d function. .. highlight:: python .. code-block:: python @triton.autotune(configs=[ triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4), triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8), ], key=['x_size'] # the two above configs will be evaluated anytime # the value ...
189,460
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import transformers from transformers.activations import ACT2FN from transformers.modeling_utils import PreTrainedModel from transformers.modeling_outputs import BaseModelOutpu...
null
189,461
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import transformers from transformers.activations import ACT2FN from transformers.modeling_utils import PreTrainedModel from transformers.modeling_outputs import BaseModelOutpu...
null
189,464
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd import math import triton import triton.language as tl from models.custom_autotune import * The provided code snippet includes necessary dependencies for implementing the `trans_matmul_248_kernel` function. Write a ...
Compute the matrix multiplication C = A x B. A is of shape (M, N) float16 B is of shape (K//8, N) int32 C is of shape (M, K) float16 scales is of shape (G, N) float16 zeros is of shape (G, N) float16 g_ptr is of shape (K) int32
189,465
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd import math import triton import triton.language as tl from models.custom_autotune import * def matmul_248_kernel(a_ptr, b_ptr, c_ptr, scales_ptr, zeros_ptr, g_ptr, M, N, K...
null
189,466
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd import math import triton import triton.language as tl from models.custom_autotune import * def transpose_matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq): output_dim = (qweight.shape[0] * 32) // bit...
null
189,467
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd import math import triton import triton.language as tl from models.custom_autotune import * def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''): if type(module) in layers: return {name: module...
null
189,468
import math import jittor as jt import jittor.nn as nn def fixed_pos_embedding(x, seq_dim=1, seq_len=None): dim = x.shape[-1] if seq_len is None: seq_len = x.shape[seq_dim] inv_freq = 1.0 / (10000 ** (jt.arange(0, dim, 2) / dim)) sinusoid_inp = ( jt.einsum("i , j -> i j", jt.arange(seq_...
null
189,469
import math import jittor as jt import jittor.nn as nn def rotate_every_two(x): x1 = x[:, :, :, ::2] x2 = x[:, :, :, 1::2] x = jt.stack((-x2, x1), dim=-1) return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)') def duplicate_interleave(m): """ A simple version of `jt.rep...
null
189,470
import math import jittor as jt import jittor.nn as nn def _init_weights(module, config): if isinstance(module, (nn.Linear,)): # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.n...
null
189,471
import math import jittor as jt import jittor.nn as nn def _convert_head_mask_to_5d(head_mask, num_hidden_layers, dtype): """-> [num_hidden_layers x batch x num_heads x seq_length x seq_length]""" if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1) ...
null
189,472
import os import json import torch import jittor as jt import numpy as np from tqdm import tqdm def load_from_map(model: jt.Module, ckpt_dir, file_weight_map): for filename, names in tqdm(file_weight_map.items()): cur_state_dict = torch.load(os.path.join(ckpt_dir, filename)) for key, value in cur_st...
Load sharded checkpoints directly from huggingface dir.
189,473
import os import json import torch import jittor as jt import numpy as np from tqdm import tqdm def check_state_dict(model: jt.Module, ckpt_dir, file_weight_map): for filename, names in file_weight_map.items(): cur_state_dict = torch.load(os.path.join(ckpt_dir, filename)) for name in names: ...
null
189,474
import jittor as jt def greedy_search(model, input_str, tokenizer, max_gen_len, eos_token_id=None, pad_token_id=None): model.eval() if eos_token_id is None: eos_token_id = tokenizer.eos_token_id if pad_token_id is None and eos_token_id is not None: pad_token_id = eos_token_...
Choose different methods to generate sentences. :param input_str: The input text. :param tokenizer: Tokenizer. :param method: Generation method. Should be one of: ['greedy', 'sample'] :param kwargs: Other parameters used for generation. - max_gen_len: int. Maximum generate length. Used in all methods. - temperature: fl...
189,475
import os from setuptools import find_namespace_packages from setuptools import setup def _get_version(): with open('mctx/__init__.py') as fp: for line in fp: if line.startswith('__version__') and '=' in line: version = line[line.find('=') + 1:].strip(' \'"\n') if version: return ...
null
189,476
import os from setuptools import find_namespace_packages from setuptools import setup _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) def _parse_requirements(path): with open(os.path.join(_CURRENT_DIR, path)) as f: return [ line.rstrip() for line in f if not (line.isspace() or ...
null
189,477
import chex import jax import jax.numpy as jnp from mctx._src import tree as tree_lib The provided code snippet includes necessary dependencies for implementing the `qtransform_by_min_max` function. Write a Python function `def qtransform_by_min_max( tree: tree_lib.Tree, node_index: chex.Numeric, *, mi...
Returns Q-values normalized by the given `min_value` and `max_value`. Args: tree: _unbatched_ MCTS tree state. node_index: scalar index of the parent node. min_value: given minimum value. Usually the `min_value` is minimum possible untransformed Q-value. max_value: given maximum value. Usually the `max_value` is maximu...
189,478
from __future__ import annotations from typing import Any, ClassVar, Generic, TypeVar import chex import jax import jax.numpy as jnp class Tree(Generic[T]): """State of a search tree. The `Tree` dataclass is used to hold and inspect search data for a batch of inputs. In the fields below `B` denotes the batch dime...
null
189,479
import functools from typing import Optional, Tuple import chex import jax import jax.numpy as jnp from mctx._src import action_selection from mctx._src import base from mctx._src import qtransforms from mctx._src import search from mctx._src import seq_halving def _mask_invalid_actions(logits, invalid_actions): """R...
Runs MuZero search and returns the `PolicyOutput`. In the shape descriptions, `B` denotes the batch dimension. Args: params: params to be forwarded to root and recurrent functions. rng_key: random number generator state, the key is consumed. root: a `(prior_logits, value, embedding)` `RootFnOutput`. The `prior_logits` ...
189,480
import functools from typing import Optional, Tuple import chex import jax import jax.numpy as jnp from mctx._src import action_selection from mctx._src import base from mctx._src import qtransforms from mctx._src import search from mctx._src import seq_halving def _mask_invalid_actions(logits, invalid_actions): """R...
Runs Gumbel MuZero search and returns the `PolicyOutput`. This policy implements Full Gumbel MuZero from "Policy improvement by planning with Gumbel". https://openreview.net/forum?id=bERaNdoegnO At the root of the search tree, actions are selected by Sequential Halving with Gumbel. At non-root nodes (aka interior nodes...
189,481
import functools from typing import Optional, Tuple import chex import jax import jax.numpy as jnp from mctx._src import action_selection from mctx._src import base from mctx._src import qtransforms from mctx._src import search from mctx._src import seq_halving def _mask_invalid_actions(logits, invalid_actions): """R...
Runs Stochastic MuZero search. Implements search as described in the Stochastic MuZero paper: (https://openreview.net/forum?id=X6D9bAHhBQ1). In the shape descriptions, `B` denotes the batch dimension. Args: params: params to be forwarded to root and recurrent functions. rng_key: random number generator state, the key i...
189,482
from typing import Optional, Sequence from absl import app from absl import flags import chex import jax import jax.numpy as jnp import mctx import pygraphviz The provided code snippet includes necessary dependencies for implementing the `convert_tree_to_graph` function. Write a Python function `def convert_tree_to_gr...
Converts a search tree into a Graphviz graph. Args: tree: A `Tree` containing a batch of search data. action_labels: Optional labels for edges, defaults to the action index. batch_index: Index of the batch element to plot. Returns: A Graphviz graph representation of `tree`.
189,483
from typing import Optional, Sequence from absl import app from absl import flags import chex import jax import jax.numpy as jnp import mctx import pygraphviz FLAGS = flags.FLAGS def _make_batched_env_model( batch_size: int, *, transition_matrix: chex.Array, rewards: chex.Array, discounts: chex.Arra...
Runs a search algorithm on a toy environment.
189,484
import functools from typing import Tuple from absl import app from absl import flags import chex import jax import jax.numpy as jnp import mctx FLAGS = flags.FLAGS class DemoOutput: prior_policy_value: chex.Array prior_policy_action_value: chex.Array selected_action_value: chex.Array action_weights_policy_valu...
Runs a search algorithm on random data.
189,485
import multiprocessing import os import pickle from itertools import count from multiprocessing.managers import SyncManager from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any, Callable, Dict, Iterator, Optional, Tuple, Type, cast import dill import pandas as pd import psutil from pa...
null
189,486
import multiprocessing import os import pickle from itertools import count from multiprocessing.managers import SyncManager from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any, Callable, Dict, Iterator, Optional, Tuple, Type, cast import dill import pandas as pd import psutil from pa...
null
189,487
import itertools from enum import Enum from typing import Any, Dict, List, Tuple import pandas as pd from pandas import DataFrame, Index The provided code snippet includes necessary dependencies for implementing the `df_indexed_like` function. Write a Python function `def df_indexed_like(df: DataFrame, axes: List[Inde...
Returns whether a data frame is indexed in the way specified by the provided axes. Used by DataFrameGroupBy to determine whether a group has been modified. Function adapted from pandas.core.groupby.ops._is_indexed_like Parameters ---------- df : DataFrame The data frame in question axes : List[Index] The axes to which ...
189,488
import itertools from enum import Enum from typing import Any, Dict, List, Tuple import pandas as pd from pandas import DataFrame, Index def get_pandas_version() -> Tuple[int, int]: major_str, minor_str, *_ = pd.__version__.split(".") return int(major_str), int(minor_str)
null
189,489
import itertools from enum import Enum from typing import Any, Dict, List, Tuple import pandas as pd from pandas import DataFrame, Index def get_axis_int(user_defined_function_kwargs: Dict[str, Any]): axis = user_defined_function_kwargs.get("axis", 0) if axis not in {0, 1, "index", "columns"}: raise V...
null
189,490
import multiprocessing import os import shutil import sys from abc import ABC, abstractmethod from enum import Enum from itertools import count from time import time_ns from typing import Callable, List, Union from .utils import WorkerStatus INTERVAL_NS = 250_000_000 class ProgressState: def __init__(self, chunk_s...
Wrap the function to apply in a function which monitor the part of work already done.
189,491
from dataclasses import dataclass, field from typing import cast import torch from datasets import load_dataset from transformers import HfArgumentParser, Trainer, TrainingArguments from magicoder.llm_wrapper import ( DecodingConfig, EncodingConfig, TokenizationContext, get_model_context, pad_sequen...
null
189,492
import itertools import json import random import warnings from dataclasses import dataclass, field from pathlib import Path from typing import cast from tqdm.auto import tqdm from transformers import HfArgumentParser from magicoder.utils import read_jsonl, write_jsonl def remove_all_whitespaces(text: str) -> str: ...
null
189,493
import itertools import json import random import warnings from dataclasses import dataclass, field from pathlib import Path from typing import cast from tqdm.auto import tqdm from transformers import HfArgumentParser from magicoder.utils import read_jsonl, write_jsonl def remove_all_whitespaces(text: str) -> str: ...
Filter out data whose solution just copies the problem.
189,494
import itertools import json import random import warnings from dataclasses import dataclass, field from pathlib import Path from typing import cast from tqdm.auto import tqdm from transformers import HfArgumentParser from magicoder.utils import read_jsonl, write_jsonl def write_jsonl(path: str | Path, data: Sequence[...
Save to `output_dir` the analysis of the filtering process: - How many data are filtered out for each language? - How many data are filtered out for each reason? - Examples of filtered data for each reason in each language - Data that are filtered
189,495
from dataclasses import dataclass, field from typing import Literal, cast from datasets import load_dataset from transformers import HfArgumentParser from magicoder.prompt_template import SRC_INSTRUCT_INSTRUCTION_PROMPT from magicoder.utils import N_CORES, read_jsonl, write_jsonl DatasetKey = Literal["evol-instruct", "...
null
189,496
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken The provided code snippet includes necessary dependencies for implementing the `read_jsonl` function. Write a Python functi...
Read lines of JSON from a file (including '\n').
189,497
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken _T = TypeVar("_T") The provided code snippet includes necessary dependencies for implementing the `chunked` function. Write...
Yield successive n-sized chunks from seq.
189,498
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken The provided code snippet includes necessary dependencies for implementing the `retry_with_exponential_backoff` function. W...
Retry a function with exponential backoff.
189,499
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken try: OPENAI_CLIENT: openai.OpenAI | None = openai.OpenAI( base_url=os.getenv("OPENAI_BASE_URL") ) except ope...
null
189,500
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken try: OPENAI_CLIENT: openai.OpenAI | None = openai.OpenAI( base_url=os.getenv("OPENAI_BASE_URL") ) except ope...
null
189,501
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken The provided code snippet includes necessary dependencies for implementing the `num_tokens_from_string` function. Write a P...
Returns the number of tokens in a text string.
189,502
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken def timestamp() -> str: return time.strftime("%Y%m%d_%H%M%S")
null
189,503
import functools import hashlib import json import os import random import time from pathlib import Path from typing import Any, Iterable, Mapping, Sequence, TypeVar import openai import tiktoken def compute_fingerprint(*args: Any, hash_length: int | None = None) -> str: combined = "".join(map(str, args)) cont...
null
189,504
import time from multiprocessing import Pool from tqdm import tqdm def save_shard(shard_tuple): """Save shard""" filename, shard = shard_tuple # use to_json instead to save as json file shard.to_parquet(filename) def shard_dataset(ds, shard_size, output_dir, num_proc): if ds._indices is not None: ...
null
189,505
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset FILTER_OUT = {k: v() for k, v in LAZY_...
Dump the dictionary of benchmark samples that are filtered out
189,506
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def filter_reason_to_benchmark_name(fi...
null
189,507
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def benchmark_name_to_filter_reason(ben...
Iterates on current benchmark-samples. If a sample is found in the cached benchmark-samples, it is removed (it does not need to be searched), and the corresponding data-samples from the cache are added to `exclude_data` Returns: - `updated`: an updated benchmark dict where samples from the cache are removed (they do no...
189,508
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def benchmark_name_to_filter_reason(ben...
filter_out: Dict[str, List[str]] mapping from benchmark name to list of strings that need to be filtered-out. Return True, None if the file should be included in the dataset. Otherwise return False and some metadata about the file excluded
189,509
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def add_dict(dict1: dict, dict2: dict)...
null
189,510
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def concatenate_meta(tmp_meta_dir: str...
null
189,511
import argparse import json import os import shutil from copy import deepcopy from glob import glob from pathlib import Path from datasets import load_dataset from magicoder.utils import write_jsonl from .benchmark_data import FILTER_OUT from .utils import add_dict, shard_dataset def arguments(): parser = argparse...
null
189,512
import itertools import json import os from pathlib import Path from datasets import load_dataset def extract_ds_1000_prompt(prompt: str): if "SOLUTION START" in prompt: assert prompt.count("SOLUTION START") == 1 return prompt.split("SOLUTION START")[0] elif "BEGIN SOLUTION" in prompt: a...
null
189,513
import itertools import json import os from pathlib import Path from datasets import load_dataset def load_mbpp(): MBPP_PATH_NAME = os.getenv("MBPP_PATH", None) assert ( MBPP_PATH_NAME is not None ), "Please set the environment variable MBPP_PATH to the path of `mbpp.jsonl`" MBPP_PATH = Path(MBP...
null
189,514
import itertools import json import os from pathlib import Path from datasets import load_dataset def load_mbpp(): MBPP_PATH_NAME = os.getenv("MBPP_PATH", None) assert ( MBPP_PATH_NAME is not None ), "Please set the environment variable MBPP_PATH to the path of `mbpp.jsonl`" MBPP_PATH = Path(MBP...
null
189,515
import itertools import json import os from pathlib import Path from datasets import load_dataset def extract_docstring(prompt: str) -> str: def human_eval_docstrings(): ds = load_dataset("openai_humaneval", split="test") docstrings = [extract_docstring(v["prompt"]) for v in ds] return docstrings
null
189,516
import itertools import json import os from pathlib import Path from datasets import load_dataset The provided code snippet includes necessary dependencies for implementing the `apps_solutions` function. Write a Python function `def apps_solutions()` to solve the following problem: Solutions column contains a list of ...
Solutions column contains a list of strings
189,517
import itertools import json import os from pathlib import Path from datasets import load_dataset def multipl_e_docstrings(): languages = [ "cpp", "cs", "d", "go", "java", "jl", "js", "lua", "php", "pl", "py", "r", ...
null
189,518
import itertools import json import os from pathlib import Path from datasets import load_dataset def load_dataset_column(dataset: str, column: str, split: str, name=None): ds = load_dataset(dataset, split=split, name=name) res = [sample[column].strip() for sample in ds] # Only return non-empty strings ...
null
189,519
import json import random from dataclasses import dataclass, field from pathlib import Path from typing import cast from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser import magicoder class Args: seed_code_start_index: int # `seed_code_start_index` + ...
null
189,520
import json import random from dataclasses import dataclass, field from pathlib import Path from typing import cast from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser import magicoder def parse_problem_solution(response_text: str) -> tuple[str, str] | None: ...
null
189,521
from __future__ import annotations import gc import hashlib import logging import multiprocessing as mp import os import random import re import struct import time import warnings from collections import defaultdict from itertools import tee from pathlib import Path from typing import Any, Dict, Iterable, List, Tuple, ...
Combined with some datasketch code to better parallelize computation. Parameters ---------- content : str The content to be embedded. idx : int The index of the content. num_perm : int The number of permutations. ngram_size : int The size of n-grams. hashranges : List[Tuple[int, int]] The ranges of hash values. permuta...
189,522
from __future__ import annotations import gc import hashlib import logging import multiprocessing as mp import os import random import re import struct import time import warnings from collections import defaultdict from itertools import tee from pathlib import Path from typing import Any, Dict, Iterable, List, Tuple, ...
Compute the optimal `MinHashLSH` parameter that minimizes the weighted sum of probabilities of false positive and false negative, taken from datasketch. Parameters ---------- threshold : float The threshold for similarity. num_perm : int The number of permutations. false_positive_weight : float The weight of false posi...
189,523
import random from dataclasses import dataclass, field from typing import cast import torch from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser, Trainer, TrainingArguments from magicoder.llm_wrapper import ( DecodingConfig, EncodingConfig, Tokeniza...
null
189,524
import random from dataclasses import dataclass, field from typing import cast import torch from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser, Trainer, TrainingArguments from magicoder.llm_wrapper import ( DecodingConfig, EncodingConfig, Tokeniza...
null
189,525
import random from dataclasses import dataclass, field from typing import cast import torch from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser, Trainer, TrainingArguments from magicoder.llm_wrapper import ( DecodingConfig, EncodingConfig, Tokeniza...
Pad input_ids to the right, create labels by setting the padding tokens to -100, and create attention_mask to ignore the padding tokens
189,526
from pathlib import Path import wget as _wget def wget(url: str, path: Path | None = None) -> Path: if path is None: filename = _wget.detect_filename(url) path = Path(filename) if not path.exists(): _wget.download(url, path.as_posix()) return path
null
189,527
from dataclasses import dataclass, field from typing import Literal, cast from matplotlib.colors import rgb_to_hsv, hsv_to_rgb import matplotlib.pyplot as plt import numpy as np from appdirs import user_cache_dir from datasets import Dataset, concatenate_datasets, load_dataset from InstructorEmbedding import INSTRUCT...
null
189,528
import os import json import argparse from tree_sitter import Language, Parser from pathlib import Path from treelib import Node, Tree from tqdm import tqdm def strip_c_style_comment_delimiters(comment: str) -> str: comment_lines = comment.split('\n') cleaned_lines = [] for l in comment_lines: l = ...
null
189,529
import os import json import argparse from tree_sitter import Language, Parser from pathlib import Path from treelib import Node, Tree from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `get_docstring_summary` function. Write a Python function `def get_docstring_summar...
Get the first lines of the documentation comment up to the empty lines.
189,530
import os import json import argparse from tree_sitter import Language, Parser from pathlib import Path from treelib import Node, Tree from tqdm import tqdm function_node_name = { "cpp": ['function_definition'], # https://github.com/tree-sitter/tree-sitter-cpp/blob/master/grammar.js "csharp": ['method_declarati...
null
189,531
import os import json import argparse from tree_sitter import Language, Parser from pathlib import Path from treelib import Node, Tree from tqdm import tqdm comment_node_name = { "cpp": ['comment'], # https://github.com/tree-sitter/tree-sitter-cpp/blob/master/grammar.js "csharp": ['comment'], # https://github.c...
null
189,532
import itertools from dataclasses import dataclass from pathlib import Path from typing import Literal, TypedDict, cast from evalplus.data import get_human_eval_plus, get_mbpp_plus, write_jsonl from tqdm.auto import tqdm from transformers import HfArgumentParser from experiments.utils import wget from magicoder.llm_wra...
null
189,533
import itertools from dataclasses import dataclass from pathlib import Path from typing import Literal, TypedDict, cast from evalplus.data import get_human_eval_plus, get_mbpp_plus, write_jsonl from tqdm.auto import tqdm from transformers import HfArgumentParser from experiments.utils import wget from magicoder.llm_wra...
null
189,534
import itertools from dataclasses import dataclass from pathlib import Path from typing import Literal, TypedDict, cast from evalplus.data import get_human_eval_plus, get_mbpp_plus, write_jsonl from tqdm.auto import tqdm from transformers import HfArgumentParser from experiments.utils import wget from magicoder.llm_wra...
null
189,535
import itertools from dataclasses import dataclass from pathlib import Path from typing import Literal, TypedDict, cast from evalplus.data import get_human_eval_plus, get_mbpp_plus, write_jsonl from tqdm.auto import tqdm from transformers import HfArgumentParser from experiments.utils import wget from magicoder.llm_wra...
null
189,536
import json from dataclasses import dataclass, field from pathlib import Path from typing import cast from datasets import Dataset, load_dataset from tqdm.auto import tqdm from transformers import HfArgumentParser from magicoder.utils import read_jsonl class Args: data_file: str output_path: str max_conside...
null
189,537
import argparse import json import os from pathlib import Path def get_language(name: str): return name.split("-")[1].split("_")[0]
null
189,538
import os from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Literal, cast from ds1000 import DS1000Dataset, DS1000Problem from tqdm.auto import tqdm from transformers import HfArgumentParser from magicoder.llm_wrapper import ( GenerationConfig, ModelContext, crea...
null
189,539
import os import warnings import logging from typing import Union, Any, Optional, Dict import numpy as np import tensorflow as tf from retinaface import __version__ from retinaface.model import retinaface_model from retinaface.commons import preprocess, postprocess from retinaface.commons.logger import Logger def detec...
Extract detected and aligned faces Args: img_path (str or numpy): given image threshold (float): detection threshold model (Model): pre-trained model can be passed to the function align (bool): enable or disable alignment allow_upscaling (bool): allowing up-scaling expand_face_area (int): expand detected facial area wi...
189,540
import glob import os import os.path as osp import platform import sys from setuptools import find_packages, setup def get_ext(): from torch.utils.cpp_extension import BuildExtension return BuildExtension.with_options( no_python_abi_suffix=True, use_ninja=False )
null
189,541
import glob import os import os.path as osp import platform import sys from setuptools import find_packages, setup WITH_SYMBOLS = os.getenv("WITH_SYMBOLS", "0") == "1" def get_extensions(): import torch from torch.__config__ import parallel_info from torch.utils.cpp_extension import CUDAExtension exte...
null
189,542
import random from typing import Optional, Sequence import numpy as np import torch from datasets.utils import Rays, namedtuple_map from torch.utils.data._utils.collate import collate, default_collate_fn_map from nerfacc.estimators.occ_grid import OccGridEstimator from nerfacc.estimators.prop_net import PropNetEstimato...
Render the pixels of an image.