id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
16,197 | 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 shift_tokens_right(input_ids: np.array, decoder_start_token_id: int):
"""
Shift input ids one token to the right.
"""
shifted_input_ids = np.zeros(input_ids.shape)
shifted_input_ids[:, 1:] = input_ids[:, :-1]
shifted_input_ids[:, 0] = decoder_start_token_id
return shifted_input_ids
def preprocess_function(
examples,
tokenizer,
text_column,
encoding_column,
max_length,
decoder_start_token_id,
):
inputs = examples[text_column]
# Setting padding="max_length" as we need fixed length inputs for jitted functions
model_inputs = tokenizer(
inputs,
max_length=max_length,
padding="max_length",
truncation=True,
return_tensors="np",
)
# set up targets
# Note: labels correspond to our target indices
# decoder input ids are the same but shifted to the right with bos at the beginning (and without last token)
labels = examples[encoding_column]
labels = np.asarray(labels)
# We need the labels, in addition to the decoder_input_ids, for the compute_loss function
model_inputs["labels"] = labels
# In our case, this prepends the bos token and removes the last one
decoder_input_ids = shift_tokens_right(labels, decoder_start_token_id)
model_inputs["decoder_input_ids"] = decoder_input_ids
return model_inputs | null |
16,198 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
person_token = [("a person", 282265), ("someone", 121194), ("somebody", 12219)]
The provided code snippet includes necessary dependencies for implementing the `replace_person_token` function. Write a Python function `def replace_person_token(t)` to solve the following problem:
Used for CC12M
Here is the function:
def replace_person_token(t):
"Used for CC12M"
t = re.sub("<person>([,\s]*(and)*[,\s]*<person>)+", " people ", t)
while "<person>" in t:
t = t.replace("<person>", f" {random.choices(*tuple(zip(*person_token)))[0]} ", 1)
return t | Used for CC12M |
16,199 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def fix_html(t):
# from OpenAI CLIP
return html.unescape(html.unescape(t)) | null |
16,200 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def replace_punctuation_with_commas(t):
return re.sub("[()[\].,|:;?!=+~\-\/{}]", ",", t) | null |
16,201 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def simplify_quotes(t):
return re.sub("""['"`]""", ' " ', t) | null |
16,202 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def merge_quotes(t):
return re.sub('(\s*"+\s*)+', ' " ', t) | null |
16,203 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def remove_comma_numbers(t):
def _f(t):
return re.sub("(\d),(\d{3})", r"\1\2", t)
return _f(_f(t)) | null |
16,204 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def pre_process_dot_numbers(t):
return re.sub("(\w)\.(\w)", rf"\1{temp_token}dot{temp_token}\2", t) | null |
16,205 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def post_process_dot_numbers(t):
return re.sub(f"{temp_token}dot{temp_token}", ".", t) | null |
16,206 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def pre_process_quotes(t):
# allows quotes only for 's, 't, 'd, 'm, 'll, 're, 've
return re.sub(r"'(?=([stdm]|(ll)|(re)|(ve)|(ll))\b)", rf"{temp_token}quote{temp_token}", t) | null |
16,207 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def post_process_quotes(t):
return re.sub(f"{temp_token}quote{temp_token}", "'", t) | null |
16,208 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def pre_process_dates(t):
return re.sub("(\d)/(\d)", rf"\1{temp_token}slash{temp_token}\2", t) | null |
16,209 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
temp_token = "xtokx"
def post_process_dates(t):
return re.sub(f"{temp_token}slash{temp_token}", "/", t) | null |
16,210 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def merge_commas(t):
return re.sub("(\s*,+\s*)+", ", ", t) | null |
16,211 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def add_space_after_commas(t):
return re.sub(",", ", ", t) | null |
16,212 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `handle_special_chars` function. Write a Python function `def handle_special_chars(t)` to solve the following problem:
Handle special characters
Here is the function:
def handle_special_chars(t):
"Handle special characters"
# replace "-" with a space when between words without space
t = re.sub("(\w)-(\w)", r"\1 \2", t)
# always add space around some characters
return re.sub("([%&\/$*])", r" \1 ", t) | Handle special characters |
16,213 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `expand_hashtags` function. Write a Python function `def expand_hashtags(t, hashtag_processor)` to solve the following problem:
Remove # and try to split words
Here is the function:
def expand_hashtags(t, hashtag_processor):
"Remove # and try to split words"
return re.sub("#(\w+)", lambda m: hashtag_processor(m.group(1)), t) | Remove # and try to split words |
16,214 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
_re_ignore_chars = r"[_#\\]"
The provided code snippet includes necessary dependencies for implementing the `ignore_chars` function. Write a Python function `def ignore_chars(t)` to solve the following problem:
Ignore useless characters
Here is the function:
def ignore_chars(t):
"Ignore useless characters"
return re.sub(_re_ignore_chars, " ", t) | Ignore useless characters |
16,215 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `remove_extra_spaces` function. Write a Python function `def remove_extra_spaces(t)` to solve the following problem:
Remove extra spaces (including \t and \n)
Here is the function:
def remove_extra_spaces(t):
"Remove extra spaces (including \t and \n)"
return re.sub("\s+", " ", t) | Remove extra spaces (including \t and \n) |
16,216 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `remove_repeating_chars` function. Write a Python function `def remove_repeating_chars(t)` to solve the following problem:
If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance
Here is the function:
def remove_repeating_chars(t):
"If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance"
return re.sub(r"(\D)(\1{3,})", r"\1", t) | If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance |
16,217 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def remove_urls(t):
return re.sub(r"http\S+", "", t) | null |
16,218 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def remove_html_tags(t):
return re.sub("<[^<]+?>", " ", t) | null |
16,219 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def remove_first_last_commas(t):
t = t.strip()
t = t[:-1] if t and t[-1] == "," else t
t = t[1:] if t and t[0] == "," else t
return t.strip() | null |
16,220 | import html
import math
import random
import re
from pathlib import Path
import emoji
from huggingface_hub import hf_hub_download
from helm.common.optional_dependencies import handle_module_not_found_error
def remove_wiki_ref(t):
t = re.sub(r"\A\s*\[\d+\]", "", t)
return re.sub(r"\[\d+\]\s*\Z", "", t) | null |
16,221 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from transformers.generation.configuration_utils import GenerationConfig
from helm.common.optional_dependencies import handle_module_not_found_error
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
The provided code snippet includes necessary dependencies for implementing the `smelu` function. Write a Python function `def smelu(beta: Any = 1.0)` to solve the following problem:
Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations" https://arxiv.org/abs/2202.06499
Here is the function:
def smelu(beta: Any = 1.0):
"""
Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations"
https://arxiv.org/abs/2202.06499
"""
@custom_jvp
@jax.jit
def _smelu(x: Any) -> Any:
x = jnp.where(x <= -beta, 0.0, x)
return jnp.where(x >= beta, x, jnp.square(x + beta) / (4 * beta))
_smelu.defjvps(
lambda g, ans, x: lax.select(
x == -beta,
lax.full_like(g, 0),
lax.select(x == beta, lax.full_like(g, 1), g),
)
)
return _smelu | Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations" https://arxiv.org/abs/2202.06499 |
16,222 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from transformers.generation.configuration_utils import GenerationConfig
from helm.common.optional_dependencies import handle_module_not_found_error
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
def deepnet_init(init_std, gain=1):
init = jax.nn.initializers.normal(init_std)
def _init(*args, **kwargs):
return gain * init(*args, **kwargs)
return _init | null |
16,223 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from transformers.generation.configuration_utils import GenerationConfig
from helm.common.optional_dependencies import handle_module_not_found_error
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
class RMSNorm(nn.Module):
"""
From "Root Mean Square Layer Normalization" by https://arxiv.org/abs/1910.07467
Adapted from flax.linen.LayerNorm
"""
epsilon: float = 1e-6
dtype: Any = jnp.float32
param_dtype: Any = jnp.float32
use_scale: bool = True
scale_init: Any = jax.nn.initializers.ones
def __call__(self, x):
reduction_axes = (-1,)
feature_axes = (-1,)
rms_sq = self._compute_rms_sq(x, reduction_axes)
return self._normalize(
self,
x,
rms_sq,
reduction_axes,
feature_axes,
self.dtype,
self.param_dtype,
self.epsilon,
self.use_scale,
self.scale_init,
)
def _compute_rms_sq(self, x, axes):
x = jnp.asarray(x, jnp.promote_types(jnp.float32, jnp.result_type(x)))
rms_sq = jnp.mean(jax.lax.square(x), axes)
return rms_sq
def _normalize(
self,
mdl,
x,
rms_sq,
reduction_axes,
feature_axes,
dtype,
param_dtype,
epsilon,
use_scale,
scale_init,
):
reduction_axes = nn.normalization._canonicalize_axes(x.ndim, reduction_axes)
feature_axes = nn.normalization._canonicalize_axes(x.ndim, feature_axes)
stats_shape = list(x.shape)
for axis in reduction_axes:
stats_shape[axis] = 1
rms_sq = rms_sq.reshape(stats_shape)
feature_shape = [1] * x.ndim
reduced_feature_shape = []
for ax in feature_axes:
feature_shape[ax] = x.shape[ax]
reduced_feature_shape.append(x.shape[ax])
mul = lax.rsqrt(rms_sq + epsilon)
if use_scale:
scale = mdl.param("scale", scale_init, reduced_feature_shape, param_dtype).reshape(feature_shape)
mul *= scale
y = mul * x
return jnp.asarray(y, dtype)
def norm(type, *args, **kwargs):
if type == "rmsnorm":
return RMSNorm(*args, **kwargs)
elif type == "layernorm":
return nn.LayerNorm(*args, **kwargs)
else:
raise ValueError(f"Unknown norm type {type}") | null |
16,224 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from transformers.generation.configuration_utils import GenerationConfig
from helm.common.optional_dependencies import handle_module_not_found_error
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
The provided code snippet includes necessary dependencies for implementing the `dot_product_attention_weights` function. Write a Python function `def dot_product_attention_weights( query: Any, key: Any, bias: Optional[Any] = None, mask: Optional[Any] = None, embed_pos: Optional[Any] = None, broadcast_dropout: bool = True, dropout_rng: Optional[PRNGKey] = None, dropout_rate: float = 0.0, deterministic: bool = False, dtype: Any = jnp.float32, precision: PrecisionLike = None, sinkhorn_iters: int = 1, is_encoder: bool = False, tau=None, )` to solve the following problem:
Computes dot-product attention weights given query and key. mask is included into the bias. Adapted from flax.linen.attention.dot_product_attention_weights"
Here is the function:
def dot_product_attention_weights(
query: Any,
key: Any,
bias: Optional[Any] = None,
mask: Optional[Any] = None,
embed_pos: Optional[Any] = None,
broadcast_dropout: bool = True,
dropout_rng: Optional[PRNGKey] = None,
dropout_rate: float = 0.0,
deterministic: bool = False,
dtype: Any = jnp.float32,
precision: PrecisionLike = None,
sinkhorn_iters: int = 1,
is_encoder: bool = False,
tau=None,
):
"""
Computes dot-product attention weights given query and key.
mask is included into the bias.
Adapted from flax.linen.attention.dot_product_attention_weights"
"""
assert query.ndim == key.ndim, "q, k must have same rank."
assert query.shape[:-3] == key.shape[:-3], "q, k batch dims must match."
assert query.shape[-2] == key.shape[-2], "q, k num_heads must match."
assert query.shape[-1] == key.shape[-1], "q, k depths must match."
# attn weight shape is (batch..., num_heads, q_length, kv_length)
attn_weights = jnp.einsum("...qhd,...khd->...hqk", query, key, precision=precision)
# divide by tau (used in Swin v2)
if tau is not None:
attn_weights = attn_weights / tau
else:
depth = query.shape[-1]
attn_weights = attn_weights / jnp.sqrt(depth).astype(dtype)
# apply attention bias: masking, dropout, proximity bias, etc.
if bias is not None:
attn_weights = attn_weights + bias
# add relative position
if embed_pos is not None:
attn_weights = attn_weights + embed_pos
# normalize the attention weights
if not is_encoder or sinkhorn_iters == 1:
# sinkhorn does not work for causal (leaks info of future tokens into past)
attn_weights = jax.nn.softmax(attn_weights).astype(dtype)
else:
# adapted from https://github.com/lucidrains/sinkhorn-transformer
for i in range(sinkhorn_iters):
# when causal, some attn_weights have been set to -inf through bias
if i % 2 == 0:
attn_weights -= jax.nn.logsumexp(attn_weights, axis=-1, keepdims=True)
else:
attn_weights -= jax.nn.logsumexp(attn_weights, axis=-2, keepdims=True)
if mask is not None:
attn_weights = jnp.where(mask, attn_weights, -jnp.inf)
attn_weights = jnp.exp(attn_weights).astype(dtype)
# apply attention dropout
if not deterministic and dropout_rate > 0.0:
keep_prob = 1.0 - dropout_rate
if broadcast_dropout:
# dropout is broadcast across the batch + head dimensions
dropout_shape = tuple([1] * (key.ndim - 2)) + attn_weights.shape[-2:]
keep = jax.random.bernoulli(dropout_rng, keep_prob, dropout_shape)
else:
keep = jax.random.bernoulli(dropout_rng, keep_prob, attn_weights.shape)
multiplier = keep.astype(attn_weights.dtype) / jnp.asarray(keep_prob, dtype=dtype)
attn_weights = attn_weights * multiplier
return attn_weights | Computes dot-product attention weights given query and key. mask is included into the bias. Adapted from flax.linen.attention.dot_product_attention_weights" |
16,225 | import re
from helm.common.optional_dependencies import handle_module_not_found_error
_unmatched = object()
def _replacement_rules(rules):
def replace(key, val):
for rule, replacement in rules:
if _match(rule, key):
return replacement
return val
return replace
def _get_partition_rules():
return [
# embeddings
(("embed_positions", "embedding"), P("mp", None)),
(("embed_tokens", "embedding"), P("mp", None)),
(("rel_bias", "embedding"), P(None, "mp")),
# attention
(("(q_proj|k_proj|v_proj)", "kernel"), P(None, "mp")),
(("out_proj", "kernel"), P("mp", None)),
# FFN
(("Dense_0", "kernel"), P(None, "mp")),
(("GLU.*", "Dense_1", "kernel"), P(None, "mp")),
(("GLU.*", "Dense_2", "kernel"), P("mp", None)),
(("FFN.*", "Dense_1", "kernel"), P("mp", None)),
# layer norms
(("(bias|scale)",), None),
(("lm_head", "kernel"), P(None, "mp")),
# head scale and tau
(("(head_scale|tau)",), None),
]
def set_partitions(in_dict, use_scan):
rules = _get_partition_rules()
replace = _replacement_rules(rules)
initd = {k: _unmatched for k in flatten_dict(in_dict)}
result = {k: replace(k, v) for k, v in initd.items()}
for k, v in result.items():
if v == _unmatched:
print(f"Unmatched -> {k}")
l = list(result.keys())
if use_scan:
# add None dimension to layers
result = {
k: (P(*(None,) + v) if v is not None else None)
if any(x in k for x in ["FlaxBartEncoderLayers", "FlaxBartDecoderLayers"])
else v
for k, v in result.items()
}
assert _unmatched not in result.values(), "Incomplete partition spec."
return freeze(unflatten_dict(result)) | null |
16,226 | from helm.common.media_object import MediaObject, MultimediaObject
class MediaObject:
"""A media object e.g., image, video, audio, etc."""
content_type: str
"""A valid Multipurpose Internet Mail Extensions (MIME) type for this media object in the format `<type>/<subtype>`.
IANA is the official registry of MIME media types and maintains a list of all the official MIME types:
https://www.iana.org/assignments/media-types/media-types.xhtml
Some common MIME types can be found here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
"""
text: Optional[str] = None
"""When the `type` of media object is text."""
location: Optional[str] = None
"""When the media object is a file, specify the location of the media object, which can be a local path or URL."""
def type(self) -> str:
"""The MIME type of the media object."""
return self.content_type.split("/")[0]
def subtype(self) -> str:
"""The MIME subtype of the media object."""
return self.content_type.split("/")[1]
def is_local_file(self) -> bool:
"""Returns `True` if the media object is a local file and False if `location` is a URL."""
if self.location is None:
return False
return urllib.parse.urlparse(self.location).scheme not in ["http", "https"]
def __post_init__(self):
"""Validates the media object field values."""
# Verify that the `mime_type` is in the correct format
assert len(self.content_type.split("/")) == 2, f"Invalid MIME type: {self.content_type}"
if self.type == TEXT_TYPE:
assert self.text is not None
assert self.location is None
else:
assert self.text is None
assert self.location is not None
# Checks that the `location` is a valid local file path
if self.is_local_file:
assert os.path.exists(self.location), f"Local file does not exist at path: {self.location}"
def is_type(self, media_type: str) -> bool:
"""Returns `True` if the media object is of the specified type."""
return self.type == media_type
class MultimediaObject:
"""Represents a sequence of `MediaObject`s."""
media_objects: List[MediaObject] = field(default_factory=list)
"""The sequence of `MediaObject`s."""
def add_textual_prefix(self, prefix: str) -> "MultimediaObject":
"""
Returns a new `MultimediaObject` with a textual prefix added to the beginning of the multimodal sequence.
:param prefix: The prefix to add.
:return: New multimodal object with prefix.
"""
result: MultimediaObject = deepcopy(self)
if not prefix:
return result
start: MediaObject = result.media_objects[0]
if start.is_type(TEXT_TYPE) and start.text:
result.media_objects[0] = replace(result.media_objects[0], text=prefix + start.text)
else:
result.media_objects.insert(0, MediaObject(text=prefix, content_type="text/plain"))
return result
def add_textual_suffix(self, suffix: str) -> "MultimediaObject":
"""
Returns a new `MultimediaObject` with a textual suffix added to the end of the multimodal sequence.
:param suffix: The suffix to add.
:return: New multimodal content with suffix.
"""
result: MultimediaObject = deepcopy(self)
if not suffix:
return result
end: MediaObject = result.media_objects[-1]
if end.is_type(TEXT_TYPE) and end.text:
result.media_objects[-1] = replace(result.media_objects[-1], text=end.text + suffix)
else:
result.media_objects.append(MediaObject(text=suffix, content_type="text/plain"))
return result
def combine(self, other: "MultimediaObject") -> "MultimediaObject":
"""
Return a new `MultimediaObject` that contains the contents of this object and the other object.
:param other: The other multimodal content.
:return: The combined multimodal content.
"""
return MultimediaObject(media_objects=self.media_objects + other.media_objects)
def size(self) -> int:
"""
Get the number of `MediaObject`s in this multimodal content.
:return: The number of `MediaObject`s .
"""
return len(self.media_objects)
def text(self) -> str:
"""
Get the text-only part of this multimodal content.
:return: The text-only representation.
"""
return "".join(item.text for item in self.media_objects if item.is_type(TEXT_TYPE) and item.text)
The provided code snippet includes necessary dependencies for implementing the `get_single_image_multimedia_object` function. Write a Python function `def get_single_image_multimedia_object(image_location: str) -> MultimediaObject` to solve the following problem:
Returns a `MultimediaObject` containing a single image file used for text-to-image generation clients.
Here is the function:
def get_single_image_multimedia_object(image_location: str) -> MultimediaObject:
"""
Returns a `MultimediaObject` containing a single image file used for text-to-image generation clients.
"""
file_extension: str = image_location.split(".")[-1]
return MultimediaObject([MediaObject(content_type=f"image/{file_extension}", location=image_location)]) | Returns a `MultimediaObject` containing a single image file used for text-to-image generation clients. |
16,227 | from typing import Dict
class AI21RequestError(Exception):
pass
def handle_failed_request(api_type: str, response: Dict):
error_message: str = f"AI21 {api_type} API error -"
# Error messages are returned via 'detail' or 'Error' in response
if "detail" in response:
error_message += f" Detail: {response['detail']}"
if "Error" in response:
error_message += f" Error: {response['Error']}"
raise AI21RequestError(error_message) | null |
16,228 | import re
import subprocess
from typing import Mapping, Set, Union
from retrying import retry
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `submit_slurm_job` function. Write a Python function `def submit_slurm_job(command: str, slurm_args: Mapping[str, Union[str, int]]) -> int` to solve the following problem:
Submit a Slurm job.
Here is the function:
def submit_slurm_job(command: str, slurm_args: Mapping[str, Union[str, int]]) -> int:
"""Submit a Slurm job."""
slurm = Slurm(**slurm_args)
return slurm.sbatch(command) | Submit a Slurm job. |
16,229 | import re
import subprocess
from typing import Mapping, Set, Union
from retrying import retry
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `get_slurm_job_state` function. Write a Python function `def get_slurm_job_state(job_id: int) -> str` to solve the following problem:
Get the state of a Slurm job.
Here is the function:
def get_slurm_job_state(job_id: int) -> str:
"""Get the state of a Slurm job."""
try:
scontrol_output = subprocess.check_output(f"scontrol show job {job_id}", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
# Default CalledProcessError message doesn't have output, so re-raise here to include the output.
raise Exception(f"{str(e)} output: {e.output}")
search_result = re.search("JobState=(\w+)", scontrol_output.decode())
if not search_result:
raise Exception(f"Could not extract JobState from scontrol: {scontrol_output.decode()}")
return search_result.group(1) | Get the state of a Slurm job. |
16,230 | import re
import subprocess
from typing import Mapping, Set, Union
from retrying import retry
from helm.common.optional_dependencies import handle_module_not_found_error
The provided code snippet includes necessary dependencies for implementing the `cancel_slurm_job` function. Write a Python function `def cancel_slurm_job(job_id: int) -> None` to solve the following problem:
Cancel a Slurm job.
Here is the function:
def cancel_slurm_job(job_id: int) -> None:
"""Cancel a Slurm job."""
try:
# Note: scancel will execute successfully on any existing job, even if the job is already terminated.
subprocess.check_output(f"scancel {job_id}", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
# Default CalledProcessError message doesn't have output, so re-raise here to include the output.
raise Exception(f"{str(e)} output: {e.output}") | Cancel a Slurm job. |
16,231 | from abc import ABC, abstractmethod
from dataclasses import replace
from random import Random
from typing import List, Optional
from .perturbation_description import PerturbationDescription
from helm.benchmark.scenarios.scenario import Input, Instance, Reference, Output
from helm.common.object_spec import ObjectSpec, create_object
class Perturbation(ABC):
# Unique name to describe perturbation
name: str
# Whether to perturb references
should_perturb_references: bool = False
def description(self) -> PerturbationDescription:
"""Description of the perturbation."""
return PerturbationDescription(name=self.name)
def get_rng(self, instance: Instance, seed: Optional[int] = None) -> Random:
"""Creates a random number generator using the `Instance` id and `seed`."""
assert instance.id is not None
# If seed exists, use it as part of the random seed
return Random(instance.id if seed is None else str(seed) + instance.id)
def apply(self, instance: Instance, seed: Optional[int] = None) -> Instance:
"""Generate a modified instance from the input instance."""
pass
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def create_object(spec: ObjectSpec):
"""Create the actual object given the `spec`."""
cls = get_class_by_name(spec.class_name)
args = {}
args.update(spec.args)
return cls(**args)
The provided code snippet includes necessary dependencies for implementing the `create_perturbation` function. Write a Python function `def create_perturbation(perturbation_spec: PerturbationSpec) -> Perturbation` to solve the following problem:
Creates Perturbation from PerturbationSpec.
Here is the function:
def create_perturbation(perturbation_spec: PerturbationSpec) -> Perturbation:
"""Creates Perturbation from PerturbationSpec."""
return create_object(perturbation_spec) | Creates Perturbation from PerturbationSpec. |
16,232 | import os
import re
from collections import defaultdict
from dataclasses import dataclass, replace
from functools import reduce
from pathlib import Path
from random import Random
from typing import Dict, List, Optional, Set
from helm.benchmark.scenarios.scenario import Input, Instance, Reference, Output
from helm.common.general import ensure_file_downloaded, ensure_directory_exists, match_case
from .perturbation_description import PerturbationDescription
from .perturbation import Perturbation
def lambda_defaultdict_list():
return defaultdict(list) | null |
16,233 | from dataclasses import dataclass, field
from typing import List
from helm.common.hierarchical_logger import htrack, hlog
from helm.common.general import parallel_map
from helm.benchmark.augmentations.perturbation import (
Perturbation,
PerturbationSpec,
create_perturbation,
)
from helm.benchmark.scenarios.scenario import Instance
class DataAugmenter:
# Perturbations to apply to generate new instances
perturbations: List[Perturbation]
def generate(
self,
instances: List[Instance],
include_original: bool = True,
skip_unchanged: bool = False,
seeds_per_instance: int = 1,
parallelism: int = 1,
) -> List[Instance]:
"""
Given a list of Instances, generate a new list of perturbed Instances.
include_original controls whether to include the original Instance in the new list of Instances.
skip_unchanged controls whether we include instances for which the perturbation did not change the input.
"""
processor = Processor(
include_original=include_original,
skip_unchanged=skip_unchanged,
perturbations=self.perturbations,
seeds_per_instance=seeds_per_instance,
)
results: List[List[Instance]] = parallel_map(
processor.process,
instances,
parallelism=parallelism,
)
output_instances = [instance for result in results for instance in result]
hlog(f"{len(instances)} instances augmented to {len(output_instances)} instances")
return output_instances
class DataAugmenterSpec:
# List of perturbation specs to use to augment the data
perturbation_specs: List[PerturbationSpec] = field(default_factory=list)
# Whether to augment train instances
should_augment_train_instances: bool = False
# Whether to include the original instances in the augmented set of train instances
should_include_original_train: bool = False
# Whether to include train instances which were unaffected by the perturbation
should_skip_unchanged_train: bool = False
# Whether to augment val/test instances
should_augment_eval_instances: bool = False
# Whether to include the original instances in the augmented set of val/test instances
should_include_original_eval: bool = False
# Whether to include val/test instances which were unaffected by the perturbation
should_skip_unchanged_eval: bool = False
# How many different seeds to apply each perturbation with
seeds_per_instance: int = 1
def perturbations(self) -> List[Perturbation]:
return [create_perturbation(spec) for spec in self.perturbation_specs]
The provided code snippet includes necessary dependencies for implementing the `create_data_augmenter` function. Write a Python function `def create_data_augmenter(data_augmenter_spec: DataAugmenterSpec) -> DataAugmenter` to solve the following problem:
Creates a DataAugmenter from a DataAugmenterSpec.
Here is the function:
def create_data_augmenter(data_augmenter_spec: DataAugmenterSpec) -> DataAugmenter:
"""Creates a DataAugmenter from a DataAugmenterSpec."""
return DataAugmenter(perturbations=data_augmenter_spec.perturbations) | Creates a DataAugmenter from a DataAugmenterSpec. |
16,234 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
def extra_space(num_spaces: int) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.extra_space_perturbation.ExtraSpacePerturbation",
args={"num_spaces": num_spaces},
) | null |
16,235 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def space(max_spaces: int) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.space_perturbation.SpacePerturbation",
args={"max_spaces": max_spaces},
) | null |
16,236 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def lower() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.lowercase_perturbation.LowerCasePerturbation", args={}
) | null |
16,237 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def misspelling(prob: float) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.misspelling_perturbation.MisspellingPerturbation",
args={"prob": prob},
) | null |
16,238 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def synonym(prob: float) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.synonym_perturbation.SynonymPerturbation",
args={"prob": prob},
) | null |
16,239 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def contrast_sets() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.contrast_sets_perturbation.ContrastSetsPerturbation",
args={},
) | null |
16,240 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def typo(prob: float) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.typos_perturbation.TyposPerturbation",
args={"prob": prob},
) | null |
16,241 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def filler(prob: float) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.filler_words_perturbation.FillerWordsPerturbation",
args={"insert_prob": prob, "speaker_ph": False},
) | null |
16,242 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def mild_mix() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.mild_mix_perturbation.MildMixPerturbation", args={}
) | null |
16,243 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def contract_and_expand() -> List[PerturbationSpec]:
return [
PerturbationSpec(
class_name=f"helm.benchmark.augmentations.contraction_expansion_perturbation.{mode}Perturbation",
args={},
)
for mode in ["Contraction", "Expansion"]
] | null |
16,244 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def dialect(
prob: float, source_class: str, target_class: str, mapping_file_path: Optional[str] = None
) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.dialect_perturbation.DialectPerturbation",
args={
"prob": prob,
"source_class": source_class,
"target_class": target_class,
"mapping_file_path": mapping_file_path,
},
) | null |
16,245 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def person_name(
prob: float,
source_class: Dict[str, str],
target_class: Dict[str, str],
name_file_path: Optional[str] = None,
person_name_type: str = "first_name",
preserve_gender: bool = True,
) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.person_name_perturbation.PersonNamePerturbation",
args={
"prob": prob,
"source_class": source_class,
"target_class": target_class,
"name_file_path": name_file_path,
"person_name_type": person_name_type,
"preserve_gender": preserve_gender,
},
) | null |
16,246 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def gender(
mode: str,
prob: float,
source_class: str,
target_class: str,
mapping_file_path: Optional[str] = None,
mapping_file_genders: Optional[Tuple[str]] = None,
bidirectional: bool = False,
) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.gender_perturbation.GenderPerturbation",
args={
"mode": mode,
"prob": prob,
"source_class": source_class,
"target_class": target_class,
"mapping_file_path": mapping_file_path,
"mapping_file_genders": mapping_file_genders,
"bidirectional": bidirectional,
},
) | null |
16,247 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def cleva_mild_mix() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.cleva_perturbation.CLEVAMildMixPerturbation",
args={},
) | null |
16,248 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def cleva_gender(
mode: str,
prob: float,
source_class: str,
target_class: str,
) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.cleva_perturbation.ChineseGenderPerturbation",
args={
"mode": mode,
"prob": prob,
"source_class": source_class,
"target_class": target_class,
},
) | null |
16,249 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def cleva_person_name(
prob: float,
source_class: Dict[str, str],
target_class: Dict[str, str],
preserve_gender: bool = True,
) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.cleva_perturbation.ChinesePersonNamePerturbation",
args={
"prob": prob,
"source_class": source_class,
"target_class": target_class,
"preserve_gender": preserve_gender,
},
) | null |
16,250 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def simplified_to_traditional() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.cleva_perturbation.SimplifiedToTraditionalPerturbation",
args={},
) | null |
16,251 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
def mandarin_to_cantonese() -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.cleva_perturbation.MandarinToCantonesePerturbation",
args={},
) | null |
16,252 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
"""Defines how to instantiate Perturbation."""
pass
def translate(language_code: str) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.translate_perturbation.TranslatePerturbation",
args={"language_code": language_code},
) | null |
16,253 | from abc import ABC, abstractmethod
from dataclasses import replace
from typing import Any, List, Dict, Optional, Tuple, Type
from helm.benchmark.model_metadata_registry import (
get_all_instruction_following_models,
get_all_code_models,
get_all_models,
get_all_text_models,
get_model_names_with_tag,
FULL_FUNCTIONALITY_TEXT_MODEL_TAG,
LIMITED_FUNCTIONALITY_TEXT_MODEL_TAG,
ABLATION_MODEL_TAG,
TEXT_TO_IMAGE_MODEL_TAG,
VISION_LANGUAGE_MODEL_TAG,
)
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.common.general import handle_module_not_found_error
from helm.benchmark.model_deployment_registry import get_model_names_with_tokenizer
from .run_spec import RunSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec, Substitution
from .augmentations.perturbation import PerturbationSpec
from .augmentations.data_augmenter import DataAugmenterSpec
from helm.benchmark.scenarios.scenario import TEST_SPLIT, VALID_SPLIT
class PerturbationSpec(ObjectSpec):
def suffix(text: str) -> PerturbationSpec:
return PerturbationSpec(
class_name="helm.benchmark.augmentations.suffix_perturbation.SuffixPerturbation",
args={"suffix": text},
) | null |
16,254 | import argparse
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
import json
import os
from typing import List, Dict, Optional, Any, Callable, Union, Mapping, Tuple, Set
import numpy as np
from scipy.stats import pearsonr
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package
from helm.common.hierarchical_logger import hlog
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.benchmark.model_metadata_registry import MODEL_NAME_TO_MODEL_METADATA
from helm.benchmark.presentation.summarize import AGGREGATE_WIN_RATE_COLUMN
class Column:
"""Values and metadata for each column of the table."""
name: str
group: str
metric: str
values: np.ndarray
lower_is_better: Optional[bool]
class Table:
"""Column-based representation of a standard run-group table. See summarize.py for exact documentation."""
adapters: List[str]
columns: List[Column]
mean_win_rates: Optional[np.ndarray] = None
AGGREGATE_WIN_RATE_COLUMN = 1
The provided code snippet includes necessary dependencies for implementing the `parse_table` function. Write a Python function `def parse_table(raw_table: Dict[str, Any]) -> Table` to solve the following problem:
Convert raw table dict to a Table. Ignores strongly contaminated table entries.
Here is the function:
def parse_table(raw_table: Dict[str, Any]) -> Table:
"""Convert raw table dict to a Table. Ignores strongly contaminated table entries."""
def get_cell_values(cells: List[dict]) -> List[Any]:
values = []
for cell in cells:
value = cell["value"] if "value" in cell else np.nan
if "contamination_level" in cell and cell["contamination_level"] == "strong":
value = np.nan
values.append(value)
return values
adapters: Optional[List[str]] = None
columns: List[Column] = []
mean_win_rates: Optional[np.ndarray] = None
for column_index, (header_cell, *column_cells) in enumerate(zip(raw_table["header"], *raw_table["rows"])):
cell_values = get_cell_values(column_cells)
if column_index == 0:
adapters = cell_values
elif column_index == AGGREGATE_WIN_RATE_COLUMN and "win rate" in header_cell["value"]:
mean_win_rates = np.array(cell_values)
else:
assert "metadata" in header_cell
name = header_cell["value"]
group = header_cell["metadata"]["run_group"]
metric = header_cell["metadata"]["metric"]
lower_is_better = header_cell["lower_is_better"] if "lower_is_better" in header_cell else None
columns.append(Column(name, group, metric, np.array(cell_values), lower_is_better))
assert adapters is not None
return Table(adapters, columns, mean_win_rates) | Convert raw table dict to a Table. Ignores strongly contaminated table entries. |
16,255 | import argparse
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
import json
import os
from typing import List, Dict, Optional, Any, Callable, Union, Mapping, Tuple, Set
import numpy as np
from scipy.stats import pearsonr
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package
from helm.common.hierarchical_logger import hlog
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.benchmark.model_metadata_registry import MODEL_NAME_TO_MODEL_METADATA
from helm.benchmark.presentation.summarize import AGGREGATE_WIN_RATE_COLUMN
try:
import colorcet
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
except ModuleNotFoundError as e:
handle_module_not_found_error(e, ["plots"])
sns.set_style("whitegrid")
def get_color_palette(n_colors: int) -> sns.palettes._ColorPalette:
if n_colors < 6:
return sns.color_palette("colorblind", n_colors=n_colors)
else:
return sns.color_palette(colorcet.glasbey_warm, n_colors=n_colors) | null |
16,256 | import argparse
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
import json
import os
from typing import List, Dict, Optional, Any, Callable, Union, Mapping, Tuple, Set
import numpy as np
from scipy.stats import pearsonr
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package
from helm.common.hierarchical_logger import hlog
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.benchmark.model_metadata_registry import MODEL_NAME_TO_MODEL_METADATA
from helm.benchmark.presentation.summarize import AGGREGATE_WIN_RATE_COLUMN
The provided code snippet includes necessary dependencies for implementing the `draw_box_plot` function. Write a Python function `def draw_box_plot( x_to_ys: Mapping[str, Union[List[float], np.ndarray]], ax: matplotlib.axis.Axis, rotate_xticklabels: bool = True )` to solve the following problem:
Given a mapping from string to floats, draw a box plot on the given axis ax. For instance, this might be a mapping from scenario_name to a list of model accuracies in which case the box plot captures aggregate model performance and highlights outliers.
Here is the function:
def draw_box_plot(
x_to_ys: Mapping[str, Union[List[float], np.ndarray]], ax: matplotlib.axis.Axis, rotate_xticklabels: bool = True
):
"""Given a mapping from string to floats, draw a box plot on the given axis ax. For instance, this might be a
mapping from scenario_name to a list of model accuracies in which case the box plot captures aggregate model
performance and highlights outliers."""
xs: List[str] = []
all_ys: List[List[float]] = []
for x, ys in x_to_ys.items():
ys = [y for y in ys if not np.isnan(y)]
if ys:
xs.append(x)
all_ys.append(ys)
ax.scatter([len(xs)] * len(ys), ys, c="#bbb")
ax.boxplot(all_ys, boxprops={"linewidth": 2}, medianprops={"linewidth": 2})
if rotate_xticklabels:
ax.set_xticklabels(xs, rotation=-30, ha="left")
else:
ax.set_xticklabels(xs) | Given a mapping from string to floats, draw a box plot on the given axis ax. For instance, this might be a mapping from scenario_name to a list of model accuracies in which case the box plot captures aggregate model performance and highlights outliers. |
16,257 | from dataclasses import dataclass
from typing import List, Optional
import dacite
import importlib_resources as resources
import yaml
from helm.common.hierarchical_logger import htrack, hlog
from helm.benchmark.model_metadata_registry import MODEL_NAME_TO_MODEL_METADATA
from helm.benchmark.presentation.schema import Schema
class Contamination:
"""
Captures train-test contamination information between models and groups.
"""
points: List[ContaminationPoint]
def get_point(self, model: str, group: str) -> Optional[ContaminationPoint]:
"""Return the point that matches `group` and `model`."""
found_points = [point for point in self.points if group in point.groups and model in point.models]
# Note: if more than one found, ideally we should take the strongest
# one, but leaving for now.
assert len(found_points) <= 1
return found_points[0] if len(found_points) == 1 else None
def hlog(x: Any) -> None:
singleton.log(x)
MODEL_NAME_TO_MODEL_METADATA: Dict[str, ModelMetadata] = {model.name: model for model in ALL_MODELS_METADATA}
class Schema:
"""Specifies information about what to display on the frontend."""
# Adapter fields (e.g., temperature)
adapter: List[Field]
# Information about each field
metrics: List[Field]
# Information about each perturbation
perturbations: List[Field]
# Group the metrics
metric_groups: List[MetricGroup]
# Group the scenarios
run_groups: List[RunGroup]
def __post_init__(self):
self.name_to_metric = {metric.name: metric for metric in self.metrics}
self.name_to_perturbation = {perturbation.name: perturbation for perturbation in self.perturbations}
self.name_to_metric_group = {metric_group.name: metric_group for metric_group in self.metric_groups}
self.name_to_run_group = {run_group.name: run_group for run_group in self.run_groups}
The provided code snippet includes necessary dependencies for implementing the `validate_contamination` function. Write a Python function `def validate_contamination(contamination: Contamination, schema: Schema)` to solve the following problem:
Make sure models and groups in contamination are defined according to `schema`.
Here is the function:
def validate_contamination(contamination: Contamination, schema: Schema):
"""Make sure models and groups in contamination are defined according to `schema`."""
for point in contamination.points:
for model in point.models:
if model not in MODEL_NAME_TO_MODEL_METADATA:
hlog(f"WARNING: model {model} not defined in schema")
for group in point.groups:
if group not in schema.name_to_run_group:
hlog(f"WARNING: group {group} not defined in schema") | Make sure models and groups in contamination are defined according to `schema`. |
16,258 | from dataclasses import dataclass
from typing import List, Optional
import dacite
import importlib_resources as resources
import yaml
from helm.common.hierarchical_logger import htrack, hlog
from helm.benchmark.model_metadata_registry import MODEL_NAME_TO_MODEL_METADATA
from helm.benchmark.presentation.schema import Schema
CONTAMINATION_YAML_PACKAGE: str = "helm.benchmark.static"
CONTAMINATION_YAML_FILENAME: str = "contamination.yaml"
class Contamination:
"""
Captures train-test contamination information between models and groups.
"""
points: List[ContaminationPoint]
def get_point(self, model: str, group: str) -> Optional[ContaminationPoint]:
"""Return the point that matches `group` and `model`."""
found_points = [point for point in self.points if group in point.groups and model in point.models]
# Note: if more than one found, ideally we should take the strongest
# one, but leaving for now.
assert len(found_points) <= 1
return found_points[0] if len(found_points) == 1 else None
def hlog(x: Any) -> None:
singleton.log(x)
def read_contamination():
hlog(f"Reading contamination information from {CONTAMINATION_YAML_FILENAME}...")
contamination_path = resources.files(CONTAMINATION_YAML_PACKAGE).joinpath(CONTAMINATION_YAML_FILENAME)
with contamination_path.open("r") as f:
raw = yaml.safe_load(f)
return dacite.from_dict(Contamination, raw) | null |
16,259 | from dataclasses import dataclass, field
from typing import Any, Optional, List, Dict
class Table:
title: str
header: List[HeaderCell]
rows: List[List[Cell]]
# Extra information to show at the bottom
links: List[Hyperlink] = field(default_factory=list)
# Optional name
name: Optional[str] = None
# Optional description to show at the top
description: Optional[str] = None
The provided code snippet includes necessary dependencies for implementing the `table_to_latex` function. Write a Python function `def table_to_latex(table: Table, table_name: str, skip_blank_columns=True) -> str` to solve the following problem:
Return a string representing the latex version of the table.
Here is the function:
def table_to_latex(table: Table, table_name: str, skip_blank_columns=True) -> str:
"""Return a string representing the latex version of the table."""
columns_shown = list(range(len(table.header)))
if skip_blank_columns:
columns_shown = [i for i in columns_shown if not all(row[i].value is None for row in table.rows)]
lines = []
lines.append("\\begin{table*}[htp]")
lines.append("\\resizebox{\\textwidth}{!}{")
lines.append("\\begin{tabular}{l" + "r" * (len(columns_shown) - 1) + "}")
lines.append("\\toprule")
lines.append(" & ".join(str(table.header[i].value) for i in columns_shown) + " \\\\")
lines.append("\\midrule")
for row in table.rows:
lines.append(" & ".join(str(row[i].display_value or row[i].value or "") for i in columns_shown) + " \\\\")
lines.append("\\bottomrule")
lines.append("\\end{tabular}}")
lines.append("\\caption{Results for " + table_name + "}")
lines.append("\\label{fig:" + table_name + "}")
lines.append("\\end{table*}")
latex = "\n".join(lines).replace("%", "\\%")
return latex | Return a string representing the latex version of the table. |
16,260 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
def singleton(items: List):
"""Ensure there's only one item in `items` and return it."""
if len(items) != 1:
raise ValueError(f"Expected 1 item, got {len(items)} items: {items}")
return items[0]
def hlog(x: Any) -> None:
singleton.log(x)
class MetricName:
# The name of the metric
name: str
# Split (e.g., train, valid, test)
split: Optional[str] = None
# Sub split (e.g., toxic, non-toxic)
sub_split: Optional[str] = None
# Description of the Perturbation applied to the Instances
perturbation: Optional[PerturbationDescription] = None
class Stat:
"""A mutable class that allows us to aggregate values and report mean/stddev."""
name: MetricName
count: int = 0
sum: float = 0
sum_squared: float = 0
min: Optional[float] = None
max: Optional[float] = None
mean: Optional[float] = None
variance: Optional[float] = None
"""This is the population variance, not the sample variance.
See https://towardsdatascience.com/variance-sample-vs-population-3ddbd29e498a
for details.
"""
stddev: Optional[float] = None
"""This is the population standard deviation, not the sample standard deviation.
See https://towardsdatascience.com/variance-sample-vs-population-3ddbd29e498a
for details.
"""
def add(self, x) -> "Stat":
# Skip Nones for statistic aggregation.
if x is None:
return self
if isinstance(x, bool):
x = 1 if x is True else 0
self.sum += x
self.sum_squared += x * x
self.min = min(self.min, x) if self.min is not None else x
self.max = max(self.max, x) if self.max is not None else x
self.count += 1
self._update_mean_variance_stddev()
return self
def merge(self, other: "Stat") -> "Stat":
# Note: don't look at other.name
self.sum += other.sum
self.sum_squared += other.sum_squared
if other.min is not None:
self.min = min(self.min, other.min) if self.min is not None else other.min
if other.max is not None:
self.max = max(self.max, other.max) if self.max is not None else other.max
self.count += other.count
self._update_mean_variance_stddev()
return self
def __repr__(self):
return f"{self.name}[{self.bare_str()}]"
def bare_str(self) -> str:
def process(x: Optional[float]) -> str:
if x is None:
return "None"
if math.isnan(x):
return "NaN"
if int(x) == x:
return str(int(x))
return str(round(x, 3))
if self.count > 0:
return (
f"min={process(self.min)}, "
f"mean={process(self.mean)}, "
f"max={process(self.max)}, "
f"sum={process(self.sum)} "
f"({self.count})"
)
else:
return "(0)"
def _update_mean_variance_stddev(self):
if self.count == 0:
# No stats with no elements.
return
# Update mean
self.mean = self.sum / self.count
# Update variance
pvariance = self.sum_squared / self.count - self.mean**2
self.variance = 0 if pvariance < 0 else pvariance
# Update stddev
self.stddev = math.sqrt(self.variance)
def take_mean(self):
"""Return a version of the stat that only has the mean."""
if self.count == 0:
return self
return Stat(self.name).add(self.mean)
def merge_stat(stats: Dict[MetricName, Stat], stat: Stat):
"""Mutate the appropriate part of `stats`."""
if stat.name not in stats:
# Important: copy so that we don't mutate accidentally
stats[stat.name] = replace(stat)
else:
stats[stat.name].merge(stat)
class MetricNameMatcher:
"""
The schema file specifies information about what metrics we want to specify,
but it doesn't specify full `MetricName`s. Instead, it specifies enough
information in a `MetricNameMatcher` to pull out the relevant
`MetricName`s.
"""
# Name of the metric
name: str
# Which data split to report numbers on (e.g., TEST_SPLIT)
split: str
# Which sub split to report numbers on (e.g., toxic, non-toxic)
# If None, will match all sub splits
sub_split: Optional[str] = None
# Which perturbation to show (e.g., robustness)
perturbation_name: Optional[str] = None
def matches(self, metric_name: MetricName) -> bool:
if self.name != metric_name.name:
return False
if self.split != metric_name.split:
return False
# Optional
if self.sub_split is not None and self.sub_split != metric_name.sub_split:
return False
metric_perturbation_name = metric_name.perturbation and metric_name.perturbation.name
if self.perturbation_name != metric_perturbation_name:
return False
# If there is a perturbation, only return the worst
if metric_name.perturbation and metric_name.perturbation.computed_on != PERTURBATION_WORST:
return False
return True
def substitute(self, environment: Dict[str, str]) -> "MetricNameMatcher":
return MetricNameMatcher(
name=mako.template.Template(self.name).render(**environment),
split=mako.template.Template(self.split).render(**environment),
perturbation_name=mako.template.Template(self.perturbation_name).render(**environment)
if self.perturbation_name is not None
else None,
)
The provided code snippet includes necessary dependencies for implementing the `get_unique_stat_by_matcher` function. Write a Python function `def get_unique_stat_by_matcher(stats: List[Stat], matcher: MetricNameMatcher) -> Optional[Stat]` to solve the following problem:
Return the single stat that matches.
Here is the function:
def get_unique_stat_by_matcher(stats: List[Stat], matcher: MetricNameMatcher) -> Optional[Stat]:
"""Return the single stat that matches."""
matching_stats = [stat for stat in stats if matcher.matches(stat.name)]
if len(matching_stats) == 0:
# HACK: if we are looking for `quasi_exact_match` and it's not there, try `exact_match` instead
# This is necessary for prompting ablations at the moment, since some scenarios normally have quasi_exact_match
# as the main metric but multiple_choice_separate_original only generates exact_match
if matcher.name == "quasi_exact_match":
hlog("WARNING: No quasi_exact_match metric found, looking for exact_match instead")
matcher = replace(matcher, name="exact_match")
matching_stats = [stat for stat in stats if matcher.matches(stat.name)]
if len(matching_stats) == 0:
return None
else:
return None
# Matcher matches all sub splits so we should aggregate these
if matcher.sub_split is None:
stats_dict: Dict[MetricName, Stat] = {}
for stat in matching_stats:
stat = Stat(replace(stat.name, sub_split=None)).merge(stat)
merge_stat(stats_dict, stat)
matching_stats = list(stats_dict.values())
return singleton(matching_stats) | Return the single stat that matches. |
16,261 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
def get_benchmarking_url(params: Dict[str, str]) -> str:
# Don't encode ' ' as '+'
return "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote) | null |
16,262 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
def dict_to_str(d: Dict[str, Any]) -> str:
class ScenarioSpec(ObjectSpec):
class RunGroup(Field):
def get_scenario_name(group: RunGroup, scenario_spec: ScenarioSpec):
return group.name + "_" + dict_to_str(scenario_spec.args).replace(" ", "").replace("/", "_") | null |
16,263 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
def get_model_deployment(name: str, warn_deprecated: bool = False) -> ModelDeployment:
if name not in DEPLOYMENT_NAME_TO_MODEL_DEPLOYMENT:
raise ValueError(f"Model deployment {name} not found")
deployment: ModelDeployment = DEPLOYMENT_NAME_TO_MODEL_DEPLOYMENT[name]
if deployment.deprecated and warn_deprecated:
hlog(f"WARNING: DEPLOYMENT Model deployment {name} is deprecated")
return deployment
class ModelMetadata:
name: str
"""Name of the model group (e.g., "openai/davinci"). This is the name of the model,
not the name of the deployment.
Usually formatted as "<creator_organization>/<engine_name>". Example: "ai21/j1-jumbo"."""
creator_organization_name: str
"""Name of the organization that created the model."""
display_name: str
"""Name that is going to be displayed to the user (on the website, etc.)."""
description: str
"""Description of the model, to be displayed on the website."""
access: str
"""Description of the access level of the model. Should be one of the following:
- "open": the model is open-source and can be downloaded from the internet.
- "closed": not accessible
- "limited": accessible with an API key.
If there are multiple deployments, this should be the most permissive access across all deployments."""
release_date: Optional[date]
"""Release date of the model."""
tags: List[str] = field(default_factory=list)
"""Tags corresponding to the properties of the model."""
num_parameters: Optional[int] = None
"""Number of parameters in the model.
This should be a string as the number of parameters is usually a round number (175B),
but we set it as an int for plotting purposes."""
deployment_names: Optional[List[str]] = None
"""List of the model deployments for this model. Should at least contain one model deployment.
Refers to the field "name" in the ModelDeployment class. Defaults to a single model deployment
with the same name as the model."""
def creator_organization(self) -> str:
"""
Extracts the creator organization from the model name.
Example: 'ai21/j1-jumbo' => 'ai21'
This can be different from the hosting organization.
"""
return self.name.split("/")[0]
def engine(self) -> str:
"""
Extracts the model engine from the model name.
Example: 'ai21/j1-jumbo' => 'j1-jumbo'
"""
return self.name.split("/")[1]
def get_model_metadata(model_name: str) -> ModelMetadata:
"""Return the `ModelMetadata` for the model name."""
if model_name not in MODEL_NAME_TO_MODEL_METADATA:
raise ValueError(f"No model with name: {model_name}")
return MODEL_NAME_TO_MODEL_METADATA[model_name]
def get_unknown_model_metadata(helm_model_name: str) -> ModelMetadata:
"""Return placeholder ModelMetadata for an unknown model."""
return ModelMetadata(
name=helm_model_name,
creator_organization_name="Unknown",
display_name=helm_model_name,
description=helm_model_name,
access="open",
release_date=date.today(),
tags=[TEXT_MODEL_TAG, FULL_FUNCTIONALITY_TEXT_MODEL_TAG],
)
class AdapterSpec:
"""
Specifies how to take a `Scenario` (a list of `Instance`s) and produce a
`ScenarioState` (set of `Request`s ). Instead of having free-form prompt
hacking, we try to make the process more declarative and systematic.
Note that an `Instance` could produce many `Request`s (e.g., one for each `Reference`).
"""
# Method of adaptation
method: str = ""
# Prepend all prompts with this string.
# For example, it is recommended to prefix all prompts with [NLG] for UL2.
global_prefix: str = ""
# Append all prompts with this string.
global_suffix: str = ""
# Prompt starts with instructions
instructions: str = ""
# What goes before the input
input_prefix: str = "Input: "
# What goes after the input
input_suffix: str = "\n"
# What goes before the input (for multiple choice)
reference_prefix: str = "A. "
# What goes before the input (for multiple choice)
reference_suffix: str = "\n"
# What goes before the output
output_prefix: str = "Output: "
# What goes after the output
output_suffix: str = "\n"
# What goes between instruction and in-context example blocks in the constructed prompt
instance_prefix: str = "\n"
# List of regular expression substitutions that we perform
substitutions: List[Substitution] = field(default_factory=list, hash=False)
# Maximum number of (in-context) training instances to put into the prompt
max_train_instances: int = 5
# Maximum number of evaluation instances. For getting valid numbers, this
# should be the entire dataset; only reduce this for piloting.
max_eval_instances: Optional[int] = None
# Generate this many outputs (which could be realized by `num_completions`
# or `top_k_per_token`).
num_outputs: int = 5
# Number of trials, where in each trial we choose an independent, random
# set of training instances. Used to compute error bars.
num_train_trials: int = 1
# Number of trials, where we query the model with the same requests, but different random seeds
num_trials: int = 1
# If true, randomly sample N training examples; if false, select N consecutive training examples
sample_train: bool = True
# Decoding parameters (inherited by `Request`)
# Model deployment to make the request to (need to fill in)
model_deployment: str = ""
# Model to make the request to
model: str = ""
# Temperature to use
temperature: float = 1
# Maximum number of tokens to generate
max_tokens: int = 100
# When to stop (set hash=False to make `AdapterSpec` hashable)
stop_sequences: List[str] = field(default_factory=list, hash=False)
# Random string (used concretely to bypass cache / see diverse results)
random: Optional[str] = None
# If true, for instances with multiple correct reference, the gold answer should be considered
# to be all the correct references rather than any of the correct references.
multi_label: bool = False
# Parameters for image generation
image_generation_parameters: Optional[ImageGenerationParameters] = None
# The splits from which evaluation instances will be drawn (set hash=False to make `AdapterSpec` hashable)
eval_splits: Optional[List[str]] = field(default=None, hash=False)
The provided code snippet includes necessary dependencies for implementing the `get_model_metadata_for_adapter_spec` function. Write a Python function `def get_model_metadata_for_adapter_spec(adapter_spec: AdapterSpec) -> ModelMetadata` to solve the following problem:
Return the ModelMetadata for the model in the given AdapterSpec.
Here is the function:
def get_model_metadata_for_adapter_spec(adapter_spec: AdapterSpec) -> ModelMetadata:
"""Return the ModelMetadata for the model in the given AdapterSpec."""
# Get model metadata based on `model` in `adapter_spec`
try:
return get_model_metadata(adapter_spec.model)
except ValueError:
pass
# Get model metadata based on `model_deployment` in `adapter_spec`
try:
model_deployment = get_model_deployment(adapter_spec.model_deployment)
if model_deployment.model_name:
return get_model_metadata(model_deployment.model_name)
except ValueError:
pass
# In some cases, some models were renamed such that the old model name is now the model deployment name
# For instance, the model called "huggingface/gpt2" is now called "openai/gpt2", but its model deployment
# is still called "huggingface/gpt2".
# Handle these cases here.
# TODO: Delete this block eventually.
try:
model_deployment = get_model_deployment(adapter_spec.model)
if model_deployment.model_name:
return get_model_metadata(model_deployment.model_name)
except ValueError:
pass
# Return a placeholder "unknown model" model metadata.
return get_unknown_model_metadata(adapter_spec.model) | Return the ModelMetadata for the model in the given AdapterSpec. |
16,264 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
class ScenarioSpec(ObjectSpec):
pass
class AdapterSpec:
"""
Specifies how to take a `Scenario` (a list of `Instance`s) and produce a
`ScenarioState` (set of `Request`s ). Instead of having free-form prompt
hacking, we try to make the process more declarative and systematic.
Note that an `Instance` could produce many `Request`s (e.g., one for each `Reference`).
"""
# Method of adaptation
method: str = ""
# Prepend all prompts with this string.
# For example, it is recommended to prefix all prompts with [NLG] for UL2.
global_prefix: str = ""
# Append all prompts with this string.
global_suffix: str = ""
# Prompt starts with instructions
instructions: str = ""
# What goes before the input
input_prefix: str = "Input: "
# What goes after the input
input_suffix: str = "\n"
# What goes before the input (for multiple choice)
reference_prefix: str = "A. "
# What goes before the input (for multiple choice)
reference_suffix: str = "\n"
# What goes before the output
output_prefix: str = "Output: "
# What goes after the output
output_suffix: str = "\n"
# What goes between instruction and in-context example blocks in the constructed prompt
instance_prefix: str = "\n"
# List of regular expression substitutions that we perform
substitutions: List[Substitution] = field(default_factory=list, hash=False)
# Maximum number of (in-context) training instances to put into the prompt
max_train_instances: int = 5
# Maximum number of evaluation instances. For getting valid numbers, this
# should be the entire dataset; only reduce this for piloting.
max_eval_instances: Optional[int] = None
# Generate this many outputs (which could be realized by `num_completions`
# or `top_k_per_token`).
num_outputs: int = 5
# Number of trials, where in each trial we choose an independent, random
# set of training instances. Used to compute error bars.
num_train_trials: int = 1
# Number of trials, where we query the model with the same requests, but different random seeds
num_trials: int = 1
# If true, randomly sample N training examples; if false, select N consecutive training examples
sample_train: bool = True
# Decoding parameters (inherited by `Request`)
# Model deployment to make the request to (need to fill in)
model_deployment: str = ""
# Model to make the request to
model: str = ""
# Temperature to use
temperature: float = 1
# Maximum number of tokens to generate
max_tokens: int = 100
# When to stop (set hash=False to make `AdapterSpec` hashable)
stop_sequences: List[str] = field(default_factory=list, hash=False)
# Random string (used concretely to bypass cache / see diverse results)
random: Optional[str] = None
# If true, for instances with multiple correct reference, the gold answer should be considered
# to be all the correct references rather than any of the correct references.
multi_label: bool = False
# Parameters for image generation
image_generation_parameters: Optional[ImageGenerationParameters] = None
# The splits from which evaluation instances will be drawn (set hash=False to make `AdapterSpec` hashable)
eval_splits: Optional[List[str]] = field(default=None, hash=False)
The provided code snippet includes necessary dependencies for implementing the `get_coarse_adapter_spec` function. Write a Python function `def get_coarse_adapter_spec( adapter_spec: AdapterSpec, scenario_spec: Optional[ScenarioSpec] = None, adapter_keys_shown: List[str] = [] ) -> AdapterSpec` to solve the following problem:
Return an abstraction of an AdapterSpec that corresponds to the method (e.g., model, decoding parameters), and not the part that contains scenario-specific things like instructions. This is not an easy thing to disentangle, so just try our best in a necessarily scenario-specific way.
Here is the function:
def get_coarse_adapter_spec(
adapter_spec: AdapterSpec, scenario_spec: Optional[ScenarioSpec] = None, adapter_keys_shown: List[str] = []
) -> AdapterSpec:
"""
Return an abstraction of an AdapterSpec that corresponds to the method
(e.g., model, decoding parameters), and not the part that contains
scenario-specific things like instructions.
This is not an easy thing to disentangle, so just try our best
in a necessarily scenario-specific way.
"""
# TODO: clean up this logic a bit
# Sometimes the instructions contain information about the scenario.
if scenario_spec and scenario_spec.class_name.endswith(".MMLUScenario"):
# MMLU: Sync up with logic in `get_mmlu_spec` for constructing the instructions.
subject = scenario_spec.args["subject"].replace("_", " ")
instructions = adapter_spec.instructions.replace(subject, "___")
elif scenario_spec and scenario_spec.class_name.endswith(".RAFTScenario"):
# RAFT scenario has arbitrary instructions, so impossible to remove
# the scenario information, so remove all of it.
instructions = "<scenario specific>"
else:
instructions = adapter_spec.instructions
adapter_spec = replace(adapter_spec, instructions=instructions)
# Create a new adapter_spec, keeping only the model and the keys in adapter_keys_shown
adapter_spec_kwargs = {key: adapter_spec.__dict__[key] for key in adapter_keys_shown}
return AdapterSpec(**adapter_spec_kwargs) | Return an abstraction of an AdapterSpec that corresponds to the method (e.g., model, decoding parameters), and not the part that contains scenario-specific things like instructions. This is not an easy thing to disentangle, so just try our best in a necessarily scenario-specific way. |
16,265 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
def dict_to_str(d: Dict[str, Any]) -> str:
return ", ".join(f"{k}: {v}" for k, v in d.items())
The provided code snippet includes necessary dependencies for implementing the `get_method_display_name` function. Write a Python function `def get_method_display_name(model_display_name: Optional[str], info: Dict[str, Any]) -> str` to solve the following problem:
Return a nice name to display for `adapter_spec` which denotes a method. `info` contains the decoding parameters. Format: Model (info...)
Here is the function:
def get_method_display_name(model_display_name: Optional[str], info: Dict[str, Any]) -> str:
"""
Return a nice name to display for `adapter_spec` which denotes a method.
`info` contains the decoding parameters.
Format: Model (info...)
"""
info = dict(info)
if "model" in info:
del info["model"]
if "model_deployment" in info:
del info["model_deployment"]
return (model_display_name or "???") + (f" [{dict_to_str(info)}]" if len(info) > 0 else "") | Return a nice name to display for `adapter_spec` which denotes a method. `info` contains the decoding parameters. Format: Model (info...) |
16,266 | import argparse
import cattrs
import os
import datetime
import urllib.parse
import json
import yaml
from collections import defaultdict
from dataclasses import dataclass, replace
from statistics import mean, median
from typing import List, Optional, Dict, Any, Tuple, Set
from tqdm import tqdm
from helm.benchmark.model_deployment_registry import get_model_deployment
from helm.benchmark.model_metadata_registry import get_unknown_model_metadata
from helm.common.general import (
write,
ensure_directory_exists,
asdict_without_nones,
parallel_map,
singleton,
unique_simplification,
)
from helm.common.codec import from_json
from helm.common.hierarchical_logger import hlog, htrack, htrack_block
from helm.benchmark.scenarios.scenario import ScenarioSpec
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.data_overlap.data_overlap_spec import DataOverlapStats, GroupOverlapStats
from helm.benchmark.data_overlap.light_scenario import ScenarioSpecInstanceIds
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.metrics.metric import get_all_stats_by_name
from helm.benchmark.metrics.statistic import Stat, merge_stat
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.runner import LATEST_SYMLINK
from helm.benchmark.presentation.table import Cell, HeaderCell, Table, Hyperlink, table_to_latex
from helm.benchmark.presentation.schema import (
MetricNameMatcher,
RunGroup,
Field,
read_schema,
SCHEMA_CLASSIC_YAML_FILENAME,
BY_GROUP,
THIS_GROUP_ONLY,
NO_GROUPS,
)
from helm.benchmark.config_registry import register_builtin_configs_from_helm_package, register_configs_from_directory
from helm.benchmark.presentation.run_display import write_run_display_json
from helm.benchmark.model_metadata_registry import ModelMetadata, get_model_metadata, get_all_models
class Table:
title: str
header: List[HeaderCell]
rows: List[List[Cell]]
# Extra information to show at the bottom
links: List[Hyperlink] = field(default_factory=list)
# Optional name
name: Optional[str] = None
# Optional description to show at the top
description: Optional[str] = None
The provided code snippet includes necessary dependencies for implementing the `compute_aggregate_row_win_rates` function. Write a Python function `def compute_aggregate_row_win_rates(table: Table, aggregation: str = "mean") -> List[Optional[float]]` to solve the following problem:
Computes the aggregate win rate of each row across columns. For a given row r1 and column c1, the win rate of r1 wrt to c1 corresponds to: if we pick another row r2 uniformly at random, what is the probability that r1c1 is better that r2c1? `aggregation` determines how we aggregate win rates across columns, currently can be "mean" or "median". We skip columns where "better" is ambiguous or less than 2 values are non-null. Returns a list of aggregate win rates, one per row, with None if a row was never meaningfully comparable (i.e., all non-null values of the row are in columns we skip).
Here is the function:
def compute_aggregate_row_win_rates(table: Table, aggregation: str = "mean") -> List[Optional[float]]:
"""
Computes the aggregate win rate of each row across columns. For a given row r1 and column c1, the win rate of r1 wrt
to c1 corresponds to: if we pick another row r2 uniformly at random, what is the probability that r1c1 is better
that r2c1?
`aggregation` determines how we aggregate win rates across columns, currently can be "mean" or "median".
We skip columns where "better" is ambiguous or less than 2 values are non-null.
Returns a list of aggregate win rates, one per row, with None if a row was never meaningfully comparable (i.e., all
non-null values of the row are in columns we skip).
"""
assert aggregation in ["mean", "median"]
win_rates_per_row: List[List[float]] = [[] for _ in table.rows]
for i, header_cell in enumerate(table.header):
lower_is_better = header_cell.lower_is_better
if lower_is_better is None: # column does not have a meaningful ordering
continue
values = [(row[i].value, j) for j, row in enumerate(table.rows) if row[i].value is not None]
if len(values) < 2: # don't rank a single model
continue
for wins, (v, j) in enumerate(sorted(values, reverse=lower_is_better)):
win_rate = wins / (len(values) - 1) # normalize to [0, 1]
win_rates_per_row[j].append(win_rate)
# Note: the logic up to here is somewhat general as it simply computes win rates across columns for each row.
# Here, we simply average these win rates but we might want some more involved later (e.g., weighted average).
aggregate_win_rates: List[Optional[float]] = []
for win_rates in win_rates_per_row:
if len(win_rates) == 0:
aggregate_win_rates.append(None)
else:
aggregate = mean(win_rates) if aggregation == "mean" else median(win_rates)
aggregate_win_rates.append(aggregate)
return aggregate_win_rates | Computes the aggregate win rate of each row across columns. For a given row r1 and column c1, the win rate of r1 wrt to c1 corresponds to: if we pick another row r2 uniformly at random, what is the probability that r1c1 is better that r2c1? `aggregation` determines how we aggregate win rates across columns, currently can be "mean" or "median". We skip columns where "better" is ambiguous or less than 2 values are non-null. Returns a list of aggregate win rates, one per row, with None if a row was never meaningfully comparable (i.e., all non-null values of the row are in columns we skip). |
16,267 | from dataclasses import dataclass, field
from typing import List, Optional, Dict
import dacite
import mako.template
import yaml
import importlib_resources as resources
from helm.common.general import hlog
from helm.benchmark.metrics.metric_name import MetricName
from helm.benchmark.augmentations.perturbation_description import PERTURBATION_WORST
SCHEMA_YAML_PACKAGE: str = "helm.benchmark.static"
class Schema:
def __post_init__(self):
def read_schema(filename: str) -> Schema:
# TODO: merge in model metadata from `model_metadata.yaml`
schema_path = resources.files(SCHEMA_YAML_PACKAGE).joinpath(filename)
hlog(f"Reading schema file {schema_path}...")
with schema_path.open("r") as f:
raw = yaml.safe_load(f)
return dacite.from_dict(Schema, raw) | null |
16,268 | from collections import OrderedDict, defaultdict
from dataclasses import dataclass, replace
import os
from typing import Dict, Iterable, List, Optional, Set, Tuple
from helm.benchmark.adaptation.adapter_spec import (
ADAPT_MULTIPLE_CHOICE_SEPARATE_METHODS,
ADAPT_MULTIPLE_CHOICE_SEPARATE_CALIBRATED,
)
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.adaptation.request_state import RequestState
from helm.benchmark.adaptation.scenario_state import ScenarioState
from helm.benchmark.augmentations.perturbation_description import PerturbationDescription
from helm.benchmark.metrics.metric import PerInstanceStats
from helm.common.multimodal_request_utils import gather_generated_image_locations
from helm.benchmark.presentation.schema import Schema
from helm.benchmark.run_spec import RunSpec
from helm.benchmark.scenarios.scenario import Instance, Input
from helm.common.general import write
from helm.common.hierarchical_logger import hlog, htrack
from helm.common.images_utils import encode_base64
from helm.common.request import Request
from helm.common.codec import from_json, to_json
class DisplayPrediction:
"""
Captures a unit of evaluation for displaying in the web frontend.
"""
# (instance_id, perturbation, train_trial_index) is a unique key for this prediction.
instance_id: str
"""ID of the Instance"""
perturbation: Optional[PerturbationDescription]
"""Description of the Perturbation that was applied"""
train_trial_index: int
"""Which replication"""
predicted_text: str
"""Prediction text"""
truncated_predicted_text: Optional[str]
"""The truncated prediction text, if truncation is required by the Adapter method."""
base64_images: Optional[List[str]]
"""Images in base64."""
mapped_output: Optional[str]
"""The mapped output, if an output mapping exists and the prediction can be mapped"""
reference_index: Optional[int]
"""Which reference of the instance we're evaluating (if any)"""
stats: Dict[str, float]
"""Statistics computed from the predicted output"""
class DisplayRequest:
"""
Captures a unit of evaluation for displaying in the web frontend.
"""
# (instance_id, perturbation, train_trial_index) is a unique key for this prediction.
instance_id: str
"""ID of the Instance"""
perturbation: Optional[PerturbationDescription]
"""Description of the Perturbation that was applied"""
train_trial_index: int
"""Which replication"""
request: Request
"""The actual Request to display in the web frontend.
There can be multiple requests per trial. The displayed request should be the
most relevant request e.g. the request for the chosen choice for multiple choice questions."""
def _read_scenario_state(scenario_state_path: str) -> ScenarioState:
if not os.path.exists(scenario_state_path):
raise ValueError(f"Could not load ScenarioState from {scenario_state_path}")
with open(scenario_state_path) as f:
return from_json(f.read(), ScenarioState)
def _read_per_instance_stats(per_instance_stats_path: str) -> List[PerInstanceStats]:
if not os.path.exists(per_instance_stats_path):
raise ValueError(f"Could not load PerInstanceStats from {per_instance_stats_path}")
with open(per_instance_stats_path) as f:
return from_json(f.read(), List[PerInstanceStats])
def _truncate_predicted_text(
predicted_text: str, request_state: RequestState, adapter_spec: AdapterSpec
) -> Optional[str]:
method = adapter_spec.method
prefix = ""
if method in ADAPT_MULTIPLE_CHOICE_SEPARATE_METHODS:
prefix = request_state.instance.input.text
elif method == "language_modeling":
if request_state.result is not None and request_state.result.completions:
tokens = request_state.result.completions[0].tokens
if tokens:
first_token = tokens[0]
prefix = first_token.text
if prefix:
predicted_text = predicted_text
prefix = prefix
if predicted_text.startswith(prefix):
return predicted_text[len(prefix) :]
return None
def _get_metric_names_for_groups(run_group_names: Iterable[str], schema: Schema) -> Set[str]:
result: Set[str] = set()
for run_group_name in run_group_names:
result.update(_get_metric_names_for_group(run_group_name, schema))
return result
_INSTANCES_JSON_FILE_NAME = "instances.json"
_DISPLAY_PREDICTIONS_JSON_FILE_NAME = "display_predictions.json"
_DISPLAY_REQUESTS_JSON_FILE_NAME = "display_requests.json"
ADAPT_MULTIPLE_CHOICE_SEPARATE_CALIBRATED: str = "multiple_choice_separate_calibrated"
ADAPT_MULTIPLE_CHOICE_SEPARATE_METHODS: List[str] = [
ADAPT_MULTIPLE_CHOICE_SEPARATE_ORIGINAL,
ADAPT_MULTIPLE_CHOICE_SEPARATE_CALIBRATED,
]
class PerturbationDescription:
"""DataClass used to describe a Perturbation"""
name: str
"""Name of the Perturbation"""
robustness: bool = False
"""Whether a perturbation is relevant to robustness. Will be used to aggregate perturbations metrics"""
fairness: bool = False
"""Whether a perturbation is relevant to fairness. Will be used to aggregate perturbations metrics"""
computed_on: str = PERTURBATION_PERTURBED
"""Which types of Instances we are evaluating, to be populated during metric evaluation. PERTURBATION_PERTURBED
(default) means we are evaluating on perturbed instances, PERTURBATION_ORIGINAL means we are evaluating the
unperturbed version of instances where this perturbation applies, and, PERTURBATION_WORST means the the minimum
metric between the two."""
seed: Optional[int] = None
"""Seed added to instance_id when generating perturbation"""
def gather_generated_image_locations(request_result: RequestResult) -> List[str]:
"""Gathers the locations (file paths or URLs) of the generated images."""
image_locations: List[str] = []
for image in request_result.completions:
# Models like DALL-E 2 can skip generating images for prompts that violate their content policy
if image.multimodal_content is None or image.multimodal_content.size == 0:
return []
location: Optional[str] = image.multimodal_content.media_objects[0].location
if location is not None:
image_locations.append(location)
return image_locations
class Schema:
"""Specifies information about what to display on the frontend."""
# Adapter fields (e.g., temperature)
adapter: List[Field]
# Information about each field
metrics: List[Field]
# Information about each perturbation
perturbations: List[Field]
# Group the metrics
metric_groups: List[MetricGroup]
# Group the scenarios
run_groups: List[RunGroup]
def __post_init__(self):
self.name_to_metric = {metric.name: metric for metric in self.metrics}
self.name_to_perturbation = {perturbation.name: perturbation for perturbation in self.perturbations}
self.name_to_metric_group = {metric_group.name: metric_group for metric_group in self.metric_groups}
self.name_to_run_group = {run_group.name: run_group for run_group in self.run_groups}
class RunSpec:
"""
Specifies how to do a single run, which gets a scenario, adapts it, and
computes a list of stats based on the defined metrics.
"""
name: str
"""Unique identifier of the RunSpec"""
scenario_spec: ScenarioSpec
"""Which scenario"""
adapter_spec: AdapterSpec
"""Specifies how to adapt an instance into a set of requests"""
metric_specs: List[MetricSpec]
"""What to evaluate on"""
data_augmenter_spec: DataAugmenterSpec = DataAugmenterSpec()
"""Data augmenter. The default `DataAugmenterSpec` does nothing."""
groups: List[str] = field(default_factory=list)
"""Groups that this run spec belongs to (for aggregation)"""
annotators: Optional[List[AnnotatorSpec]] = None
"""Annotators to use for this run spec"""
def __post_init__(self):
"""
`self.name` is used as the name of the output folder for the `RunSpec`.
Clean up `self.name` by replacing any "/"'s with "_".
"""
# TODO: Don't mutate name! clean this up before passing it into the constructor here
object.__setattr__(self, "name", self.name.replace(os.path.sep, "_"))
class Input:
"""
The input of an `Instance`.
"""
text: str = ""
"""The text of the input (e.g, passage to summarize, text for sentiment analysis, etc.)"""
multimedia_content: Optional[MultimediaObject] = None
"""A single input can consists of multimodal content interleaved (e.g., text, image, text, ...)."""
class Instance:
"""
An `Instance` represents one data point that we're evaluating on (e.g., one
question in a QA task).
Note: `eq=False` means that we hash by the identity.
"""
input: Input
"""The input"""
references: List[Reference]
"""References that helps us evaluate"""
split: Optional[str] = None
"""Split (e.g., train, valid, test)"""
sub_split: Optional[str] = None
"""Sub split (e.g. toxic, non-toxic)"""
id: Optional[str] = None
"""Used to group Instances that were created from a particular Instance through data augmentation"""
perturbation: Optional[PerturbationDescription] = None
"""Description of the Perturbation that was applied when creating this Instance"""
contrast_inputs: Optional[List[Input]] = None
"""Perturbed input as defined by contrast sets (if available)"""
contrast_references: Optional[List[List[Reference]]] = None
"""References for the perturbed input above (if available)"""
def first_correct_reference(self) -> Optional[Reference]:
"""Return the first correct reference."""
for reference in self.references:
if reference.is_correct:
return reference
return None
def all_correct_references(self) -> List[Reference]:
"""Return all correct references."""
return [reference for reference in self.references if reference.is_correct]
def render_lines(self) -> List[str]:
info = [f"input: {format_text(self.input.text)}"]
if self.sub_split:
info.append(f"sub_split: {format_text(self.sub_split)}")
if self.id:
info.append(f"id: {format_text(self.id)}")
if self.perturbation:
info.append(f"perturbation: {self.perturbation}")
for reference in self.references:
info.extend(reference.render_lines())
return info
def write(file_path: str, content: str):
"""Write content out to a file at path file_path."""
hlog(f"Writing {len(content)} characters to {file_path}")
with open(file_path, "w") as f:
f.write(content)
def hlog(x: Any) -> None:
singleton.log(x)
def encode_base64(image_location: str, format="JPEG") -> str:
"""Returns the base64 representation of an image file."""
image_file = io.BytesIO()
image: Image.Image = open_image(image_location)
image.save(image_file, format=format)
return base64.b64encode(image_file.getvalue()).decode("ascii")
def to_json(data: Any) -> str:
return json.dumps(_converter.unstructure(data), indent=2)
The provided code snippet includes necessary dependencies for implementing the `write_run_display_json` function. Write a Python function `def write_run_display_json(run_path: str, run_spec: RunSpec, schema: Schema, skip_completed: bool) -> None` to solve the following problem:
Write run JSON files that are used by the web frontend. The derived JSON files that are used by the web frontend are much more compact than the source JSON files. This speeds up web frontend loading significantly. Reads: - ScenarioState from `scenario_state.json` - List[PerInstanceStats] from `per_instance_stats.json` Writes: - List[Instance] to `instances.json` - List[DisplayPrediction] to `display_predictions.json` - List[DisplayRequest] to `display_requests.json`
Here is the function:
def write_run_display_json(run_path: str, run_spec: RunSpec, schema: Schema, skip_completed: bool) -> None:
"""Write run JSON files that are used by the web frontend.
The derived JSON files that are used by the web frontend are much more compact than
the source JSON files. This speeds up web frontend loading significantly.
Reads:
- ScenarioState from `scenario_state.json`
- List[PerInstanceStats] from `per_instance_stats.json`
Writes:
- List[Instance] to `instances.json`
- List[DisplayPrediction] to `display_predictions.json`
- List[DisplayRequest] to `display_requests.json`
"""
instances_file_path = os.path.join(run_path, _INSTANCES_JSON_FILE_NAME)
display_predictions_file_path = os.path.join(run_path, _DISPLAY_PREDICTIONS_JSON_FILE_NAME)
display_requests_file_path = os.path.join(run_path, _DISPLAY_REQUESTS_JSON_FILE_NAME)
scenario_state_path = os.path.join(run_path, "scenario_state.json")
per_instance_stats_path = os.path.join(run_path, "per_instance_stats.json")
if (
skip_completed
and os.path.exists(instances_file_path)
and os.path.exists(display_predictions_file_path)
and os.path.exists(display_requests_file_path)
):
hlog(
f"Skipping writing display JSON for run {run_spec.name} "
"because all output display JSON files already exist."
)
return
elif not os.path.exists(scenario_state_path):
hlog(
f"Skipping writing display JSON for run {run_spec.name} because "
f"the scenario state JSON file does not exist at {scenario_state_path}"
)
return
elif not os.path.exists(per_instance_stats_path):
hlog(
f"Skipping writing display JSON for run {run_spec.name} because "
f"the per instance stats JSON file does not exist at {per_instance_stats_path}"
)
return
scenario_state = _read_scenario_state(scenario_state_path)
per_instance_stats = _read_per_instance_stats(per_instance_stats_path)
metric_names = _get_metric_names_for_groups(run_spec.groups, schema)
if run_spec.adapter_spec.method in ADAPT_MULTIPLE_CHOICE_SEPARATE_METHODS:
metric_names.add("predicted_index")
stats_by_trial: Dict[Tuple[str, Optional[PerturbationDescription], int], Dict[str, float]] = defaultdict(dict)
for original_stats in per_instance_stats:
stats_dict: Dict[str, float] = {
original_stat.name.name: original_stat.mean
for original_stat in original_stats.stats
if original_stat.name.name in metric_names and original_stat.mean is not None
}
key = (
original_stats.instance_id,
original_stats.perturbation,
original_stats.train_trial_index,
)
stats_by_trial[key].update(stats_dict)
instance_id_to_instance: Dict[Tuple[str, Optional[PerturbationDescription]], Instance] = OrderedDict()
predictions: List[DisplayPrediction] = []
requests: List[DisplayRequest] = []
for request_state in scenario_state.request_states:
assert request_state.instance.id is not None
if request_state.result is None:
continue
# For the multiple_choice_separate_calibrated adapter method,
# only keep the original prediction and discard the calibration prediction.
if (
run_spec.adapter_spec.method == ADAPT_MULTIPLE_CHOICE_SEPARATE_CALIBRATED
and request_state.request_mode == "calibration"
):
continue
stats_key = (
request_state.instance.id,
request_state.instance.perturbation,
request_state.train_trial_index,
)
trial_stats: Dict[str, float] = stats_by_trial[stats_key]
# For the multiple_choice_separate_* adapter methods,
# only keep the prediction for the chosen reference and discard the rest.
if (
run_spec.adapter_spec.method in ADAPT_MULTIPLE_CHOICE_SEPARATE_METHODS
and "predicted_index" in trial_stats
and trial_stats["predicted_index"] != request_state.reference_index
):
continue
predicted_text = (
request_state.result.completions[0].text
if request_state.result is not None and request_state.result.completions
else ""
)
mapped_output = (
request_state.output_mapping.get(predicted_text.strip()) if request_state.output_mapping else None
)
instance_id_to_instance[
(request_state.instance.id, request_state.instance.perturbation)
] = request_state.instance
# TODO: hacky way to display input images on the old frontend
if request_state.instance.input.multimedia_content is not None:
html_input: str = ""
for media_object in request_state.instance.input.multimedia_content.media_objects:
if media_object.is_type("image") and media_object.location is not None:
html_input += f'<br><img src="data:image;base64,{encode_base64(media_object.location)}">'
elif media_object.is_type("text") and media_object.text is not None:
html_input += f"<br>{media_object.text}"
else:
raise ValueError(f"Unhandled media type: {media_object.type}")
instance_id_to_instance[(request_state.instance.id, request_state.instance.perturbation)] = replace(
request_state.instance,
input=Input(text=html_input),
)
# Process images and include if they exist
images: List[str] = [
encode_base64(image_location)
for image_location in gather_generated_image_locations(request_state.result)
if os.path.exists(image_location)
]
predictions.append(
DisplayPrediction(
instance_id=request_state.instance.id,
perturbation=request_state.instance.perturbation,
train_trial_index=request_state.train_trial_index,
predicted_text=predicted_text,
truncated_predicted_text=_truncate_predicted_text(predicted_text, request_state, run_spec.adapter_spec),
base64_images=images,
mapped_output=mapped_output,
reference_index=request_state.reference_index,
stats=trial_stats,
)
)
requests.append(
DisplayRequest(
instance_id=request_state.instance.id,
perturbation=request_state.instance.perturbation,
train_trial_index=request_state.train_trial_index,
request=request_state.request,
)
)
write(
instances_file_path,
to_json(list(instance_id_to_instance.values())),
)
write(display_predictions_file_path, to_json(predictions))
write(
display_requests_file_path,
to_json(requests),
) | Write run JSON files that are used by the web frontend. The derived JSON files that are used by the web frontend are much more compact than the source JSON files. This speeds up web frontend loading significantly. Reads: - ScenarioState from `scenario_state.json` - List[PerInstanceStats] from `per_instance_stats.json` Writes: - List[Instance] to `instances.json` - List[DisplayPrediction] to `display_predictions.json` - List[DisplayRequest] to `display_requests.json` |
16,269 | from dataclasses import dataclass
from typing import Optional, List
import dacite
from helm.common.general import parse_hocon
from helm.common.hierarchical_logger import hlog
class RunEntries:
entries: List[RunEntry]
def merge_run_entries(run_entries1: RunEntries, run_entries2: RunEntries):
return RunEntries(run_entries1.entries + run_entries2.entries)
def parse_hocon(text: str):
"""Parse `text` (in HOCON format) into a dict-like object."""
return pyhocon.ConfigFactory.parse_string(text)
def hlog(x: Any) -> None:
singleton.log(x)
The provided code snippet includes necessary dependencies for implementing the `read_run_entries` function. Write a Python function `def read_run_entries(paths: List[str]) -> RunEntries` to solve the following problem:
Read a HOCON file `path` and return the `RunEntry`s.
Here is the function:
def read_run_entries(paths: List[str]) -> RunEntries:
"""Read a HOCON file `path` and return the `RunEntry`s."""
run_entries = RunEntries([])
for path in paths:
with open(path) as f:
raw = parse_hocon(f.read())
run_entries = merge_run_entries(run_entries, dacite.from_dict(RunEntries, raw))
hlog(f"Read {len(run_entries.entries)} run entries from {path}")
return run_entries | Read a HOCON file `path` and return the `RunEntry`s. |
16,270 | import json
import os
import argparse
from typing import List, DefaultDict, Set
from collections import defaultdict
from helm.common.general import asdict_without_nones, ensure_directory_exists
from helm.common.hierarchical_logger import hlog, htrack_block
from helm.benchmark.scenarios.scenario import (
Scenario,
Instance,
create_scenario,
TRAIN_SPLIT,
VALID_SPLIT,
TEST_SPLIT,
ScenarioSpec,
with_instance_ids,
)
from helm.benchmark.presentation.run_entry import read_run_entries
from helm.benchmark.run import run_entries_to_run_specs
from helm.benchmark.data_overlap.light_scenario import LightInstance, LightScenario, LightScenarioKey
def create_light_instance_from_instance(instance: Instance) -> LightInstance:
"""Create a LightInstance given an Instance. Only keep the text attributes."""
input_text: str = instance.input.text
reference_texts: List[str] = [reference.output.text for reference in instance.references]
return LightInstance(input=input_text, references=reference_texts, id=instance.id)
def ensure_directory_exists(path: str):
"""Create `path` if it doesn't exist."""
os.makedirs(path, exist_ok=True)
class htrack_block:
def __init__(self, x: Any) -> None:
self.x = x
def __enter__(self) -> None:
singleton.track_begin(self.x)
def __exit__(self, tpe: Any, value: Any, callback: Any) -> None:
singleton.track_end()
TRAIN_SPLIT: str = "train"
VALID_SPLIT: str = "valid"
TEST_SPLIT: str = "test"
class Instance:
"""
An `Instance` represents one data point that we're evaluating on (e.g., one
question in a QA task).
Note: `eq=False` means that we hash by the identity.
"""
input: Input
"""The input"""
references: List[Reference]
"""References that helps us evaluate"""
split: Optional[str] = None
"""Split (e.g., train, valid, test)"""
sub_split: Optional[str] = None
"""Sub split (e.g. toxic, non-toxic)"""
id: Optional[str] = None
"""Used to group Instances that were created from a particular Instance through data augmentation"""
perturbation: Optional[PerturbationDescription] = None
"""Description of the Perturbation that was applied when creating this Instance"""
contrast_inputs: Optional[List[Input]] = None
"""Perturbed input as defined by contrast sets (if available)"""
contrast_references: Optional[List[List[Reference]]] = None
"""References for the perturbed input above (if available)"""
def first_correct_reference(self) -> Optional[Reference]:
"""Return the first correct reference."""
for reference in self.references:
if reference.is_correct:
return reference
return None
def all_correct_references(self) -> List[Reference]:
"""Return all correct references."""
return [reference for reference in self.references if reference.is_correct]
def render_lines(self) -> List[str]:
info = [f"input: {format_text(self.input.text)}"]
if self.sub_split:
info.append(f"sub_split: {format_text(self.sub_split)}")
if self.id:
info.append(f"id: {format_text(self.id)}")
if self.perturbation:
info.append(f"perturbation: {self.perturbation}")
for reference in self.references:
info.extend(reference.render_lines())
return info
class Scenario(ABC):
"""
A scenario represents a (task, data distribution).
It is usually based on some raw dataset and is converted into a list of `Instance`s.
Override this class.
Note: the constructor should be lightweight, `get_instances` should do all
the heavy lifting.
"""
# Set by the Scenario subclass.
name: str = field(init=False)
"""Short unique identifier of the scenario"""
# Set by the Scenario subclass.
description: str = field(init=False)
"""Description of the scenario (task, data)"""
# Set by the Scenario subclass.
tags: List[str] = field(init=False)
"""Extra metadata (e.g., whether this is a question answering or commonsense task)"""
definition_path: str = field(init=False)
"""Where the scenario subclass for `self` is defined."""
def __post_init__(self) -> None:
parts = list(PurePath(inspect.getfile(type(self))).parts)
path = parts.pop()
parts.reverse()
for part in parts:
path = part + "/" + path
if part == "helm":
break
self.definition_path = "https://github.com/stanford-crfm/helm/blob/main/src/" + path
def get_instances(self, output_path: str) -> List[Instance]:
"""
Does the main work in the `Scenario` (e.g., download datasets, convert
it into a list of instances).
"""
pass
def render_lines(self, instances: List[Instance]) -> List[str]:
total = len(instances)
output = [
f"name: {self.name}",
f"description: {self.description}",
f"tags: {format_tags(self.tags)}",
"",
]
for i, instance in enumerate(instances):
output.append(f"instance {i} ({total} total) {format_split(str(instance.split))} {{")
output.extend(indent_lines(instance.render_lines()))
output.append("}")
return output
def with_instance_ids(instances: List[Instance]) -> List[Instance]:
"""Return the instances with an ID. Note: order of instances matters."""
return [replace(instance, id=f"id{i}") for i, instance in enumerate(instances)]
class ScenarioSpec(ObjectSpec):
pass
def create_scenario(scenario_spec: ScenarioSpec) -> Scenario:
"""Construct the scenario and set some fields."""
return create_object(scenario_spec)
class LightInstance:
"""
A lighter `Instance` with only text fields.
"""
input: str
"""The input"""
references: List[str]
"""References that help us evaluate"""
id: Optional[str] = None
"""Helm instance id"""
class LightScenarioKey:
"""
Key for LightScenario
"""
scenario_spec: ScenarioSpec
split: str
def __hash__(self):
return hash((self.scenario_spec, self.split))
class LightScenario:
"""
A lighter `Scenario`.
"""
scenario_key: LightScenarioKey
instances: List[LightInstance]
"""Instances of this scenario"""
The provided code snippet includes necessary dependencies for implementing the `get_light_scenarios_from_scenario_spec` function. Write a Python function `def get_light_scenarios_from_scenario_spec( scenario_spec: ScenarioSpec, scenario_download_path: str = "exported_scenarios" ) -> List[LightScenario]` to solve the following problem:
Create a list of LightInstances given a ScenarioSpec. Only keep the text of the input and references. Note that one LightScenario object is created for each split of the Scenario for simplification.
Here is the function:
def get_light_scenarios_from_scenario_spec(
scenario_spec: ScenarioSpec, scenario_download_path: str = "exported_scenarios"
) -> List[LightScenario]:
"""
Create a list of LightInstances given a ScenarioSpec. Only keep the text of the input and references.
Note that one LightScenario object is created for each split of the Scenario for simplification.
"""
scenario: Scenario = create_scenario(scenario_spec)
ensure_directory_exists(scenario_download_path)
scenario_output_path = os.path.join(scenario_download_path, scenario.name)
ensure_directory_exists(scenario_output_path)
# Load instances
instances: List[Instance]
with htrack_block("scenario.get_instances"):
instances = scenario.get_instances(scenario_output_path)
# Get instance ids
instances = with_instance_ids(instances)
# Classify instances into splits
splits: List[str] = [TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT]
split_mapping: DefaultDict[str, list] = defaultdict(list)
for instance in instances:
if instance.split is None or instance.split not in splits:
raise ValueError(
f"split should be one of {TRAIN_SPLIT}, {VALID_SPLIT}, or {TEST_SPLIT}, but got {instance.split}"
)
split_mapping[instance.split].append(instance)
# Convert Scenarios to LightScenarios
light_scenarios: List[LightScenario] = []
for split, instances in split_mapping.items():
light_instances: List[LightInstance] = [create_light_instance_from_instance(instance) for instance in instances]
light_scenario_key: LightScenarioKey = LightScenarioKey(
scenario_spec=scenario_spec,
split=split,
)
light_scenario = LightScenario(
scenario_key=light_scenario_key,
instances=light_instances,
)
light_scenarios.append(light_scenario)
return light_scenarios | Create a list of LightInstances given a ScenarioSpec. Only keep the text of the input and references. Note that one LightScenario object is created for each split of the Scenario for simplification. |
16,271 | import json
import os
import argparse
from typing import List, DefaultDict, Set
from collections import defaultdict
from helm.common.general import asdict_without_nones, ensure_directory_exists
from helm.common.hierarchical_logger import hlog, htrack_block
from helm.benchmark.scenarios.scenario import (
Scenario,
Instance,
create_scenario,
TRAIN_SPLIT,
VALID_SPLIT,
TEST_SPLIT,
ScenarioSpec,
with_instance_ids,
)
from helm.benchmark.presentation.run_entry import read_run_entries
from helm.benchmark.run import run_entries_to_run_specs
from helm.benchmark.data_overlap.light_scenario import LightInstance, LightScenario, LightScenarioKey
def asdict_without_nones(obj: Any) -> Dict[str, Any]:
if not is_dataclass(obj):
raise ValueError(f"Expected dataclass, got '{obj}'")
return asdict(obj, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})
class LightScenario:
"""
A lighter `Scenario`.
"""
scenario_key: LightScenarioKey
instances: List[LightInstance]
"""Instances of this scenario"""
The provided code snippet includes necessary dependencies for implementing the `save_scenarios_to_jsonl` function. Write a Python function `def save_scenarios_to_jsonl(light_scenarios: List[LightScenario], filename: str)` to solve the following problem:
Save a list of LightInstance to a jsonl file where each line represents a LightScenario object.
Here is the function:
def save_scenarios_to_jsonl(light_scenarios: List[LightScenario], filename: str):
"""
Save a list of LightInstance to a jsonl file where each line represents a LightScenario object.
"""
with open(filename, "a") as f:
for light_scenario in light_scenarios:
f.write(json.dumps(asdict_without_nones(light_scenario), ensure_ascii=False) + "\n") | Save a list of LightInstance to a jsonl file where each line represents a LightScenario object. |
16,272 | import json
import os
from typing import Dict, List
from helm.common.general import ensure_file_downloaded
def get_split_to_class_to_pinned_file_order(download_dir: str):
"""Lazily download and return a nested mapping of split to class to pinned file order."""
global _split_to_class_to_pinned_file_order
if not _split_to_class_to_pinned_file_order:
file_path: str = os.path.join(download_dir, _PINNED_FILE_ORDER_FILENAME)
ensure_file_downloaded(
source_url=_PINNED_FILE_ORDER_URL,
target_path=file_path,
unpack=False,
)
with open(file_path) as f:
_split_to_class_to_pinned_file_order = json.load(f)
return _split_to_class_to_pinned_file_order
The provided code snippet includes necessary dependencies for implementing the `listdir_with_pinned_file_order` function. Write a Python function `def listdir_with_pinned_file_order(download_dir: str, split: str, class_name: str) -> List[str]` to solve the following problem:
List files for the split in a pinned order for IMDB to ensure reproducibility. Unfortunately, the previous official HELM runs used the arbitrary file order produced by os.listdir() and did not sort the files, so future runs must use the same file order in order to sample the same instances to reproduce the official HELM runs.
Here is the function:
def listdir_with_pinned_file_order(download_dir: str, split: str, class_name: str) -> List[str]:
"""List files for the split in a pinned order for IMDB to ensure reproducibility.
Unfortunately, the previous official HELM runs used the arbitrary file order
produced by os.listdir() and did not sort the files, so future runs must use
the same file order in order to sample the same instances to reproduce
the official HELM runs."""
return get_split_to_class_to_pinned_file_order(download_dir)[split][class_name] | List files for the split in a pinned order for IMDB to ensure reproducibility. Unfortunately, the previous official HELM runs used the arbitrary file order produced by os.listdir() and did not sort the files, so future runs must use the same file order in order to sample the same instances to reproduce the official HELM runs. |
16,273 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
class TokenizerService:
"""
A wrapper around `Service` that makes only necessary server requests to tokenize.
"""
def __init__(self, service: Service, auth: Authentication):
self._service: Service = service
self._auth: Authentication = auth
def tokenize(self, request: TokenizationRequest) -> TokenizationRequestResult:
"""Tokenize via an API."""
return self._service.tokenize(self._auth, request)
def decode(self, request: DecodeRequest) -> DecodeRequestResult:
"""Decode via an API."""
return self._service.decode(self._auth, request)
def get_info(self, model_name: str) -> WindowServiceInfo:
"""Get info via an API."""
return self._service.get_window_service_info(model_name)
class Authentication:
"""Needed to authenticate with the proxy server to make requests, etc.."""
api_key: str
class ServerService(Service):
"""
Main class that supports various functionality for the server.
"""
def __init__(
self,
base_path: str = "prod_env",
root_mode: bool = False,
cache_backend_config: CacheBackendConfig = BlackHoleCacheBackendConfig(),
):
ensure_directory_exists(base_path)
client_file_storage_path = os.path.join(base_path, CACHE_DIR)
ensure_directory_exists(client_file_storage_path)
credentials = get_credentials(base_path)
accounts_path = os.path.join(base_path, ACCOUNTS_FILE)
self.cache_backend_config = cache_backend_config
self.client = AutoClient(credentials, client_file_storage_path, cache_backend_config)
self.tokenizer = AutoTokenizer(credentials, cache_backend_config)
self.token_counter = AutoTokenCounter(self.tokenizer)
self.accounts = Accounts(accounts_path, root_mode=root_mode)
# Lazily instantiate the following clients
self.moderation_api_client: Optional[ModerationAPIClient] = None
self.toxicity_classifier_client: Optional[ToxicityClassifierClient] = None
self.perspective_api_client: Optional[PerspectiveAPIClient] = None
self.nudity_check_client: Optional[NudityCheckClient] = None
self.clip_score_client: Optional[CLIPScoreClient] = None
self.gcs_client: Optional[GCSClient] = None
def get_general_info(self) -> GeneralInfo:
# Can't send release_dates in ModelMetadata bacause dates cannot be round-tripped to and from JSON easily.
# TODO(#2158): Either fix this or delete get_general_info.
all_models = [dataclasses.replace(model_metadata, release_date=None) for model_metadata in ALL_MODELS_METADATA]
return GeneralInfo(version=VERSION, example_queries=example_queries, all_models=all_models)
def get_window_service_info(self, model_name) -> WindowServiceInfo:
# The import statement is placed here to avoid two problems, please refer to the link for details
# https://github.com/stanford-crfm/helm/pull/1430#discussion_r1156686624
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.benchmark.window_services.window_service_factory import WindowServiceFactory
token_service = TokenizerService(self, Authentication(""))
window_service = WindowServiceFactory.get_window_service(model_name, token_service)
return WindowServiceInfo(
tokenizer_name=window_service.tokenizer_name,
max_sequence_length=window_service.max_sequence_length,
max_request_length=window_service.max_request_length,
end_of_text_token=window_service.end_of_text_token,
prefix_token=window_service.prefix_token,
)
def expand_query(self, query: Query) -> QueryResult:
"""Turn the `query` into requests."""
prompt = query.prompt
settings = query.settings
environments = parse_hocon(query.environments)
requests = []
for environment in expand_environments(environments):
request = synthesize_request(prompt, settings, environment)
requests.append(request)
return QueryResult(requests=requests)
def _get_model_group_for_model_deployment(self, model_deployment: str) -> str:
if model_deployment.startswith("openai/"):
if model_deployment.startswith("openai/code-"):
return "codex"
elif model_deployment.startswith("openai/dall-e-"):
return "dall_e"
elif model_deployment.startswith("openai/gpt-4-"):
return "gpt4"
else:
return "gpt3"
elif model_deployment.startswith("ai21/"):
return "jurassic"
else:
return get_model_deployment_host_organization(model_deployment)
def make_request(self, auth: Authentication, request: Request) -> RequestResult:
"""Actually make a request to an API."""
# TODO: try to invoke the API even if we're not authenticated, and if
# it turns out the results are cached, then we can just hand back the results.
# https://github.com/stanford-crfm/benchmarking/issues/56
self.accounts.authenticate(auth)
model_group: str = self._get_model_group_for_model_deployment(request.model_deployment)
# Make sure we can use
self.accounts.check_can_use(auth.api_key, model_group)
# Use!
request_result: RequestResult = self.client.make_request(request)
# Only deduct if not cached
if not request_result.cached:
# Count the number of tokens used
count: int = self.token_counter.count_tokens(request, request_result.completions)
self.accounts.use(auth.api_key, model_group, count)
return request_result
def tokenize(self, auth: Authentication, request: TokenizationRequest) -> TokenizationRequestResult:
"""Tokenize via an API."""
self.accounts.authenticate(auth)
return self.tokenizer.tokenize(request)
def decode(self, auth: Authentication, request: DecodeRequest) -> DecodeRequestResult:
"""Decodes to text."""
self.accounts.authenticate(auth)
return self.tokenizer.decode(request)
def upload(self, auth: Authentication, request: FileUploadRequest) -> FileUploadResult:
"""Uploads a file to external storage."""
self.accounts.authenticate(auth)
if not self.gcs_client:
self.gcs_client = self.client.get_gcs_client()
assert self.gcs_client
return self.gcs_client.upload(request)
def check_nudity(self, auth: Authentication, request: NudityCheckRequest) -> NudityCheckResult:
"""Check for nudity."""
self.accounts.authenticate(auth)
if not self.nudity_check_client:
self.nudity_check_client = self.client.get_nudity_check_client()
assert self.nudity_check_client
return self.nudity_check_client.check_nudity(request)
def compute_clip_score(self, auth: Authentication, request: CLIPScoreRequest) -> CLIPScoreResult:
"""Computes CLIPScore for a given caption and image."""
self.accounts.authenticate(auth)
if not self.clip_score_client:
self.clip_score_client = self.client.get_clip_score_client()
assert self.clip_score_client
return self.clip_score_client.compute_score(request)
def get_toxicity_scores(self, auth: Authentication, request: PerspectiveAPIRequest) -> PerspectiveAPIRequestResult:
def get_toxicity_scores_with_retry(request: PerspectiveAPIRequest) -> PerspectiveAPIRequestResult:
if not self.toxicity_classifier_client:
self.toxicity_classifier_client = self.client.get_toxicity_classifier_client()
return self.toxicity_classifier_client.get_toxicity_scores(request)
self.accounts.authenticate(auth)
return get_toxicity_scores_with_retry(request)
def get_moderation_results(self, auth: Authentication, request: ModerationAPIRequest) -> ModerationAPIRequestResult:
def get_moderation_results_with_retry(request: ModerationAPIRequest) -> ModerationAPIRequestResult:
if not self.moderation_api_client:
self.moderation_api_client = self.client.get_moderation_api_client()
return self.moderation_api_client.get_moderation_results(request)
self.accounts.authenticate(auth)
return get_moderation_results_with_retry(request)
def make_critique_request(self, auth: Authentication, request: CritiqueRequest) -> CritiqueRequestResult:
self.accounts.authenticate(auth)
return self.client.get_critique_client().make_critique_request(request)
def create_account(self, auth: Authentication) -> Account:
"""Creates a new account."""
return self.accounts.create_account(auth)
def delete_account(self, auth: Authentication, api_key: str) -> Account:
return self.accounts.delete_account(auth, api_key)
def get_accounts(self, auth: Authentication) -> List[Account]:
"""Get list of accounts."""
return self.accounts.get_all_accounts(auth)
def get_account(self, auth: Authentication) -> Account:
"""Get information about an account."""
return self.accounts.get_account(auth)
def update_account(self, auth: Authentication, account: Account) -> Account:
"""Update account."""
return self.accounts.update_account(auth, account)
def rotate_api_key(self, auth: Authentication, account: Account) -> Account:
"""Generate a new API key for this account."""
return self.accounts.rotate_api_key(auth, account)
def shutdown(self, auth: Authentication):
"""Shutdown server (admin-only)."""
self.accounts.check_admin(auth)
pid = os.getpid()
hlog(f"Shutting down server by killing its own process {pid}...")
os.kill(pid, signal.SIGTERM)
hlog("Done.")
def get_cache_config(self, shard_name: str) -> CacheConfig:
return self.cache_backend_config.get_cache_config(shard_name)
def get_test_tokenizer_service() -> TokenizerService:
# Pointed to the default local path set in run.py (--local-path)
return TokenizerService(ServerService(base_path="prod_env", root_mode=True), Authentication("test")) | null |
16,274 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
def get_powers(terms: List[List[int]]) -> List[List[Tuple[int, int]]]:
return list(map(lambda _: list(zip(*np.unique(_, return_counts=True))), terms))
The provided code snippet includes necessary dependencies for implementing the `stringify_terms` function. Write a Python function `def stringify_terms(terms: List[List[int]], variable_names: List[str] = list("xyz")) -> List[str]` to solve the following problem:
Formatting utility for multisets.
Here is the function:
def stringify_terms(terms: List[List[int]], variable_names: List[str] = list("xyz")) -> List[str]:
"""Formatting utility for multisets."""
def stringify_power(index: int, degree: int) -> str:
"""Helper formatting utility for powers."""
var = variable_names[index]
if degree == 0:
return ""
if degree == 1:
return var
return f"{var}^{degree}"
powers = get_powers(terms)
return list(map(lambda _: "".join([stringify_power(*el) for el in _]), powers)) | Formatting utility for multisets. |
16,275 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
Range = List[Tuple[int, int]]
class Polynomial:
"""A simple polynomial class over the integers that supports evaluation and pretty-printing."""
degree: int
num_variables: int
coeffs: npt.NDArray[np.int64]
terms: List[List[int]] = field(init=False)
def __post_init__(self):
self.terms = generate_terms(self.degree, self.num_variables)
def eval(self, vals: List[int]):
return np.dot(self.coeffs, np.array(list(map(lambda _: np.prod(np.array(vals).__getitem__(_)), self.terms))))
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
if coeff == 0:
return None
if coeff == 1:
return term or str(coeff)
if coeff == -1:
return f"-{term}" if term else "-1"
return f"{coeff}{term}"
monomials = [stringify_monomial(c, x) for c, x in zip(self.coeffs, stringify_terms(self.terms))]
present_monomials: List[str] = [m for m in monomials if m]
return " + ".join(present_monomials).replace(" + -", " - ")
def from_string(cls, expr_str: str, degree: int, num_variables: int):
expr = sympy.parse_expr(expr_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = Poly(expr, list(sorted(expr.free_symbols, key=lambda _: _.name)))
return sympy_poly_to_poly(poly, degree, num_variables)
def generate_polynomial(
degree: int,
num_variables: int,
range_coeffs: Range, # inclusive
seed: Optional[int] = None,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) -> Polynomial:
"""Sample the coefficients (A, B, ...) of the polynomial equation y = ... + A x + B.
A generic method used by the function class-specific methods below.
Args:
strict_degree (bool): if True, require `rel` to have degree strictly equal to `degree`
strict_variables (bool): if True, require `rel` to use exactly `num_variables`
strict_constant (bool): if True, require the constant (ie. term of degree 0) to be non-zero
Returns:
`rel` (Polynomial)
"""
MAX_ATTEMPTS = 100
if seed is not None:
random.seed(seed)
np.random.seed(seed)
count = 0
terms = generate_terms(degree, num_variables)
while count < MAX_ATTEMPTS:
done = True
coeffs = [random.randint(r[0], r[1]) for r in range_coeffs]
if strict_constant and coeffs[-1] == 0:
done = False
if strict_degree and not sum(coeffs[: comb(degree + num_variables - 1, num_variables - 1)]):
done = False
if strict_variables:
for idx in range(num_variables):
vals = np.zeros(num_variables)
vals[idx] = 1
res = np.dot(coeffs[:-1], np.array(list(map(lambda _: np.prod(vals.__getitem__(_)), terms[:-1]))))
if not res:
done = False
break
if done:
break
count += 1
if count >= MAX_ATTEMPTS:
raise ValueError(
"Failed to sample valid polynomial equation within "
+ f"{MAX_ATTEMPTS} attempts from ranges {str(range_coeffs)}."
)
return Polynomial(degree=degree, num_variables=num_variables, coeffs=np.array(coeffs))
def generate_linear(range_coeffs: Range) -> Polynomial:
return generate_polynomial(
degree=1,
num_variables=1,
range_coeffs=range_coeffs,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) | null |
16,276 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
Range = List[Tuple[int, int]]
class Polynomial:
"""A simple polynomial class over the integers that supports evaluation and pretty-printing."""
degree: int
num_variables: int
coeffs: npt.NDArray[np.int64]
terms: List[List[int]] = field(init=False)
def __post_init__(self):
self.terms = generate_terms(self.degree, self.num_variables)
def eval(self, vals: List[int]):
return np.dot(self.coeffs, np.array(list(map(lambda _: np.prod(np.array(vals).__getitem__(_)), self.terms))))
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
if coeff == 0:
return None
if coeff == 1:
return term or str(coeff)
if coeff == -1:
return f"-{term}" if term else "-1"
return f"{coeff}{term}"
monomials = [stringify_monomial(c, x) for c, x in zip(self.coeffs, stringify_terms(self.terms))]
present_monomials: List[str] = [m for m in monomials if m]
return " + ".join(present_monomials).replace(" + -", " - ")
def from_string(cls, expr_str: str, degree: int, num_variables: int):
expr = sympy.parse_expr(expr_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = Poly(expr, list(sorted(expr.free_symbols, key=lambda _: _.name)))
return sympy_poly_to_poly(poly, degree, num_variables)
def generate_polynomial(
degree: int,
num_variables: int,
range_coeffs: Range, # inclusive
seed: Optional[int] = None,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) -> Polynomial:
"""Sample the coefficients (A, B, ...) of the polynomial equation y = ... + A x + B.
A generic method used by the function class-specific methods below.
Args:
strict_degree (bool): if True, require `rel` to have degree strictly equal to `degree`
strict_variables (bool): if True, require `rel` to use exactly `num_variables`
strict_constant (bool): if True, require the constant (ie. term of degree 0) to be non-zero
Returns:
`rel` (Polynomial)
"""
MAX_ATTEMPTS = 100
if seed is not None:
random.seed(seed)
np.random.seed(seed)
count = 0
terms = generate_terms(degree, num_variables)
while count < MAX_ATTEMPTS:
done = True
coeffs = [random.randint(r[0], r[1]) for r in range_coeffs]
if strict_constant and coeffs[-1] == 0:
done = False
if strict_degree and not sum(coeffs[: comb(degree + num_variables - 1, num_variables - 1)]):
done = False
if strict_variables:
for idx in range(num_variables):
vals = np.zeros(num_variables)
vals[idx] = 1
res = np.dot(coeffs[:-1], np.array(list(map(lambda _: np.prod(vals.__getitem__(_)), terms[:-1]))))
if not res:
done = False
break
if done:
break
count += 1
if count >= MAX_ATTEMPTS:
raise ValueError(
"Failed to sample valid polynomial equation within "
+ f"{MAX_ATTEMPTS} attempts from ranges {str(range_coeffs)}."
)
return Polynomial(degree=degree, num_variables=num_variables, coeffs=np.array(coeffs))
def generate_parabola(range_coeffs: Range) -> Polynomial:
return generate_polynomial(
degree=2,
num_variables=1,
range_coeffs=range_coeffs,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) | null |
16,277 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
Range = List[Tuple[int, int]]
class Polynomial:
def __post_init__(self):
def eval(self, vals: List[int]):
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
def from_string(cls, expr_str: str, degree: int, num_variables: int):
def generate_polynomial(
degree: int,
num_variables: int,
range_coeffs: Range, # inclusive
seed: Optional[int] = None,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) -> Polynomial:
def generate_paraboloid(range_coeffs: Range) -> Polynomial:
return generate_polynomial(
degree=2,
num_variables=2,
range_coeffs=range_coeffs,
strict_degree=True,
strict_variables=True,
strict_constant=True,
) | null |
16,278 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
Range = List[Tuple[int, int]]
class Polynomial:
"""A simple polynomial class over the integers that supports evaluation and pretty-printing."""
degree: int
num_variables: int
coeffs: npt.NDArray[np.int64]
terms: List[List[int]] = field(init=False)
def __post_init__(self):
self.terms = generate_terms(self.degree, self.num_variables)
def eval(self, vals: List[int]):
return np.dot(self.coeffs, np.array(list(map(lambda _: np.prod(np.array(vals).__getitem__(_)), self.terms))))
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
if coeff == 0:
return None
if coeff == 1:
return term or str(coeff)
if coeff == -1:
return f"-{term}" if term else "-1"
return f"{coeff}{term}"
monomials = [stringify_monomial(c, x) for c, x in zip(self.coeffs, stringify_terms(self.terms))]
present_monomials: List[str] = [m for m in monomials if m]
return " + ".join(present_monomials).replace(" + -", " - ")
def from_string(cls, expr_str: str, degree: int, num_variables: int):
expr = sympy.parse_expr(expr_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = Poly(expr, list(sorted(expr.free_symbols, key=lambda _: _.name)))
return sympy_poly_to_poly(poly, degree, num_variables)
def sympy_poly_to_poly(poly: Poly, degree: int, num_variables: int) -> Polynomial:
terms = poly.terms()
all_terms = generate_terms(degree, num_variables)
all_powers = get_powers(all_terms)
coeffs_dict = defaultdict(int, {tuple(sympy_power_to_power(power)): coeff for power, coeff in terms})
coeffs = [coeffs_dict[tuple(_)] for _ in all_powers]
return Polynomial(degree=degree, num_variables=num_variables, coeffs=np.array(coeffs))
def generate_plane(range_coeffs: Range) -> Polynomial:
return generate_polynomial(
degree=1,
num_variables=2,
range_coeffs=range_coeffs,
strict_degree=True,
strict_variables=True,
strict_constant=True,
)
The provided code snippet includes necessary dependencies for implementing the `generate_rotated_translated_paraboloid` function. Write a Python function `def generate_rotated_translated_paraboloid(range_coeffs: Range) -> Polynomial` to solve the following problem:
Unused.
Here is the function:
def generate_rotated_translated_paraboloid(range_coeffs: Range) -> Polynomial:
"""Unused."""
do_sample = True
while do_sample:
coeffs_0 = generate_plane(range_coeffs).coeffs
coeffs_1 = generate_plane(range_coeffs).coeffs
mat = np.array(
[
coeffs_0,
coeffs_1,
]
)
if np.linalg.matrix_rank(mat) == 2:
do_sample = False
x = Symbol("x")
y = Symbol("y")
xprime = coeffs_0[0] * x + coeffs_0[1] * y + coeffs_0[2]
yprime = coeffs_1[0] * x + coeffs_1[1] * y + coeffs_1[2]
expr = xprime**2 + yprime**2
poly = Poly(expr, [x, y])
return sympy_poly_to_poly(poly, 2, 2) | Unused. |
16,279 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
class Polynomial:
"""A simple polynomial class over the integers that supports evaluation and pretty-printing."""
degree: int
num_variables: int
coeffs: npt.NDArray[np.int64]
terms: List[List[int]] = field(init=False)
def __post_init__(self):
self.terms = generate_terms(self.degree, self.num_variables)
def eval(self, vals: List[int]):
return np.dot(self.coeffs, np.array(list(map(lambda _: np.prod(np.array(vals).__getitem__(_)), self.terms))))
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
if coeff == 0:
return None
if coeff == 1:
return term or str(coeff)
if coeff == -1:
return f"-{term}" if term else "-1"
return f"{coeff}{term}"
monomials = [stringify_monomial(c, x) for c, x in zip(self.coeffs, stringify_terms(self.terms))]
present_monomials: List[str] = [m for m in monomials if m]
return " + ".join(present_monomials).replace(" + -", " - ")
def from_string(cls, expr_str: str, degree: int, num_variables: int):
expr = sympy.parse_expr(expr_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = Poly(expr, list(sorted(expr.free_symbols, key=lambda _: _.name)))
return sympy_poly_to_poly(poly, degree, num_variables)
RELTYPE_INFO: Dict[str, RelationTypeInfo] = {
"linear": RelationTypeInfo(
name="linear", degree=1, num_variables=1, range=[(1, 5), (1, 5)], example_coeffs=np.array([2, 5])
), # 2x + 5
"parabola": RelationTypeInfo(
# parabolas with axis of symmetry to the left of the origin
name="parabola",
degree=2,
num_variables=1,
range=[(1, 2), (0, 2), (1, 5)],
example_coeffs=np.array([1, 0, 2]),
), # x^2 + 2
"plane": RelationTypeInfo(
name="plane", degree=1, num_variables=2, range=[(1, 5), (1, 5), (1, 5)], example_coeffs=np.array([2, 1, 5])
), # 2x + y + 5
"paraboloid": RelationTypeInfo(
# axis-aligned elliptic paraboloids only, ie. of the form z = A x^2 + B y^2 + C
name="paraboloid",
degree=2,
num_variables=2,
range=[(1, 2), (0, 1), (1, 2), (0, 0), (0, 0), (1, 5)],
example_coeffs=np.array([2, 0, 1, 0, 0, 2]),
), # 2x^2 + y^2 + 2
}
The provided code snippet includes necessary dependencies for implementing the `distance_linear` function. Write a Python function `def distance_linear(point: List[int], rel_str: str)` to solve the following problem:
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: A x - y + B = 0
Here is the function:
def distance_linear(point: List[int], rel_str: str):
"""
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form:
A x - y + B = 0
"""
relation_type = "linear"
degree: int = RELTYPE_INFO[relation_type].degree
num_variables: int = RELTYPE_INFO[relation_type].num_variables
rel = Polynomial.from_string(rel_str.split(" = ")[-1], degree, num_variables)
A = rel.coeffs[0]
B = -1
C = rel.coeffs[1]
x, y = point
return float(abs((A * x + B * y + C)) / (math.sqrt(A**2 + B**2))) | Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: A x - y + B = 0 |
16,280 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
try:
import sympy
from sympy import Symbol, Poly, diff
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
except ModuleNotFoundError as e:
handle_module_not_found_error(e, ["scenarios"])
SYMPY_TRANSFORMATIONS = standard_transformations + (implicit_multiplication_application,)
The provided code snippet includes necessary dependencies for implementing the `distance_parabola` function. Write a Python function `def distance_parabola(point: List[int], rel_str: str, TOL: float = 1e-10)` to solve the following problem:
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: y = A x^2 + B x + C
Here is the function:
def distance_parabola(point: List[int], rel_str: str, TOL: float = 1e-10):
"""
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form:
y = A x^2 + B x + C
"""
rel_str = rel_str.split(" = ")[-1]
expr = sympy.parse_expr(rel_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = sympy.Poly(expr, list(expr.free_symbols))
x = list(expr.free_symbols)[0]
x0, y0 = point
dist = (x - x0) ** 2 + (poly - y0) ** 2
deriv = sympy.diff(dist, x)
try:
sols = sympy.solve(deriv, x)
except ZeroDivisionError:
# This shouldn't happen, but has happened for a prior implementation of
# `distance_paraboloid`, so catch it conservatively:
print("Failed to compute minimum distance.")
# pdb.set_trace()
return float(0.0)
dist_vals = list(map(lambda _: sympy.N(dist.eval(_)), sols))
try:
dist_val = min([sympy.re(_) for _ in dist_vals if abs(sympy.im(_)) < TOL and sympy.re(_) >= 0])
except ValueError:
# A real solution should exist, but if not (eg. numerical error exceeds TOL):
print("Failed to compute minimum distance.")
# pdb.set_trace()
return float(0.0)
return np.sqrt(float(dist_val)) | Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: y = A x^2 + B x + C |
16,281 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
class Polynomial:
"""A simple polynomial class over the integers that supports evaluation and pretty-printing."""
degree: int
num_variables: int
coeffs: npt.NDArray[np.int64]
terms: List[List[int]] = field(init=False)
def __post_init__(self):
self.terms = generate_terms(self.degree, self.num_variables)
def eval(self, vals: List[int]):
return np.dot(self.coeffs, np.array(list(map(lambda _: np.prod(np.array(vals).__getitem__(_)), self.terms))))
def __str__(self):
def stringify_monomial(coeff: int, term: str) -> Optional[str]:
if coeff == 0:
return None
if coeff == 1:
return term or str(coeff)
if coeff == -1:
return f"-{term}" if term else "-1"
return f"{coeff}{term}"
monomials = [stringify_monomial(c, x) for c, x in zip(self.coeffs, stringify_terms(self.terms))]
present_monomials: List[str] = [m for m in monomials if m]
return " + ".join(present_monomials).replace(" + -", " - ")
def from_string(cls, expr_str: str, degree: int, num_variables: int):
expr = sympy.parse_expr(expr_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
poly = Poly(expr, list(sorted(expr.free_symbols, key=lambda _: _.name)))
return sympy_poly_to_poly(poly, degree, num_variables)
RELTYPE_INFO: Dict[str, RelationTypeInfo] = {
"linear": RelationTypeInfo(
name="linear", degree=1, num_variables=1, range=[(1, 5), (1, 5)], example_coeffs=np.array([2, 5])
), # 2x + 5
"parabola": RelationTypeInfo(
# parabolas with axis of symmetry to the left of the origin
name="parabola",
degree=2,
num_variables=1,
range=[(1, 2), (0, 2), (1, 5)],
example_coeffs=np.array([1, 0, 2]),
), # x^2 + 2
"plane": RelationTypeInfo(
name="plane", degree=1, num_variables=2, range=[(1, 5), (1, 5), (1, 5)], example_coeffs=np.array([2, 1, 5])
), # 2x + y + 5
"paraboloid": RelationTypeInfo(
# axis-aligned elliptic paraboloids only, ie. of the form z = A x^2 + B y^2 + C
name="paraboloid",
degree=2,
num_variables=2,
range=[(1, 2), (0, 1), (1, 2), (0, 0), (0, 0), (1, 5)],
example_coeffs=np.array([2, 0, 1, 0, 0, 2]),
), # 2x^2 + y^2 + 2
}
The provided code snippet includes necessary dependencies for implementing the `distance_plane` function. Write a Python function `def distance_plane(point: List[int], rel_str: str)` to solve the following problem:
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: A x + B y - z + C = 0
Here is the function:
def distance_plane(point: List[int], rel_str: str):
"""
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form:
A x + B y - z + C = 0
"""
relation_type = "plane"
degree: int = RELTYPE_INFO[relation_type].degree
num_variables: int = RELTYPE_INFO[relation_type].num_variables
rel = Polynomial.from_string(rel_str.split(" = ")[-1], degree, num_variables)
A = rel.coeffs[0]
B = rel.coeffs[1]
C = -1
D = rel.coeffs[2]
x, y, z = point
d = abs((A * x + B * y + C * z + D))
e = math.sqrt(A**2 + B**2 + C**2)
return float(d / e) | Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: A x + B y - z + C = 0 |
16,282 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
try:
import sympy
from sympy import Symbol, Poly, diff
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
except ModuleNotFoundError as e:
handle_module_not_found_error(e, ["scenarios"])
SYMPY_TRANSFORMATIONS = standard_transformations + (implicit_multiplication_application,)
The provided code snippet includes necessary dependencies for implementing the `distance_paraboloid` function. Write a Python function `def distance_paraboloid(point: List[int], rel_str: str, TOL: float = 1e-10)` to solve the following problem:
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: z = A x^2 + B x y + C y^2 + D x + E y + F Uses method of Lagrange multipliers.
Here is the function:
def distance_paraboloid(point: List[int], rel_str: str, TOL: float = 1e-10):
"""
Returns the minimum distance from the given point to the relation given by `rel_str` which has the form:
z = A x^2 + B x y + C y^2 + D x + E y + F
Uses method of Lagrange multipliers.
"""
rel_str = rel_str.split(" = ")[-1]
expr = sympy.parse_expr(rel_str.replace("^", "**"), transformations=SYMPY_TRANSFORMATIONS)
x, y = list(expr.free_symbols)
if x.name == "y":
x, y = y, x
z = Symbol("z")
x0, y0, z0 = point
f = (x - x0) ** 2 + (y - y0) ** 2 + (z - z0) ** 2
g = z - expr
if abs(g.subs([(x, x0), (y, y0), (z, z0)])) < TOL:
return float(0.0)
λ = Symbol("λ")
# The code below is meant to be equivalent to
# `sols = sympy.solve([eq_x, eq_y, eq_z, g], [x, y, z, λ])`
# but sympy.solve was failing to find any solution on many inputs
# as well as not finding some solutions
# so this breaks it down for the special case of `f - λ g` which is at most quadratic.
# Set up the equations from method of Lagrange multipliers
eq_x = diff(f, x) - λ * diff(g, x)
eq_y = diff(f, y) - λ * diff(g, y)
eq_z = diff(f, z) - λ * diff(g, z)
# Solve for each variable individually
has_xy = y in eq_x.free_symbols # has xy term
if has_xy:
sols_x = sympy.solve(eq_x, [x, y, λ])
sols_y = sympy.solve(eq_y, [x, y, λ])
sols_z = sympy.solve(eq_z, [z, λ])
else:
sols_x = sympy.solve(eq_x, [x, λ])
sols_y = sympy.solve(eq_y, [y, λ])
sols_z = sympy.solve(eq_z, [z, λ])
try:
# Put the solutions together
# Extract x,y,z resp. from tuples
sols_lst_xyz = [[_[0] for _ in lst] for lst in [sols_x, sols_y, sols_z]]
# Extract solutions for λ from tuples
sols_lst_λλλ = [[_[-1] for _ in lst] for lst in [sols_x, sols_y, sols_z]]
# Get list of possible solution tuples and corresponding solutions for λ
sols_xyz = list(product(*sols_lst_xyz))
vals_λ = list(product(*sols_lst_λλλ))
sols = []
# Try each possible combined solution for x, y, z, λ
for sol_xyz, val_λs in zip(sols_xyz, vals_λ):
val_λs = tuple(set(filter(lambda _: not _.is_symbol, val_λs))) # get distinct values for λ if there are any
if len(val_λs) > 1: # there can be at most one distinct value for λ
continue
val_λ = val_λs[0] if val_λs else λ
sol_x, sol_y, sol_z = sol_xyz
if not val_λ.is_symbol:
# Substitute in values of λ
sol_x = sol_x.subs(λ, val_λ)
sol_y = sol_y.subs(λ, val_λ)
sol_z = sol_z.subs(λ, val_λ)
g_λ = g.subs(λ, val_λ)
else:
g_λ = g
# Substitute in solutions for x, y, z
if has_xy:
g_λ = g_λ.subs([(x, sol_x), (z, sol_z)])
sol_ys = sympy.solve(sol_x - sol_y, y)
for sol_y in sol_ys:
g_λy = g_λ.subs(y, sol_y)
sol_xy = sol_x.subs(y, sol_y)
syms = list(g_λy.free_symbols)
if len(syms) > 1: # underdetermined system
continue
sym = syms[0]
vals = [sympy.N(_) for _ in sympy.solveset(g_λy, sym)]
sols.extend([(sol_xy.subs(sym, _), sol_y.subs(sym, _), sol_z.subs(sym, _)) for _ in vals])
else:
g_λ = g_λ.subs([(x, sol_x), (y, sol_y), (z, sol_z)])
syms = list(g_λ.free_symbols)
if len(syms) > 1: # underdetermined system
continue
# Solve for remaining variable
sym = syms[0]
vals = [sympy.N(_) for _ in sympy.solveset(g_λ, sym)]
sols.extend([(sol_x.subs(sym, _), sol_y.subs(sym, _), sol_z.subs(sym, _)) for _ in vals])
except ZeroDivisionError:
# This shouldn't happen, but has happened for a prior implementation of
# `distance_paraboloid`, so catch it conservatively:
print("Failed to compute minimum distance.")
# pdb.set_trace()
return float(0.0)
poly_f = sympy.Poly(f, [x, y, z])
# Evaluate f on found solutions
try:
dist_vals = list(map(lambda _: sympy.N(poly_f.eval(_)), sols))
except sympy.polys.polyerrors.UnificationFailed:
# Forgot to substitute all variables in some expression.
# This shouldn't happen, but has happened for a prior implementation of
# `distance_paraboloid`, so catch it conservatively:
print("sympy error: Unification failed.")
# pdb.set_trace()
return float(0.0)
# Get the minimum nonnegative real value
try:
dist_val = min([sympy.re(_) for _ in dist_vals if abs(sympy.im(_)) < TOL and sympy.re(_) >= 0])
except ValueError:
# A real solution should exist, but if not (eg. numerical error exceeds TOL):
print("Failed to compute minimum distance.")
print([eq_x, eq_y, eq_z, g])
print(sols)
# pdb.set_trace()
return float(0.0)
return np.sqrt(float(dist_val)) | Returns the minimum distance from the given point to the relation given by `rel_str` which has the form: z = A x^2 + B x y + C y^2 + D x + E y + F Uses method of Lagrange multipliers. |
16,283 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
Range = List[Tuple[int, int]]
The provided code snippet includes necessary dependencies for implementing the `select_ranges` function. Write a Python function `def select_ranges( num_train: int, num_test: int, dim: int, overlap: bool = True, nonnegative_only: bool = False ) -> Tuple[Range, Range]` to solve the following problem:
Choose disjoint intervals from which to sample points, where the test points lie within a region bounded by the region that the train points are sampled from.
Here is the function:
def select_ranges(
num_train: int, num_test: int, dim: int, overlap: bool = True, nonnegative_only: bool = False
) -> Tuple[Range, Range]:
"""
Choose disjoint intervals from which to sample points, where
the test points lie within a region bounded by the region
that the train points are sampled from.
"""
choices: npt.NDArray[np.int64] = np.array([0, 1, 2, 5, 10, 20, 50, 100, 200])
def select_index(lst: npt.NDArray[np.int64], val: int) -> int:
return list((lst - val) >= 0).index(True)
def construct_range(index: int, dim: int) -> List[Tuple[int, int]]:
if nonnegative_only:
return [(0, choices[index]) for _ in range(dim)]
return [(-choices[index], choices[index]) for _ in range(dim)]
if nonnegative_only:
num_points = (choices + 1) ** dim # list of ints
else:
num_points = (2 * choices + 1) ** dim # list of ints
if overlap:
train_index = test_index = select_index(num_points, num_train + num_test)
else:
test_index = select_index(num_points, num_test)
train_index = select_index(num_points - num_points[test_index], num_train)
test_range = construct_range(test_index, dim)
train_range = construct_range(train_index, dim)
return (train_range, test_range) | Choose disjoint intervals from which to sample points, where the test points lie within a region bounded by the region that the train points are sampled from. |
16,284 | from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations_with_replacement, product
import math
from math import comb
import numpy as np
import numpy.typing as npt
import random
from typing import List, Optional, Tuple, Dict
from helm.benchmark.adaptation.adapters.adapter_factory import ADAPT_GENERATION
from helm.benchmark.adaptation.adapter_spec import AdapterSpec
from helm.benchmark.window_services.tokenizer_service import TokenizerService
from helm.common.authentication import Authentication
from helm.common.optional_dependencies import handle_module_not_found_error
from helm.proxy.services.server_service import ServerService
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
def get_var(dim: int, variable_names=list("xyz")):
return variable_names[dim - 1] | null |
16,285 | from pathlib import Path
from typing import List, Optional, Any
import datasets
from datasets import load_dataset
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
def _clean_and_truncate(text: str, max_num_words: Optional[int] = None) -> str:
text = text.replace("\n", " ")
whitespace_tokens = text.split()
if max_num_words:
whitespace_tokens = whitespace_tokens[:max_num_words]
return " ".join(whitespace_tokens) | null |
16,286 | import io
import json
import os
import sys
from typing import List, Dict, Iterable, Optional, cast
from helm.common.general import ensure_file_downloaded
from helm.common.hierarchical_logger import hlog
from .code_scenario_helper import run as run_reindent
from .code_scenario_apps_pinned_file_order import apps_listdir_with_pinned_order
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
class CodeReference(Reference):
# Extra none-string metadata, e.g., paths.
test_cases: Optional[Dict] = None
def __init__(self, test_cases=None, **kw):
self.test_cases = test_cases
super(CodeReference, self).__init__(**kw)
class CodeInstance(Instance):
reference: CodeReference
# Extra none-string metadata, e.g., paths.
metadata: Optional[Dict] = None
def __init__(self, metadata=None, **kw):
self.metadata = metadata
super(CodeInstance, self).__init__(**kw)
def _read_human_eval(evalset_file: str = "HumanEval.jsonl") -> Dict[str, Dict]:
return {task["task_id"]: task for task in _stream_jsonl(evalset_file)}
TRAIN_SPLIT: str = "train"
VALID_SPLIT: str = "valid"
TEST_SPLIT: str = "test"
CORRECT_TAG: str = "correct"
class Input:
"""
The input of an `Instance`.
"""
text: str = ""
"""The text of the input (e.g, passage to summarize, text for sentiment analysis, etc.)"""
multimedia_content: Optional[MultimediaObject] = None
"""A single input can consists of multimodal content interleaved (e.g., text, image, text, ...)."""
class Output:
"""
The output of a `Reference`.
"""
text: str = ""
"""The text of the output."""
multimedia_content: Optional[MultimediaObject] = None
"""The output can be multimodal content interleaved (e.g., text, image, text, ...)."""
def _read_and_preprocess_human_eval(
target_path: str, num_train_instances: int, num_val_instances: int, num_test_instances: int
) -> List[CodeInstance]:
problems = _read_human_eval(target_path)
instances = []
for sample_idx, task_id in enumerate(problems):
if sample_idx < num_train_instances:
split = TRAIN_SPLIT
elif sample_idx < num_train_instances + num_val_instances:
split = VALID_SPLIT
else:
split = TEST_SPLIT
instance = CodeInstance(
input=Input(text=problems[task_id]["prompt"]),
references=[
CodeReference(
output=Output(text=problems[task_id]["canonical_solution"]),
test_cases=problems[task_id],
tags=[CORRECT_TAG],
)
],
split=split,
)
instances.append(instance)
return instances | null |
16,287 | import io
import json
import os
import sys
from typing import List, Dict, Iterable, Optional, cast
from helm.common.general import ensure_file_downloaded
from helm.common.hierarchical_logger import hlog
from .code_scenario_helper import run as run_reindent
from .code_scenario_apps_pinned_file_order import apps_listdir_with_pinned_order
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
class CodeReference(Reference):
# Extra none-string metadata, e.g., paths.
test_cases: Optional[Dict] = None
def __init__(self, test_cases=None, **kw):
self.test_cases = test_cases
super(CodeReference, self).__init__(**kw)
class CodeInstance(Instance):
reference: CodeReference
# Extra none-string metadata, e.g., paths.
metadata: Optional[Dict] = None
def __init__(self, metadata=None, **kw):
self.metadata = metadata
super(CodeInstance, self).__init__(**kw)
def _reindent_code(codestr):
"""Given code string, reindent it in the same way that the Github dataset was indented"""
codestr = io.StringIO(codestr)
ret = io.StringIO()
run_reindent(
codestr,
ret,
config={
"dry-run": False,
"help": False,
"to": 4,
"from": -1,
"tabs": True,
"encoding": "utf-8",
"is-tabs": False,
"tabsize": 4,
"all-tabs": False,
},
)
return ret.getvalue()
def _make_input_for_apps(question: str, starter_code: str, answer_type: str) -> str:
"""Format the prompt as in the original training pipeline."""
# Different from the original paper: We add the phrase 'in Python' to make models only generate Python code;
# otherwise models can generate C++ and code in other languages. The evaluation engine, mostly copied from the
# original APPS codebase, runs PyExt and has no way to execute C++ code.
# The extra phrase isn't needed when there's in-context examples of Python code.
return "\nQUESTION:\n" + question + "\n" + starter_code + "\n" + answer_type + "\nANSWER in Python code:\n"
# Below is what's used in the original paper for reference and comparison.
# return "\nQUESTION:\n" + question + "\n" + starter_code + "\n" + answer_type + "\nANSWER:\n"
def hlog(x: Any) -> None:
singleton.log(x)
def apps_listdir_with_pinned_order(download_dir: str, split_tag: str) -> List[str]:
"""List files for the split in a pinned order for APPS to ensure reproducibility.
Unfortunately, the previous official HELM runs used the arbitrary file order
produced by os.listdir() and did not sort the files, so future runs must use
the same file order in order to sample the same test instances to reproduce
the official HELM runs."""
pinned_filename_order = get_apps_split_to_pinned_file_order(download_dir).get(split_tag)
if pinned_filename_order:
return pinned_filename_order
return list(sorted(os.listdir(os.path.join(download_dir, split_tag))))
TRAIN_SPLIT: str = "train"
TEST_SPLIT: str = "test"
CORRECT_TAG: str = "correct"
class Input:
"""
The input of an `Instance`.
"""
text: str = ""
"""The text of the input (e.g, passage to summarize, text for sentiment analysis, etc.)"""
multimedia_content: Optional[MultimediaObject] = None
"""A single input can consists of multimodal content interleaved (e.g., text, image, text, ...)."""
class Output:
"""
The output of a `Reference`.
"""
text: str = ""
"""The text of the output."""
multimedia_content: Optional[MultimediaObject] = None
"""The output can be multimodal content interleaved (e.g., text, image, text, ...)."""
The provided code snippet includes necessary dependencies for implementing the `_read_and_preprocess_apps` function. Write a Python function `def _read_and_preprocess_apps(target_path: str) -> List[CodeInstance]` to solve the following problem:
Read APPS dataset. Adapted from https://github.com/lxuechen/apps/blob/main/train/dataset_apps/APPSBaseDataset.py
Here is the function:
def _read_and_preprocess_apps(target_path: str) -> List[CodeInstance]:
"""Read APPS dataset.
Adapted from
https://github.com/lxuechen/apps/blob/main/train/dataset_apps/APPSBaseDataset.py
"""
# Some versions of Python have a configurable maximum number of digits of integers that can be parsed
# from strings. This limit also applies to parsing integers in JSON. The default limit is 4300 digits.
#
# Reading APPS instances will fail with the default limit because the APPS dataset contains very large
# integers.
#
# The sys.set_int_max_str_digits() method can be used to increase the limit. This method exists if and
# only if the version of Python has a default limit.
#
# See: https://docs.python.org/3/library/stdtypes.html#int-max-str-digits
if hasattr(sys, "set_int_max_str_digits"):
sys.set_int_max_str_digits(100000)
SINGLE_STR_LIMIT = 150000 # From original codebase.
instances = []
for split_tag in (TRAIN_SPLIT, TEST_SPLIT):
split_dir = os.path.join(target_path, split_tag)
num_problems = 0
skipped_problems = []
for problem_name in apps_listdir_with_pinned_order(target_path, split_tag):
problem_dir = os.path.join(split_dir, problem_name)
question_fname = os.path.join(problem_dir, "question.txt")
sols_fname = os.path.join(problem_dir, "solutions.json")
tests_fname = os.path.join(problem_dir, "input_output.json")
# All instances must have the question description.
if not os.path.isfile(question_fname):
skipped_problems.append(problem_name)
continue
else:
# Train instances must have solution code.
if split_tag in ("train",):
if not os.path.isfile(sols_fname):
skipped_problems.append(problem_name)
continue
# Test instances can ignore solution code, but must have test cases.
elif split_tag in ("test",):
if not os.path.exists(tests_fname) or not os.path.isfile(tests_fname):
skipped_problems.append(problem_name)
continue
# Answer type.
starter_code_fname = os.path.join(problem_dir, "starter_code.py")
if os.path.exists(starter_code_fname):
answer_type = "\nUse Call-Based format\n"
else:
answer_type = "\nUse Standard Input format\n"
# Starter code.
if os.path.isfile(starter_code_fname):
with open(starter_code_fname, "r") as f:
starter_code = f.read()
else:
starter_code = ""
# Question description.
with open(question_fname, "r") as f:
question = f.read()
# Solutions. Multiple of them!
if os.path.isfile(sols_fname):
with open(sols_fname, "r") as f:
sols_str_list = json.load(f)
solutions = [_reindent_code(sol_str) for sol_str in sols_str_list]
else:
solutions = []
# Tests.
if os.path.exists(tests_fname):
with open(tests_fname, "r") as f:
# Some files may contain the key `fn_name`, which indicates it's
# call-based instance. Annoying!
# Call-based instances check function input/outputs; for other instances
# I/O is handled through stdin and stdout streams.
data: Dict = json.load(f)
else:
data = dict()
data["root"] = problem_dir
# Truncate for training, following original codebase.
question = question[:SINGLE_STR_LIMIT]
starter_code = starter_code[:SINGLE_STR_LIMIT]
solutions = [sol[:SINGLE_STR_LIMIT] for sol in solutions]
if len(solutions) == 0:
solutions = [""]
# Create overall prompt.
prompt = _make_input_for_apps(
question=question,
starter_code=starter_code,
answer_type=answer_type,
)
instance = CodeInstance(
input=Input(text=prompt),
references=[
CodeReference(output=Output(text=solution), tags=[CORRECT_TAG], test_cases=data)
for solution in solutions
],
split=split_tag,
metadata=data,
)
instances.append(instance)
num_problems += 1
# Should not skip any cases; just defensive.
hlog(
f"Split {split_tag}, "
f"skipped {len(skipped_problems)}/{num_problems} problems with no description or solution. "
f"Their ids are: {skipped_problems}"
)
return instances | Read APPS dataset. Adapted from https://github.com/lxuechen/apps/blob/main/train/dataset_apps/APPSBaseDataset.py |
16,288 | import numpy as np
from typing import List, Dict, Tuple
from .scenario import Scenario, Instance, Reference, TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT, CORRECT_TAG, Input, Output
def subst(pattern: List[str], rule_symbol: str, substitute_str: str) -> List[str]:
"""
We substitute one rule symbols in a pattern according by a substitution str.
example:
pattern = "A+B=B+A"
rule_symbol = "A"
substitute_str = "apple"
return: "apple+B=B+apple"
:param pattern: A Pattern representing the rule.
:param rule_symbol: One rule symbol.
:param substitute_str: The substitution string.
:return: The result of substitution.
"""
assert rule_symbol in pattern
# check which index is the same as rule_symbol
indices = [i for i, x in enumerate(pattern) if x == rule_symbol]
# form a new string with the symbol replaced
new_string = pattern[: indices[0]] + [substitute_str]
for i, j in zip(indices[:-1], indices[1:]):
new_string += pattern[i + 1 : j]
new_string += [substitute_str]
new_string += pattern[indices[-1] + 1 :]
return new_string
The provided code snippet includes necessary dependencies for implementing the `pattern_subst` function. Write a Python function `def pattern_subst(pattern: List[str], rule_symbols: List[str], substitute_dict: Dict[str, str]) -> List[str]` to solve the following problem:
We substitute the rule symbols in a pattern according to a substitution dictionary. example: pattern = "A+B=B+A" rule_symbols = ["A", "B"] substitute_dict = {"A":"apple", "B":"peach"} return: "apple+peach=peach+apple" :param pattern: A Pattern representing the rule. :param rule_symbols: The set of rule symbols. :param substitute_dict: The substitution dictionary. :return: The result of substitution.
Here is the function:
def pattern_subst(pattern: List[str], rule_symbols: List[str], substitute_dict: Dict[str, str]) -> List[str]:
"""
We substitute the rule symbols in a pattern according to a substitution dictionary.
example:
pattern = "A+B=B+A"
rule_symbols = ["A", "B"]
substitute_dict = {"A":"apple", "B":"peach"}
return: "apple+peach=peach+apple"
:param pattern: A Pattern representing the rule.
:param rule_symbols: The set of rule symbols.
:param substitute_dict: The substitution dictionary.
:return: The result of substitution.
"""
out = pattern
# we iteratively replace each rule symbol with its subsitution string
for symbol in rule_symbols:
out = subst(out, symbol, substitute_dict[symbol])
return out | We substitute the rule symbols in a pattern according to a substitution dictionary. example: pattern = "A+B=B+A" rule_symbols = ["A", "B"] substitute_dict = {"A":"apple", "B":"peach"} return: "apple+peach=peach+apple" :param pattern: A Pattern representing the rule. :param rule_symbols: The set of rule symbols. :param substitute_dict: The substitution dictionary. :return: The result of substitution. |
16,289 | from collections import defaultdict
from dataclasses import dataclass, field, replace
from functools import cached_property
from typing import List, Optional
from helm.common.hierarchical_logger import hlog
import dacite
import re
import yaml
class Grammar:
"""
A grammar, specified by a set of `rules` defines a set of strings generated
by that grammar, and is a compact way of specifying a large structured set
of strings.
"""
rules: List[GrammarRule]
def category_to_rules(self):
category_to_rules = defaultdict(list)
for rule in self.rules:
category_to_rules[rule.category].append(rule)
return category_to_rules
def validate_grammar(grammar: Grammar):
for rule in grammar.rules:
for expansion in rule.expansions:
# Make sure all categories are defined
for category in expansion.categories:
if category not in grammar.category_to_rules:
hlog(f"WARNING: Category {category} is not defined")
The provided code snippet includes necessary dependencies for implementing the `read_grammar` function. Write a Python function `def read_grammar(path: str) -> Grammar` to solve the following problem:
Read a grammar from `path` and return it.
Here is the function:
def read_grammar(path: str) -> Grammar:
"""Read a grammar from `path` and return it."""
with open(path) as f:
raw = yaml.safe_load(f)
grammar = dacite.from_dict(Grammar, raw)
validate_grammar(grammar)
return grammar | Read a grammar from `path` and return it. |
16,290 | from collections import defaultdict
from dataclasses import dataclass, field, replace
from functools import cached_property
from typing import List, Optional
from helm.common.hierarchical_logger import hlog
import dacite
import re
import yaml
ROOT_CATEGORY = "Root"
def get_category(text: str) -> Optional[str]:
"""
Parse the category out of `text`; return `None` if it's not a category.
Example: "${Root}" => "Root"
"""
if text.startswith("${") and text.endswith("}"):
return text[2:-1]
return None
class Expansion:
"""
An `Expansion` corresponds to the right-hand side of a grammar rule,
and consists of a sequence of tokens and categories.
The Expansion is given by a single string `text`, in which categories are specified
using special notation (e.g., ${Topic}).
Example: text = "this is a ${Topic}"
"""
text: str
tags: List[str] = field(default_factory=list)
def children(self):
"""
List of categories and tokens.
Example: ['this is a ', '${Topic}', '']
"""
return re.split(r"(\${\w+})", self.text)
def categories(self):
"""
Return the list of categories (non-terminals).
Example: ["Topic"]
"""
return [x for x in [get_category(child) for child in self.children] if x is not None]
class GrammarRule:
"""
Represents a set of grammar rules:
<category> -> expansions[0]
<category> -> expansions[1]
...
"""
category: str
expansions: List[Expansion]
tags: List[str] = field(default_factory=list)
class Grammar:
"""
A grammar, specified by a set of `rules` defines a set of strings generated
by that grammar, and is a compact way of specifying a large structured set
of strings.
"""
rules: List[GrammarRule]
def category_to_rules(self):
category_to_rules = defaultdict(list)
for rule in self.rules:
category_to_rules[rule.category].append(rule)
return category_to_rules
class Derivation:
"""
A `Derivation` corresponds to a node in a parse tree.
Exactly one of {value, children} should be specified depending whether this
node is a leaf or not.
`tags` is based on the tags of the grammar rules, and is used to filter out
examples later.
"""
value: Optional[str]
children: Optional[List["Derivation"]]
tags: List[str]
def is_leaf(self):
return self.value is not None
def generate_derivations(grammar: Grammar) -> List[Derivation]:
def expand_rule_expansion(rule: GrammarRule, expansion: Expansion) -> List[Derivation]:
results: List[Derivation] = [Derivation(value=None, children=[], tags=rule.tags + expansion.tags)]
# Go through each item of the RHS of the rule and expand it, forming
# the cross product as we go.
for item in expansion.children:
# Get list of candidate children
candidates: List[Derivation] = []
category = get_category(item)
if category is None:
# Terminal
candidates = [Derivation(value=item, children=None, tags=[])]
else:
# Non-terminal
candidates = expand_category(category)
# Extend each derivation with each candidate children
new_results: List[Derivation] = []
for derivation in results:
for child in candidates:
assert derivation.children is not None
new_derivation = replace(derivation, children=derivation.children + [child])
new_results.append(new_derivation)
results = new_results
return results
def expand_category(category: str) -> List[Derivation]:
results: List[Derivation] = []
for rule in grammar.category_to_rules[category]:
for expansion in rule.expansions:
results.extend(expand_rule_expansion(rule, expansion))
return results
return expand_category(ROOT_CATEGORY) | null |
16,291 | from collections import defaultdict
from dataclasses import dataclass, field, replace
from functools import cached_property
from typing import List, Optional
from helm.common.hierarchical_logger import hlog
import dacite
import re
import yaml
class Derivation:
"""
A `Derivation` corresponds to a node in a parse tree.
Exactly one of {value, children} should be specified depending whether this
node is a leaf or not.
`tags` is based on the tags of the grammar rules, and is used to filter out
examples later.
"""
value: Optional[str]
children: Optional[List["Derivation"]]
tags: List[str]
def is_leaf(self):
return self.value is not None
The provided code snippet includes necessary dependencies for implementing the `get_values` function. Write a Python function `def get_values(derivation: Derivation) -> List[str]` to solve the following problem:
Return all the `values` that are collected recursively.
Here is the function:
def get_values(derivation: Derivation) -> List[str]:
"""Return all the `values` that are collected recursively."""
if derivation.is_leaf:
assert derivation.value is not None
return [derivation.value]
values: List[str] = []
assert derivation.children is not None
for child in derivation.children:
values.extend(get_values(child))
return values | Return all the `values` that are collected recursively. |
16,292 | from collections import defaultdict
from dataclasses import dataclass, field, replace
from functools import cached_property
from typing import List, Optional
from helm.common.hierarchical_logger import hlog
import dacite
import re
import yaml
class Derivation:
"""
A `Derivation` corresponds to a node in a parse tree.
Exactly one of {value, children} should be specified depending whether this
node is a leaf or not.
`tags` is based on the tags of the grammar rules, and is used to filter out
examples later.
"""
value: Optional[str]
children: Optional[List["Derivation"]]
tags: List[str]
def is_leaf(self):
return self.value is not None
The provided code snippet includes necessary dependencies for implementing the `get_tags` function. Write a Python function `def get_tags(derivation: Derivation) -> List[str]` to solve the following problem:
Return all the `tags` that are collected recursively.
Here is the function:
def get_tags(derivation: Derivation) -> List[str]:
"""Return all the `tags` that are collected recursively."""
tags: List[str] = []
tags.extend(derivation.tags)
if derivation.children is not None:
for child in derivation.children:
tags.extend(get_tags(child))
return tags | Return all the `tags` that are collected recursively. |
16,293 | import json
import os
from typing import Dict, Tuple
import numpy as np
from helm.common.general import ensure_file_downloaded
def get_split_to_fixed_random_seed(download_dir: str):
"""Lazily download and return a dict of dataset to fixed random seed."""
global _split_to_fixed_random_seed
if not _split_to_fixed_random_seed:
file_path: str = os.path.join(download_dir, _FIXED_RANDOM_SEED_FILENAME)
ensure_file_downloaded(
source_url=_FIXED_RANDOM_SEED_URL,
target_path=file_path,
unpack=False,
)
with open(file_path) as f:
raw_split_to_fixed_random_seed = json.load(f)
for dataset, raw_fixed_random_seed in raw_split_to_fixed_random_seed.items():
_split_to_fixed_random_seed[dataset] = (
str(raw_fixed_random_seed[0]),
np.array(
raw_fixed_random_seed[1],
dtype=np.uint32,
),
int(raw_fixed_random_seed[2]),
int(raw_fixed_random_seed[3]),
int(raw_fixed_random_seed[4]),
)
return _split_to_fixed_random_seed
The provided code snippet includes necessary dependencies for implementing the `set_fixed_random_state_for_dataset` function. Write a Python function `def set_fixed_random_state_for_dataset(download_dir: str, dataset: str) -> None` to solve the following problem:
Set the fixed random state for entity_matching_scenario to ensure reproducibility. Unfortunately, the previous official HELM runs did not initialize the numpy random state to zero, so future runs must use the same random states in order to sample the same test instances to reproduce the official HELM runs.
Here is the function:
def set_fixed_random_state_for_dataset(download_dir: str, dataset: str) -> None:
"""Set the fixed random state for entity_matching_scenario to ensure reproducibility.
Unfortunately, the previous official HELM runs did not initialize
the numpy random state to zero, so future runs must use the same
random states in order to sample the same test instances to reproduce
the official HELM runs."""
random_state = get_split_to_fixed_random_seed(download_dir).get(dataset)
if random_state:
np.random.set_state(random_state)
else:
np.random.seed(0) | Set the fixed random state for entity_matching_scenario to ensure reproducibility. Unfortunately, the previous official HELM runs did not initialize the numpy random state to zero, so future runs must use the same random states in order to sample the same test instances to reproduce the official HELM runs. |
16,294 | import os
import json
from typing import Dict, List
from helm.common.general import ensure_file_downloaded
def get_path_to_pinned_file_order(download_dir: str):
"""Lazily download and return a dict of path to pinned file order."""
global _path_to_pinned_file_order
if not _path_to_pinned_file_order:
file_path: str = os.path.join(download_dir, _PINNED_FILE_ORDER_FILENAME)
ensure_file_downloaded(
source_url=_PINNED_FILE_ORDER_URL,
target_path=file_path,
unpack=False,
)
with open(file_path) as f:
_path_to_pinned_file_order = json.load(f)
return _path_to_pinned_file_order
The provided code snippet includes necessary dependencies for implementing the `listdir_with_pinned_file_order` function. Write a Python function `def listdir_with_pinned_file_order(download_dir: str, corpus_path: str) -> List[str]` to solve the following problem:
List files for the path in a pinned order for ICE to ensure reproducibility. Unfortunately, the previous official HELM runs used the arbitrary file order produced by os.listdir() and did not sort the files, so future runs must use the same file order in order to sample the same instances to reproduce the official HELM runs.
Here is the function:
def listdir_with_pinned_file_order(download_dir: str, corpus_path: str) -> List[str]:
"""List files for the path in a pinned order for ICE to ensure reproducibility.
Unfortunately, the previous official HELM runs used the arbitrary file order
produced by os.listdir() and did not sort the files, so future runs must use
the same file order in order to sample the same instances to reproduce
the official HELM runs."""
pinned_file_order = get_path_to_pinned_file_order(download_dir).get(corpus_path)
if pinned_file_order:
return pinned_file_order
return list(sorted(os.listdir(corpus_path))) | List files for the path in a pinned order for ICE to ensure reproducibility. Unfortunately, the previous official HELM runs used the arbitrary file order produced by os.listdir() and did not sort the files, so future runs must use the same file order in order to sample the same instances to reproduce the official HELM runs. |
16,295 | from abc import ABC, abstractmethod
from dataclasses import dataclass, field, replace
from typing import List, Optional, Tuple
import os
from pathlib import PurePath
import inspect
from helm.common.media_object import MultimediaObject
from helm.common.object_spec import ObjectSpec, create_object
from helm.common.general import ensure_directory_exists, format_text, format_split, format_tags, indent_lines
from helm.benchmark.augmentations.perturbation_description import PerturbationDescription
The provided code snippet includes necessary dependencies for implementing the `make_relevance_tag` function. Write a Python function `def make_relevance_tag(relevance: int) -> str` to solve the following problem:
Make a relevance tag. Relevance value is an integer bigger than or equal to 0.
Here is the function:
def make_relevance_tag(relevance: int) -> str:
"""Make a relevance tag.
Relevance value is an integer bigger than or equal to 0.
"""
return f"relevance={relevance}" | Make a relevance tag. Relevance value is an integer bigger than or equal to 0. |
16,296 | from abc import ABC, abstractmethod
from dataclasses import dataclass, field, replace
from typing import List, Optional, Tuple
import os
from pathlib import PurePath
import inspect
from helm.common.media_object import MultimediaObject
from helm.common.object_spec import ObjectSpec, create_object
from helm.common.general import ensure_directory_exists, format_text, format_split, format_tags, indent_lines
from helm.benchmark.augmentations.perturbation_description import PerturbationDescription
The provided code snippet includes necessary dependencies for implementing the `make_rank_tag` function. Write a Python function `def make_rank_tag(rank: int) -> str` to solve the following problem:
Make a rank tag. Rank value is an integer bigger than or equal to 1.
Here is the function:
def make_rank_tag(rank: int) -> str:
"""Make a rank tag.
Rank value is an integer bigger than or equal to 1.
"""
return f"rank={rank}" | Make a rank tag. Rank value is an integer bigger than or equal to 1. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.