id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
16,097 | import numpy as np
import scipy.sparse as sparse
import Animation as Animation
The provided code snippet includes necessary dependencies for implementing the `graph` function. Write a Python function `def graph(anim)` to solve the following problem:
Generates a weighted adjacency matrix using local joint distances alo... | Generates a weighted adjacency matrix using local joint distances along the skeletal structure. Joints which are not connected are assigned the weight `0`. Joints which actually have zero distance between them, but are still connected, are perturbed by some minimal amount. The output of this routine can be used with th... |
16,098 | import numpy as np
import scipy.sparse as sparse
import Animation as Animation
def parents_list(parents):
"""
Parameters
----------
parents : (J) ndarray
parents array
Returns
-------
parents : [ndarray]
List of arrays of joint idices for
the parents of each joint
... | Generates a distance matrix for pairwise joint distances along the skeletal structure Parameters ---------- anim : Animation input animation Returns ------- distances : (N, N) ndarray array of pairwise distances along skeletal structure from some joint N to some joint M |
16,099 | import numpy as np
import scipy.sparse as sparse
import Animation as Animation
def edges(parents):
"""
Animation structure edges
Parameters
----------
parents : (J) ndarray
parents array
Returns
-------
edges : (M, 2) ndarray
array of pairs where each
pair contain... | Incidence Matrix Parameters ---------- parents : (J) ndarray parents array Returns ------- incidence : (N, M) ndarray Matrix of N joint positions by M edges which each entry is either 1 or -1 and multiplication by the joint positions returns the an array of vectors along each edge of the structure |
16,100 | import re
import numpy as np
from Animation import Animation
from Quaternions import Quaternions
channelmap = {
'Xrotation' : 'x',
'Yrotation' : 'y',
'Zrotation' : 'z'
}
class Animation:
"""
Animation is a numpy-like wrapper for animation data
Animation data consists of several arrays c... | Reads a BVH file and constructs an animation Parameters ---------- filename: str File to be opened start : int Optional Starting Frame end : int Optional Ending Frame order : str Optional Specifier for joint order. Given as string E.G 'xyz', 'zxy' world : bool If set to true euler angles are applied together in world s... |
16,101 | import re
import numpy as np
from Animation import Animation
from Quaternions import Quaternions
channelmap_inv = {
'x': 'Xrotation',
'y': 'Yrotation',
'z': 'Zrotation',
}
ordermap = {
'x' : 0,
'y' : 1,
'z' : 2,
}
def save_joint(f, anim, names, t, i, order='zyx', positions=False):
f.write("%... | Saves an Animation to file as BVH Parameters ---------- filename: str File to be saved to anim : Animation Animation to save names : [str] List of joint names order : str Optional Specifier for joint order. Given as string E.G 'xyz', 'zxy' frametime : float Optional Animation Frame time positions : bool Optional specfi... |
16,102 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
class Quaternions:
"""
Quaternions ... | input: rotations [T, J, 4], rtpos [T, 3] output: positions [T, J, 3] |
16,103 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
def get_local3d(local_x, view_angle=None):
... | motion: motion in relative joint positions & global root positions [(B,) T, (J - 1) + 1, 3] local_x: [(B,) 3], local x-axis view_angle: [3], the angles to rotate output: motion_proj [(B,) J * 2, T] |
16,104 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
The provided code snippet includes necessar... | positions: [T, J, 3], trimmed (only "chosen_joints") fid_l, fid_r: indices of feet joints (in "chosen_joints") |
16,105 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
def across_from_glb(positions, hips=(2, 6), ... | input: positions [T, J, 3] output: quaters: [T, 1, 4], quaternions that rotate the character around the y-axis to face [0, 0, 1] pivots: [T, 1] in [0, 2pi], the angle from [0, 0, 1] to the current facing direction |
16,106 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
def parse_args():
parser = argparse.Arg... | null |
16,107 | import sys
import os
from os.path import join as pjoin
import argparse
import numpy as np
import scipy.ndimage.filters as filters
from load_skeleton import Skel
from Quaternions_old import Quaternions
from Pivots import Pivots
import BVH
from probe.anim_view import visualize
def phase_from_ft(foot_contact, is_debug=Fal... | null |
16,108 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
class Quaternions:
"""
Quaternions is a wrapper around a numpy ndarray
that allows it to act as if it were an narray of
a quaternion data type.
Therefore add... | Load Animation Object into Maya as Joint Skeleton loads each frame as a new keyfame in maya. If the animation is too slow or too fast perhaps the framerate needs adjusting before being loaded such that it matches the maya scene framerate. Parameters ---------- anim : Animation Animation to load into Scene names : [str]... |
16,109 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
class Animation:
"""
Animation is a numpy-like wrapper for animation data
Animation data consists of several arrays consisting
of F frames and J joints.
The animat... | Load Animation Object from Maya Joint Skeleton Parameters ---------- root : PyNode Root Joint of Maya Skeleton start, end : int, int Start and End frame index of Maya Animation Returns ------- animation : Animation Loaded animation from maya names : [str] Joint names from maya |
16,110 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
def rotations_global(anim):
"""
Global Animation Rotations
This relies on joint ordering
being incremental. That means a joint
J1 must not be a ancestor of J0 if
... | null |
16,111 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
The provided code snippet includes necessary dependencies for implementing the `rotations_load_to_maya` function. Write a Python function `def rotations_load_to_maya(rotations, posit... | Load Rotations into Maya Loads a Quaternions array into the scene via the representation of axis Parameters ---------- rotations : (F, J) Quaternions array of rotations to load into the scene where F = number of frames J = number of joints positions : (F, J, 3) ndarray array of positions to load rotation axis at where:... |
16,112 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
class Quaternions:
"""
Quaternions is a wrapper around a numpy ndarray
that allows it to act as if it were an narray of
a quaternion data type.
Therefore add... | null |
16,113 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
def offset_lengths(anim):
return np.sum(anim.offsets[1:]**2.0, axis=1)**0.5 | null |
16,114 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
def position_lengths(anim):
return np.sum(anim.positions[:,1:]**2.0, axis=2)**0.5 | null |
16,115 | import operator
import numpy as np
import numpy.core.umath_tests as ut
import AnimationStructure
from Quaternions_old import Quaternions
def transforms_multiply(t0s, t1s):
"""
Transforms Multiply
Multiplies two arrays of animation transforms
Parameters
----------
t0s, t1s : (F, J, 4, 4) ndarray
... | null |
16,116 | from typing import Dict, List, Type
from helm.benchmark.model_metadata_registry import ALL_MODELS_METADATA, TEXT_MODEL_TAG, CODE_MODEL_TAG, ModelMetadata
from helm.benchmark.run_expander import RUN_EXPANDERS, RunExpander
class ModelMetadata:
def creator_organization(self) -> str:
def engine(self) -> str:
... | null |
16,117 | from helm.benchmark.config_registry import register_builtin_configs_from_helm_package
def register_builtin_configs_from_helm_package() -> None:
package_path = str(resources.files(CONFIG_PACKAGE))
register_configs_from_directory(package_path)
def on_startup(command: str, dirty: bool):
register_builtin_conf... | null |
16,118 | import argparse
from typing import List, Dict
import re
import sys
from helm.common.hierarchical_logger import hlog
from helm.common.authentication import Authentication
from .accounts import Usage, Account
from .services.remote_service import RemoteService, add_service_args, create_authentication
def render_header(sho... | null |
16,119 | import argparse
from typing import List, Dict
import re
import sys
from helm.common.hierarchical_logger import hlog
from helm.common.authentication import Authentication
from .accounts import Usage, Account
from .services.remote_service import RemoteService, add_service_args, create_authentication
UNLIMITED_QUOTA = "un... | null |
16,120 | import argparse
from typing import List, Dict
import re
import sys
from helm.common.hierarchical_logger import hlog
from helm.common.authentication import Authentication
from .accounts import Usage, Account
from .services.remote_service import RemoteService, add_service_args, create_authentication
def render_header(sho... | null |
16,121 | import argparse
from typing import List, Dict
import re
import sys
from helm.common.hierarchical_logger import hlog
from helm.common.authentication import Authentication
from .accounts import Usage, Account
from .services.remote_service import RemoteService, add_service_args, create_authentication
DEFAULT_SERVER_URL = ... | null |
16,122 | from typing import Callable, Union
from retrying import Retrying
from helm.common.request import RequestResult
from helm.common.tokenization_request import TokenizationRequestResult
from helm.common.hierarchical_logger import hlog
import traceback
import threading
print_lock: threading.Lock = threading.Lock()
class Non... | Create a decorator that will retry with exponential backoff. |
16,123 | from typing import Callable, Union
from retrying import Retrying
from helm.common.request import RequestResult
from helm.common.tokenization_request import TokenizationRequestResult
from helm.common.hierarchical_logger import hlog
import traceback
import threading
class RequestResult:
"""What comes back due to a `... | Fails if `success` of `RequestResult` or `TokenizationRequestResult` is false. |
16,124 | import textwrap
from .query import Query
def dedent(text: str) -> str:
# Remove leading newline
if text.startswith("\n"):
text = text[1:]
text = textwrap.dedent(text)
# Remove trailing new line
if text.endswith("\n"):
text = text[:-1]
return text | null |
16,125 | import copy
import datetime
import random
import string
from typing import Dict, Optional, Callable, List
from dacite import from_dict
from dataclasses import asdict, dataclass, field
from sqlitedict import SqliteDict
from helm.common.authentication import Authentication
from helm.common.general import hlog
DEFAULT_QUO... | Impose the `DEFAULT_QUOTAS` on the `account` if they don't exist, but don't override anything. |
16,126 | import copy
import datetime
import random
import string
from typing import Dict, Optional, Callable, List
from dacite import from_dict
from dataclasses import asdict, dataclass, field
from sqlitedict import SqliteDict
from helm.common.authentication import Authentication
from helm.common.general import hlog
def comput... | null |
16,127 | import copy
import datetime
import random
import string
from typing import Dict, Optional, Callable, List
from dacite import from_dict
from dataclasses import asdict, dataclass, field
from sqlitedict import SqliteDict
from helm.common.authentication import Authentication
from helm.common.general import hlog
def comput... | null |
16,128 | import copy
import datetime
import random
import string
from typing import Dict, Optional, Callable, List
from dacite import from_dict
from dataclasses import asdict, dataclass, field
from sqlitedict import SqliteDict
from helm.common.authentication import Authentication
from helm.common.general import hlog
def comput... | null |
16,129 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,130 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,131 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,132 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,133 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,134 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,135 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,136 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,137 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,138 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,139 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,140 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,141 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,142 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,143 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,144 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,145 | from urllib.parse import unquote_plus
import argparse
import dataclasses
import json
import os
import sys
import time
from dacite import from_dict
import bottle
from helm.benchmark.config_registry import (
register_configs_from_directory,
register_builtin_configs_from_helm_package,
)
from helm.benchmark.model_d... | null |
16,146 | import csv
from datetime import datetime
import os
from threading import Lock
from typing import Dict, List, Sequence
import textwrap
import re
from helm.common.critique_request import CritiqueQuestionTemplate, CritiqueRequest, CritiqueTaskTemplate, QuestionType
from helm.common.general import ensure_directory_exists
f... | Render the Crowd HTML for the template. |
16,147 | import csv
from datetime import datetime
import os
from threading import Lock
from typing import Dict, List, Sequence
import textwrap
import re
from helm.common.critique_request import CritiqueQuestionTemplate, CritiqueRequest, CritiqueTaskTemplate, QuestionType
from helm.common.general import ensure_directory_exists
f... | Exports critique requests. After the calling this, the user should manually upload the generated CSV and Crowd HTML files to the Mechanical Turk web UI. - The requests will be exported to mturk/{template.name}/requests_{timestamp}.csv - The template Crowd HTML will be exported to mturk/{template.name}/layout_{timestamp... |
16,148 | from collections import defaultdict
import csv
import os
from threading import Lock
from typing import Dict, List, Optional, Tuple, Union
import re
import sys
from helm.common.critique_request import (
CritiqueRequest,
CritiqueResponse,
CritiqueTaskTemplate,
QuestionType,
CritiqueRequestResult,
)
fr... | Imports a request result from CSV files. Before calling this, the user should manually download the response CSV files from the Mechanical Turk web UI and place them at turk/{template.name}/Batch_{batch_number}_batch_results.csv |
16,149 | from hashlib import sha512
import json
import threading
from typing import Dict, List, Union, Set, Any
from cattrs import unstructure
from helm.common.hierarchical_logger import hlog
from helm.common.cache import Cache, CacheConfig
from helm.common.critique_request import (
CritiqueQuestionTemplate,
CritiqueReq... | Ensure that the Scale batch exists, creating it if necessary. |
16,150 | import argparse
import json
import requests
import urllib.parse
from dataclasses import asdict
from typing import Any, List, Optional
from helm.common.cache import CacheConfig
from helm.common.cache_backend_config import BlackHoleCacheBackendConfig
from helm.common.authentication import Authentication
from helm.common.... | Add command-line arguments to enable command-line utilities to specify how to connect to a remote server. |
16,151 | import argparse
import json
import requests
import urllib.parse
from dataclasses import asdict
from typing import Any, List, Optional
from helm.common.cache import CacheConfig
from helm.common.cache_backend_config import BlackHoleCacheBackendConfig
from helm.common.authentication import Authentication
from helm.common.... | null |
16,152 | import mako.template
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Tuple, Any
from helm.common.general import parse_hocon
from helm.common.critique_request import CritiqueRequest, CritiqueRequestResult
from helm.common.clip_score_request import CLIPScoreRequest, CL... | `environments` is a map from variable names to a list of strings. Return: a list of environments, where for each variable, we choose one of its string. |
16,153 | import mako.template
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Tuple, Any
from helm.common.general import parse_hocon
from helm.common.critique_request import CritiqueRequest, CritiqueRequestResult
from helm.common.clip_score_request import CLIPScoreRequest, CL... | Substitute `environment` into `prompt` and `settings`. |
16,154 | from abc import ABC, abstractmethod
from typing import List, Optional
from helm.common.tokenization_request import (
TokenizationRequest,
TokenizationRequestResult,
DecodeRequest,
DecodeRequestResult,
)
def cleanup_str(token: str, tokenizer_name: Optional[str] = None) -> str:
"""
Certain tokeniz... | Applies `cleanup_str` to each token in `tokens`. |
16,155 | import os
from typing import Any, Dict, Optional, cast
from threading import Lock
from helm.common.cache import CacheConfig
from helm.common.concurrency import ThreadSafeWrapper
from transformers import AutoTokenizer, PreTrainedTokenizerBase
from helm.common.hierarchical_logger import htrack_block, hlog
from .caching_t... | Resolve some HELM model names to Hugging Face pretrained model name. |
16,156 | from abc import abstractmethod
from dataclasses import asdict
from typing import Any, Dict, List, Optional
from helm.common.cache import Cache, CacheConfig
from helm.common.request import wrap_request_time
from helm.common.tokenization_request import (
TokenizationRequest,
TokenizationRequestResult,
DecodeR... | Applies `cleanup_str` to each token in `tokens`. |
16,157 | import importlib_resources as resources
from helm.common.optional_dependencies import handle_module_not_found_error
import torch
The provided code snippet includes necessary dependencies for implementing the `convert_to_unicode` function. Write a Python function `def convert_to_unicode(text)` to solve the following pr... | Converts `text` to Unicode (if it's not already), assuming utf-8 input. |
16,158 | from threading import Lock
from typing import Optional
from transformers import AutoConfig, AutoModelForCausalLM
from helm.common.cache import CacheConfig
from helm.common.optional_dependencies import OptionalDependencyNotInstalled
from helm.clients.huggingface_client import HuggingFaceClient
_register_open_lm_lock = L... | Register OpenLMForCausalLM for AutoModelForCausalLM. |
16,159 | import os
from typing import Optional
from helm.common.hierarchical_logger import hlog
from helm.common.optional_dependencies import handle_module_not_found_error
try:
import boto3
from botocore.config import Config
except ModuleNotFoundError as e:
handle_module_not_found_error(e, ["aws"])
def hlog(x: Any)... | Create a boto3 client for Amazon Bedrock, with optional configuration overrides Parameters ---------- assumed_role : Optional ARN of an AWS IAM role to assume for calling the Bedrock service. If not specified, the current active credentials will be used. region : Optional name of the AWS Region in which the service sho... |
16,160 | from urllib.parse import urljoin
def get_cohere_url(endpoint: str) -> str:
return urljoin("https://api.cohere.ai", endpoint) | null |
16,161 | from copy import deepcopy
import torch
from transformers import AutoModelForCausalLM
from transformers.generation.stopping_criteria import (
StoppingCriteria,
StoppingCriteriaList,
)
from typing import Any, Dict, List, Optional, TypedDict
from helm.common.cache import CacheConfig
from helm.common.hierarchical_l... | Process the kwargs for HuggingFaceClient. The kwargs passed to HuggingFaceClient will eventually be passed to AutoModel.from_pretrained(). Since the kwargs from HuggingFaceClient may be derived from configuration YAML, they may contain primitive types instead of the unserializable types that AutoModel.from_pretrained()... |
16,162 | from typing import Any, Dict, List, Optional, TypedDict, Union, cast
import json
import requests
import time
import urllib.parse
from helm.common.cache import CacheConfig
from helm.common.hierarchical_logger import htrack_block, hlog
from helm.common.media_object import IMAGE_TYPE, TEXT_TYPE
from helm.common.optional_d... | Return whether a a response failed because of the content moderation filter. |
16,163 | import json
import requests
from typing import Any, Dict, List
from helm.common.cache import CacheConfig
from helm.common.hierarchical_logger import hlog
from helm.common.request import wrap_request_time, Request, RequestResult, Sequence, Token, ErrorFlags
from helm.common.tokenization_request import (
Tokenization... | Return whether a a response failed because of the content moderation filter. |
16,164 | from typing import List, Optional
import torch
The provided code snippet includes necessary dependencies for implementing the `generate` function. Write a Python function `def generate( model: torch.nn.Module, idx: torch.Tensor, max_returned_tokens: int, *, temperature: float = 1.0, top_k: Opti... | Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested. The implementation of this function is modified from A. Karpathy's nanoGPT. Args: model: The model to use. idx: Tensor of shape (T) with indices of the prompt sequence. max_returned_tokens: The maximum number of token... |
16,165 | import json
from abc import ABC, abstractmethod
from typing import List, Mapping, Optional, cast
from helm.common.hierarchical_logger import hlog
from helm.common.media_object import MultimediaObject, TEXT_TYPE
from helm.common.request import Request, RequestResult, Sequence, Token
from helm.common.cache import Cache, ... | Certain providers have bugs where they aren't respecting max_tokens, stop_sequences and the end of text token, so as a hack, we have to manually truncate the suffix of `sequence` and `tokens` as a post-hoc process. This method is unsafe and may produce warnings or incorrect results. Prefer using the safer truncate_and_... |
16,166 | import json
from abc import ABC, abstractmethod
from typing import List, Mapping, Optional, cast
from helm.common.hierarchical_logger import hlog
from helm.common.media_object import MultimediaObject, TEXT_TYPE
from helm.common.request import Request, RequestResult, Sequence, Token
from helm.common.cache import Cache, ... | Truncate a string-only response to respect stop_sequences and max_tokens. This can only be used if all of the following conditions are true: - You have access to the tokenizer. - The request has echo_prompt = False. - The tokenizer supports encoding and decoding. - The tokenizer's tokenize() method supports truncation.... |
16,167 | import json
from abc import ABC, abstractmethod
from typing import List, Mapping, Optional, cast
from helm.common.hierarchical_logger import hlog
from helm.common.media_object import MultimediaObject, TEXT_TYPE
from helm.common.request import Request, RequestResult, Sequence, Token
from helm.common.cache import Cache, ... | Applies `cleanup_str` to each token in `tokens`. |
16,168 | import json
from abc import ABC, abstractmethod
from typing import List, Mapping, Optional, cast
from helm.common.hierarchical_logger import hlog
from helm.common.media_object import MultimediaObject, TEXT_TYPE
from helm.common.request import Request, RequestResult, Sequence, Token
from helm.common.cache import Cache, ... | Generates a unique identifier for a given multimodal prompt. |
16,169 | from copy import deepcopy
from typing import List, Dict, Any, Optional, Union
import requests
from retrying import retry
from helm.common.cache import CacheConfig
from helm.common.request import wrap_request_time, Request, RequestResult, Sequence, Token
from .client import CachingClient, truncate_sequence, cleanup_str
... | Rewrite the raw request given the model. |
16,170 | def getattr_recursive(obj, att):
"""
Return nested attribute of obj
Example: getattr_recursive(obj, 'a.b.c') is equivalent to obj.a.b.c
"""
if att == "":
return obj
i = att.find(".")
if i < 0:
return getattr(obj, att)
else:
return getattr_recursive(getattr(obj, at... | Set nested attribute of obj Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val |
16,171 |
def apply_with_stopping_condition(module, apply_fn, apply_condition=None, stopping_condition=None, **other_args):
if stopping_condition(module):
return
if apply_condition(module):
apply_fn(module, **other_args)
for child in module.children():
apply_with_stopping_condition(
... | null |
16,172 | import torch
from einops import rearrange, repeat
from einops_exts import rearrange_many
from torch import einsum, nn
def exists(val):
return val is not None | null |
16,173 | import torch
from einops import rearrange, repeat
from einops_exts import rearrange_many
from torch import einsum, nn
def FeedForward(dim, mult=4):
inner_dim = int(dim * mult)
return nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, inner_dim, bias=False),
nn.GELU(),
nn.Linear(in... | null |
16,174 | from typing import Optional
from transformers import AutoModelForCausalLM, AutoTokenizer
from helm.common.general import handle_module_not_found_error
from .flamingo import Flamingo
from .flamingo_lm import FlamingoLMMixin
from .utils import extend_instance
def _infer_decoder_layers_attr_name(model):
for k in __KNO... | Initialize a Flamingo model from a pretrained vision encoder and language encoder. Appends special tokens to the tokenizer and freezes backbones. Args: clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32") clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "... |
16,175 | import os
from functools import partial
from helm.common.optional_dependencies import handle_module_not_found_error
def handle_module_not_found_error(e: ModuleNotFoundError, suggestions: Optional[List[str]] = None):
# TODO: Ask user to install more specific optional dependencies
# e.g. crfm-helm[plots] or crfm... | null |
16,176 | import torch
import torch.nn as nn
from typing import Tuple, Optional
def nonlinearity(x):
# swish
return x * torch.sigmoid(x) | null |
16,177 | import torch
import torch.nn as nn
from typing import Tuple, Optional
def Normalize(in_channels):
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) | null |
16,178 | import torch
from typing import Optional
from tqdm import tqdm
from torch.nn import functional as F
def cutoff_topk_logits(logits: torch.FloatTensor, k: int) -> torch.FloatTensor:
if k is None:
return logits
else:
v, ix = torch.topk(logits, k)
out = logits.clone()
out[out < v[:, ... | null |
16,179 | import os
import random
import urllib
import hashlib
import tarfile
import torch
import numpy as np
from torch.nn import functional as F
from tqdm import tqdm
from helm.common.optional_dependencies import handle_module_not_found_error
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.ma... | null |
16,180 | import os
import random
import urllib
import hashlib
import tarfile
import torch
import numpy as np
from torch.nn import functional as F
from tqdm import tqdm
from helm.common.optional_dependencies import handle_module_not_found_error
def handle_module_not_found_error(e: ModuleNotFoundError, suggestions: Optional[List... | null |
16,181 | import os
import random
import urllib
import hashlib
import tarfile
import torch
import numpy as np
from torch.nn import functional as F
from tqdm import tqdm
from helm.common.optional_dependencies import handle_module_not_found_error
def download(url: str, root: str) -> str:
def realpath_url_or_path(url_or_path: str,... | null |
16,182 | from typing import Optional, List
from dataclasses import dataclass, field
from helm.common.optional_dependencies import handle_module_not_found_error
class DefaultConfig:
dataset: DataConfig = DataConfig()
stage1: Stage1Config = Stage1Config()
stage2: Stage2Config = Stage2Config()
class FineTuningConfig:
... | null |
16,183 | import torch
from helm.common.optional_dependencies import handle_module_not_found_error
def get_masks_and_position_ids_coglm(seq, context_length):
tokens = seq.unsqueeze(0)
attention_mask = torch.ones((1, len(seq), len(seq)), device=tokens.device)
attention_mask.tril_()
attention_mask[..., :context_le... | null |
16,184 | import torch
from helm.common.optional_dependencies import handle_module_not_found_error
def get_recipe(name):
r = {
"attn_plus": 1.4,
"temp_all_gen": 1.15,
"topk_gen": 16,
"temp_cluster_gen": 1.0,
"temp_all_dsr": 1.5,
"topk_dsr": 100,
"temp_cluster_dsr": 0.8... | null |
16,185 | import math
import torch
import torch.nn.functional as F
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `sparse_attention_2d_text` function. Write a Python function `def sparse_attention_2d_text( q0, k0,... | q0, k0, v0: [batch_size, 16, hidden_size] q1, k1, v1: [batch_size, 3600, hidden_size] n_head: int attention_mask: [batch_size, 16] |
16,186 | import math
import torch
import torch.nn.functional as F
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `sparse_attention_2d_notext` function. Write a Python function `def sparse_attention_2d_notext( q0, ... | q0, k0, v0: [batch_size, 16, hidden_size] q1, k1, v1: [batch_size, 3600, hidden_size] n_head: int attention_mask: [batch_size, 16] |
16,187 | import math
import torch
import torch.nn.functional as F
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `sparse_attention_2d_light` function. Write a Python function `def sparse_attention_2d_light( q0, k... | q0, k0, v0: [batch_size, 1088, hidden_size] q1, k1, v1: [batch_size, 4096, h2] n_head: int attention_mask: [batch_size, 1088, 1088] |
16,188 | import os
import math
import torch
import torch.nn.functional as F
import numpy as np
def top_k_logits_(logits, top_k=0, filter_value=-float("Inf")):
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
return logits | null |
16,189 | import os
import math
import torch
import torch.nn.functional as F
import numpy as np
class IterativeEntfilterStrategy:
def __init__(self, invalid_slices=[], temperature=1.0, topk=6, temperature2=0.9):
self.invalid_slices = invalid_slices
self.temperature = temperature
self.topk = topk
... | seq: [PAD]... [ROI1] text ... [BOI1] {layout[0]} 1024 {layout[1]} [EOI1] 4095 {layout[2]} final_token. Attention: The sampling temperature are changing, temporally we hard code them here. The temperature in the strategy is not used. |
16,190 | import torch
import torch.nn.functional as F
from icetk import icetk as tokenizer
def top_k_logits_(logits, top_k=0, filter_value=-float("Inf")):
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
return logits | null |
16,191 | import torch
import torch.nn.functional as F
from icetk import icetk as tokenizer
class IterativeEntfilterStrategy:
def __init__(self, invalid_slices=[], temperature=1.0, topk=10):
self.invalid_slices = invalid_slices
self.temperature = temperature
self.topk = topk
def forward(self, logi... | seq: [PAD]... [ROI1] text ... [BOI1] {layout[0]} 1024 {layout[1]} [EOI1] 4095 {layout[2]} final_token. Attention: The sampling temperature are changing, temporally we hard code them here. The temperature in the strategy is not used. |
16,192 | import os
import torch
import numpy as np
import torch.nn.functional as F
def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-65504):
# This function has been mostly taken from huggingface conversational ai code at
# https://medium.com/huggingface/how-to-build-a-state-of-the-art-conversational-ai-with-t... | null |
16,193 | import re
import torch
from .modeling_flax_vqgan import VQModel
from .configuration_vqgan import VQGANConfig
from helm.common.optional_dependencies import handle_module_not_found_error
def rename_key(key):
def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model):
class VQModel(VQGANPreTrainedModel):
class VQ... | null |
16,194 | import random
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
import numpy as np
from datasets import Dataset, load_dataset
from .model.text import TextNormalizer
from helm.common.optional_dependencies import handle_module_not_found_error
def blank_caption_function(examp... | null |
16,195 | import random
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
import numpy as np
from datasets import Dataset, load_dataset
from .model.text import TextNormalizer
from helm.common.optional_dependencies import handle_module_not_found_error
def normalize_function(example, ... | null |
16,196 | import random
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
import numpy as np
from datasets import Dataset, load_dataset
from .model.text import TextNormalizer
from helm.common.optional_dependencies import handle_module_not_found_error
def filter_function(
example... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.