language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/ovis2/modular_ovis2.py | {
"start": 4861,
"end": 5345
} | class ____(PreTrainedModel):
config: Ovis2Config
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Ovis2VisionAttention"]
_skip_keys_device_placement = "past_key_values"
_supports_cache_class = True
_supports_flash_attn = True
_supports_flex_attn = True
_supports_sdpa = True
_can_compile_fullgraph = True
_supports_attention_backend = True
| Ovis2PreTrainedModel |
python | dask__distributed | distributed/spans.py | {
"start": 22426,
"end": 23767
} | class ____:
"""Worker extension for spans support"""
worker: Worker
digests_total_since_heartbeat: dict[tuple[Hashable, ...], float]
def __init__(self, worker: Worker):
self.worker = worker
self.digests_total_since_heartbeat = {}
def collect_digests(
self, digests_total_since_heartbeat: Mapping[Hashable, float]
) -> None:
# Note: this method may be called spuriously by Worker._register_with_scheduler,
# but when it does it's guaranteed not to find any metrics
assert not self.digests_total_since_heartbeat
self.digests_total_since_heartbeat = {
k: v
for k, v in digests_total_since_heartbeat.items()
if isinstance(k, tuple) and k[0] in CONTEXTS_WITH_SPAN_ID
}
def heartbeat(self) -> dict[tuple[Hashable, ...], float]:
"""Apportion the metrics that do have a span to the Spans on the scheduler
Returns
-------
``{(context, span_id, prefix, activity, unit): value}}``
See Also
--------
SpansSchedulerExtension.heartbeat
Span.cumulative_worker_metrics
distributed.worker.Worker.get_metrics
"""
out = self.digests_total_since_heartbeat
self.digests_total_since_heartbeat = {}
return out
| SpansWorkerExtension |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py | {
"start": 129,
"end": 1115
} | class ____(ValidationRule):
def enter_Field(self, node, key, parent, path, ancestors):
type = self.context.get_type()
if not type:
return
if is_leaf_type(get_named_type(type)):
if node.selection_set:
self.context.report_error(GraphQLError(
self.no_subselection_allowed_message(node.name.value, type),
[node.selection_set]
))
elif not node.selection_set:
self.context.report_error(GraphQLError(
self.required_subselection_message(node.name.value, type),
[node]
))
@staticmethod
def no_subselection_allowed_message(field, type):
return 'Field "{}" of type "{}" must not have a sub selection.'.format(field, type)
@staticmethod
def required_subselection_message(field, type):
return 'Field "{}" of type "{}" must have a sub selection.'.format(field, type)
| ScalarLeafs |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 364451,
"end": 370577
} | class ____:
r""" Test the non-parametric quantile test,
including the computation of confidence intervals
"""
def test_quantile_test_iv(self):
x = [1, 2, 3]
message = "`x` must be a one-dimensional array of numbers."
with pytest.raises(ValueError, match=message):
stats.quantile_test([x])
message = "`q` must be a scalar."
with pytest.raises(ValueError, match=message):
stats.quantile_test(x, q=[1, 2])
message = "`p` must be a float strictly between 0 and 1."
with pytest.raises(ValueError, match=message):
stats.quantile_test(x, p=[0.5, 0.75])
with pytest.raises(ValueError, match=message):
stats.quantile_test(x, p=2)
with pytest.raises(ValueError, match=message):
stats.quantile_test(x, p=-0.5)
message = "`alternative` must be one of..."
with pytest.raises(ValueError, match=message):
stats.quantile_test(x, alternative='one-sided')
message = "`confidence_level` must be a number between 0 and 1."
with pytest.raises(ValueError, match=message):
stats.quantile_test(x).confidence_interval(1)
@pytest.mark.parametrize(
'p, alpha, lb, ub, alternative',
[[0.3, 0.95, 1.221402758160170, 1.476980793882643, 'two-sided'],
[0.5, 0.9, 1.506817785112854, 1.803988415397857, 'two-sided'],
[0.25, 0.95, -np.inf, 1.39096812846378, 'less'],
[0.8, 0.9, 2.117000016612675, np.inf, 'greater']]
)
def test_R_ci_quantile(self, p, alpha, lb, ub, alternative):
# Test against R library `confintr` function `ci_quantile`, e.g.
# library(confintr)
# options(digits=16)
# x <- exp(seq(0, 1, by = 0.01))
# ci_quantile(x, q = 0.3)$interval
# ci_quantile(x, q = 0.5, probs = c(0.05, 0.95))$interval
# ci_quantile(x, q = 0.25, probs = c(0, 0.95))$interval
# ci_quantile(x, q = 0.8, probs = c(0.1, 1))$interval
x = np.exp(np.arange(0, 1.01, 0.01))
res = stats.quantile_test(x, p=p, alternative=alternative)
assert_allclose(res.confidence_interval(alpha), [lb, ub], rtol=1e-15)
@pytest.mark.parametrize(
'q, p, alternative, ref',
[[1.2, 0.3, 'two-sided', 0.01515567517648],
[1.8, 0.5, 'two-sided', 0.1109183496606]]
)
def test_R_pvalue(self, q, p, alternative, ref):
# Test against R library `snpar` function `quant.test`, e.g.
# library(snpar)
# options(digits=16)
# x < - exp(seq(0, 1, by=0.01))
# quant.test(x, q=1.2, p=0.3, exact=TRUE, alternative='t')
x = np.exp(np.arange(0, 1.01, 0.01))
res = stats.quantile_test(x, q=q, p=p, alternative=alternative)
assert_allclose(res.pvalue, ref, rtol=1e-12)
@pytest.mark.parametrize('case', ['continuous', 'discrete'])
@pytest.mark.parametrize('alternative', ['less', 'greater'])
@pytest.mark.parametrize('alpha', [0.9, 0.95])
def test_pval_ci_match(self, case, alternative, alpha):
# Verify that the following statement holds:
# The 95% confidence interval corresponding with alternative='less'
# has -inf as its lower bound, and the upper bound `xu` is the greatest
# element from the sample `x` such that:
# `stats.quantile_test(x, q=xu, p=p, alternative='less').pvalue``
# will be greater than 5%.
# And the corresponding statement for the alternative='greater' case.
seed = int((7**len(case) + len(alternative))*alpha)
rng = np.random.default_rng(seed)
if case == 'continuous':
p, q = rng.random(size=2)
rvs = rng.random(size=100)
else:
rvs = rng.integers(1, 11, size=100)
p = rng.random()
q = rng.integers(1, 11)
res = stats.quantile_test(rvs, q=q, p=p, alternative=alternative)
ci = res.confidence_interval(confidence_level=alpha)
# select elements inside the confidence interval based on alternative
if alternative == 'less':
i_inside = rvs <= ci.high
else:
i_inside = rvs >= ci.low
for x in rvs[i_inside]:
res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative)
assert res.pvalue > 1 - alpha
for x in rvs[~i_inside]:
res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative)
assert res.pvalue < 1 - alpha
def test_match_conover_examples(self):
# Test against the examples in [1] (Conover Practical Nonparametric
# Statistics Third Edition) pg 139
# Example 1
# Data is [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193,
# 174, 166, 248]
# Two-sided test of whether the upper quartile (p=0.75) equals 193
# (q=193). Conover shows that 7 of the observations are less than or
# equal to 193, and "for the binomial random variable Y, P(Y<=7) =
# 0.0173", so the two-sided p-value is twice that, 0.0346.
x = [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193,
174, 166, 248]
pvalue_expected = 0.0346
res = stats.quantile_test(x, q=193, p=0.75, alternative='two-sided')
assert_allclose(res.pvalue, pvalue_expected, rtol=1e-5)
# Example 2
# Conover doesn't give explicit data, just that 8 out of 112
# observations are 60 or less. The test is whether the median time is
# equal to 60 against the alternative that the median is greater than
# 60. The p-value is calculated as P(Y<=8), where Y is again a binomial
# distributed random variable, now with p=0.5 and n=112. Conover uses a
# normal approximation, but we can easily calculate the CDF of the
# binomial distribution.
x = [59]*8 + [61]*(112-8)
pvalue_expected = stats.binom(p=0.5, n=112).pmf(k=8)
res = stats.quantile_test(x, q=60, p=0.5, alternative='greater')
assert_allclose(res.pvalue, pvalue_expected, atol=1e-10)
| TestQuantileTest |
python | numpy__numpy | numpy/_core/records.py | {
"start": 1356,
"end": 6284
} | class ____:
"""
Class to convert formats, names, titles description to a dtype.
After constructing the format_parser object, the dtype attribute is
the converted data-type:
``dtype = format_parser(formats, names, titles).dtype``
Attributes
----------
dtype : dtype
The converted data-type.
Parameters
----------
formats : str or list of str
The format description, either specified as a string with
comma-separated format descriptions in the form ``'f8, i4, S5'``, or
a list of format description strings in the form
``['f8', 'i4', 'S5']``.
names : str or list/tuple of str
The field names, either specified as a comma-separated string in the
form ``'col1, col2, col3'``, or as a list or tuple of strings in the
form ``['col1', 'col2', 'col3']``.
An empty list can be used, in that case default field names
('f0', 'f1', ...) are used.
titles : sequence
Sequence of title strings. An empty list can be used to leave titles
out.
aligned : bool, optional
If True, align the fields by padding as the C-compiler would.
Default is False.
byteorder : str, optional
If specified, all the fields will be changed to the
provided byte-order. Otherwise, the default byte-order is
used. For all available string specifiers, see `dtype.newbyteorder`.
See Also
--------
numpy.dtype, numpy.typename
Examples
--------
>>> import numpy as np
>>> np.rec.format_parser(['<f8', '<i4'], ['col1', 'col2'],
... ['T1', 'T2']).dtype
dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4')])
`names` and/or `titles` can be empty lists. If `titles` is an empty list,
titles will simply not appear. If `names` is empty, default field names
will be used.
>>> np.rec.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
... []).dtype
dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')])
>>> np.rec.format_parser(['<f8', '<i4', '<a5'], [], []).dtype
dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')])
"""
def __init__(self, formats, names, titles, aligned=False, byteorder=None):
self._parseFormats(formats, aligned)
self._setfieldnames(names, titles)
self._createdtype(byteorder)
def _parseFormats(self, formats, aligned=False):
""" Parse the field formats """
if formats is None:
raise ValueError("Need formats argument")
if isinstance(formats, list):
dtype = sb.dtype(
[
(f'f{i}', format_)
for i, format_ in enumerate(formats)
],
aligned,
)
else:
dtype = sb.dtype(formats, aligned)
fields = dtype.fields
if fields is None:
dtype = sb.dtype([('f1', dtype)], aligned)
fields = dtype.fields
keys = dtype.names
self._f_formats = [fields[key][0] for key in keys]
self._offsets = [fields[key][1] for key in keys]
self._nfields = len(keys)
def _setfieldnames(self, names, titles):
"""convert input field names into a list and assign to the _names
attribute """
if names:
if type(names) in [list, tuple]:
pass
elif isinstance(names, str):
names = names.split(',')
else:
raise NameError(f"illegal input names {repr(names)}")
self._names = [n.strip() for n in names[:self._nfields]]
else:
self._names = []
# if the names are not specified, they will be assigned as
# "f0, f1, f2,..."
# if not enough names are specified, they will be assigned as "f[n],
# f[n+1],..." etc. where n is the number of specified names..."
self._names += ['f%d' % i for i in range(len(self._names),
self._nfields)]
# check for redundant names
_dup = find_duplicate(self._names)
if _dup:
raise ValueError(f"Duplicate field names: {_dup}")
if titles:
self._titles = [n.strip() for n in titles[:self._nfields]]
else:
self._titles = []
titles = []
if self._nfields > len(titles):
self._titles += [None] * (self._nfields - len(titles))
def _createdtype(self, byteorder):
dtype = sb.dtype({
'names': self._names,
'formats': self._f_formats,
'offsets': self._offsets,
'titles': self._titles,
})
if byteorder is not None:
byteorder = _byteorderconv[byteorder[0]]
dtype = dtype.newbyteorder(byteorder)
self.dtype = dtype
| format_parser |
python | kamyu104__LeetCode-Solutions | Python/parsing-a-boolean-expression.py | {
"start": 29,
"end": 834
} | class ____(object):
def parseBoolExpr(self, expression):
"""
:type expression: str
:rtype: bool
"""
def parse(expression, i):
if expression[i[0]] not in "&|!":
result = expression[i[0]] == 't'
i[0] += 1
return result
op = expression[i[0]]
i[0] += 2
stk = []
while expression[i[0]] != ')':
if expression[i[0]] == ',':
i[0] += 1
continue
stk.append(parse(expression, i))
i[0] += 1
if op == '&':
return all(stk)
if op == '|':
return any(stk)
return not stk[0]
return parse(expression, [0])
| Solution |
python | readthedocs__readthedocs.org | readthedocs/integrations/migrations/0008_add_new_jsonfields.py | {
"start": 149,
"end": 956
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("integrations", "0007_update-provider-data"),
]
operations = [
migrations.AddField(
model_name="httpexchange",
name="request_headers_json",
field=models.JSONField(null=True, blank=True, verbose_name="Request headers"),
),
migrations.AddField(
model_name="httpexchange",
name="response_headers_json",
field=models.JSONField(null=True, blank=True, verbose_name="Request headers"),
),
migrations.AddField(
model_name="integration",
name="provider_data_json",
field=models.JSONField(null=True, blank=True, verbose_name="Provider data"),
),
]
| Migration |
python | keon__algorithms | tests/test_graph.py | {
"start": 8587,
"end": 9176
} | class ____(unittest.TestCase):
def test_prim_spanning(self):
graph1 = {
1: [[3, 2], [8, 3]],
2: [[3, 1], [5, 4]],
3: [[8, 1], [2, 4], [4, 5]],
4: [[5, 2], [2, 3], [6, 5]],
5: [[4, 3], [6, 4]]
}
self.assertEqual(14, prims_minimum_spanning(graph1))
graph2 = {
1: [[7, 2], [6, 4]],
2: [[7, 1], [9, 4], [6, 3]],
3: [[8, 4], [6, 2]],
4: [[6, 1], [9, 2], [8, 3]]
}
self.assertEqual(19, prims_minimum_spanning(graph2))
| PrimsMinimumSpanning |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 27304,
"end": 32780
} | class ____(nn.Module):
"""
Cross-Attention used in Conditional DETR 'Conditional DETR for Fast Training Convergence' paper.
The key q_proj, k_proj, v_proj are defined outside the attention. This attention allows the dim of q, k to be
different to v.
"""
def __init__(
self,
embed_dim: int,
out_dim: int,
num_heads: int,
dropout: float = 0.0,
bias: bool = True,
):
super().__init__()
self.embed_dim = embed_dim
self.out_dim = out_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if self.head_dim * num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {num_heads})."
)
# head dimension of values
self.v_head_dim = out_dim // num_heads
if self.v_head_dim * num_heads != self.out_dim:
raise ValueError(
f"out_dim must be divisible by num_heads (got `out_dim`: {self.out_dim} and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.out_proj = nn.Linear(out_dim, out_dim, bias=bias)
def _qk_shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def _v_shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
return tensor.view(batch_size, seq_len, self.num_heads, self.v_head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
key_states: Optional[torch.Tensor] = None,
value_states: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
batch_size, target_len, _ = hidden_states.size()
# get query proj
query_states = hidden_states * self.scaling
# get key, value proj
key_states = self._qk_shape(key_states, -1, batch_size)
value_states = self._v_shape(value_states, -1, batch_size)
proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
v_proj_shape = (batch_size * self.num_heads, -1, self.v_head_dim)
query_states = self._qk_shape(query_states, target_len, batch_size).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*v_proj_shape)
source_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
raise ValueError(
f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (batch_size, 1, target_len, source_len):
raise ValueError(
f"Attention mask should be of size {(batch_size, 1, target_len, source_len)}, but is"
f" {attention_mask.size()}"
)
if attention_mask.dtype == torch.bool:
attention_mask = torch.zeros_like(attention_mask, dtype=attn_weights.dtype).masked_fill_(
attention_mask, -torch.inf
)
attn_weights = attn_weights.view(batch_size, self.num_heads, target_len, source_len) + attention_mask
attn_weights = attn_weights.view(batch_size * self.num_heads, target_len, source_len)
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
else:
attn_weights_reshaped = None
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.bmm(attn_probs, value_states)
if attn_output.size() != (batch_size * self.num_heads, target_len, self.v_head_dim):
raise ValueError(
f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.v_head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.v_head_dim)
attn_output = attn_output.transpose(1, 2)
attn_output = attn_output.reshape(batch_size, target_len, self.out_dim)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights_reshaped
# Copied from transformers.models.detr.modeling_detr.DetrEncoderLayer with DetrEncoderLayer->ConditionalDetrEncoderLayer,DetrConfig->ConditionalDetrConfig
| ConditionalDetrAttention |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/kernel_mixins.py | {
"start": 315,
"end": 430
} | class ____(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
_timer = None
| QtKernelRestarterMixin |
python | google__pytype | pytype/tools/annotate_ast/annotate_ast.py | {
"start": 2299,
"end": 2454
} | class ____(Exception):
"""Wrap exceptions raised by Pytype."""
def _annotation_str_from_type_def(type_def):
return pytd_utils.Print(type_def)
| PytypeError |
python | run-llama__llama_index | llama-index-core/tests/agent/workflow/test_single_agent_workflow.py | {
"start": 534,
"end": 7220
} | class ____(MockLLM):
def __init__(self, responses: List[ChatMessage]):
super().__init__()
self._responses = responses
self._response_index = 0
@property
def metadata(self) -> LLMMetadata:
return LLMMetadata(is_function_calling_model=True)
async def astream_chat(
self, messages: List[ChatMessage], **kwargs: Any
) -> ChatResponseAsyncGen:
response_msg = None
if self._responses:
response_msg = self._responses[self._response_index]
self._response_index = (self._response_index + 1) % len(self._responses)
async def _gen():
if response_msg:
yield ChatResponse(
message=response_msg,
delta=response_msg.content,
raw={"content": response_msg.content},
)
return _gen()
async def astream_chat_with_tools(
self, tools: List[Any], chat_history: List[ChatMessage], **kwargs: Any
) -> ChatResponseAsyncGen:
response_msg = None
if self._responses:
response_msg = self._responses[self._response_index]
self._response_index = (self._response_index + 1) % len(self._responses)
async def _gen():
if response_msg:
yield ChatResponse(
message=response_msg,
delta=response_msg.content,
raw={"content": response_msg.content},
)
return _gen()
def get_tool_calls_from_response(
self, response: ChatResponse, **kwargs: Any
) -> List[ToolSelection]:
return response.message.additional_kwargs.get("tool_calls", [])
@pytest.fixture()
def function_agent():
return FunctionAgent(
name="retriever",
description="Manages data retrieval",
system_prompt="You are a retrieval assistant.",
llm=MockLLM(
responses=[
ChatMessage(
role=MessageRole.ASSISTANT, content="Success with the FunctionAgent"
)
],
),
)
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
def subtract(a: int, b: int) -> int:
"""Subtract two numbers."""
return a - b
@pytest.fixture()
def calculator_agent():
return ReActAgent(
name="calculator",
description="Performs basic arithmetic operations",
system_prompt="You are a calculator assistant.",
tools=[
FunctionTool.from_defaults(fn=add),
FunctionTool.from_defaults(fn=subtract),
],
llm=MockLLM(
responses=[
ChatMessage(
role=MessageRole.ASSISTANT,
content='Thought: I need to add these numbers\nAction: add\nAction Input: {"a": 5, "b": 3}\n',
),
ChatMessage(
role=MessageRole.ASSISTANT,
content=r"Thought: The result is 8\Answer: The sum is 8",
),
]
),
)
@pytest.fixture()
def retry_calculator_agent():
return ReActAgent(
name="calculator",
description="Performs basic arithmetic operations",
system_prompt="You are a calculator assistant.",
tools=[
FunctionTool.from_defaults(fn=add),
FunctionTool.from_defaults(fn=subtract),
],
llm=MockLLM(
responses=[
ChatMessage(
role=MessageRole.ASSISTANT,
content='Thought: I need to add these numbers\nAction: add\n{"a": 5 "b": 3}\n',
),
ChatMessage(
role=MessageRole.ASSISTANT,
content='Thought: I need to add these numbers\nAction: add\nAction Input: {"a": 5, "b": 3}\n',
),
ChatMessage(
role=MessageRole.ASSISTANT,
content=r"Thought: The result is 8\nAnswer: The sum is 8",
),
]
),
)
@pytest.mark.asyncio
async def test_single_function_agent(function_agent):
"""Test single agent with state management."""
handler = function_agent.run(user_msg="test")
async for _ in handler.stream_events():
pass
response = await handler
assert "Success with the FunctionAgent" in str(response.response)
@pytest.mark.asyncio
async def test_single_react_agent(calculator_agent):
"""Verify execution of basic ReAct single agent."""
memory = ChatMemoryBuffer.from_defaults()
handler = calculator_agent.run(user_msg="Can you add 5 and 3?", memory=memory)
events = []
async for event in handler.stream_events():
events.append(event)
response = await handler
assert "8" in str(response.response)
@pytest.mark.asyncio
async def test_single_react_agent_retry(retry_calculator_agent):
"""Verify execution of basic ReAct single agent with retry due to a output parsing error."""
memory = ChatMemoryBuffer.from_defaults()
handler = retry_calculator_agent.run(user_msg="Can you add 5 and 3?", memory=memory)
events = []
contains_error_message = False
async for event in handler.stream_events():
events.append(event)
if isinstance(event, AgentInput):
if "Error while parsing the output" in event.input[-1].content:
contains_error_message = True
assert contains_error_message
response = await handler
assert "8" in str(response.response)
@pytest.mark.asyncio
async def test_max_iterations():
"""Test max iterations."""
def random_tool() -> str:
return "random"
agent = FunctionAgent(
name="agent",
description="test",
tools=[random_tool],
llm=MockLLM(
responses=[
ChatMessage(
role=MessageRole.ASSISTANT,
content="handing off",
additional_kwargs={
"tool_calls": [
ToolSelection(
tool_id="one",
tool_name="random_tool",
tool_kwargs={},
)
]
},
),
]
* 100
),
)
# Default max iterations is 20
with pytest.raises(WorkflowRuntimeError, match="Either something went wrong"):
_ = await agent.run(user_msg="test")
# Set max iterations to 101 to avoid error
_ = agent.run(user_msg="test", max_iterations=101)
| MockLLM |
python | encode__django-rest-framework | rest_framework/relations.py | {
"start": 9356,
"end": 15146
} | class ____(RelatedField):
lookup_field = 'pk'
view_name = None
default_error_messages = {
'required': _('This field is required.'),
'no_match': _('Invalid hyperlink - No URL match.'),
'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'),
'does_not_exist': _('Invalid hyperlink - Object does not exist.'),
'incorrect_type': _('Incorrect type. Expected URL string, received {data_type}.'),
}
def __init__(self, view_name=None, **kwargs):
if view_name is not None:
self.view_name = view_name
assert self.view_name is not None, 'The `view_name` argument is required.'
self.lookup_field = kwargs.pop('lookup_field', self.lookup_field)
self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field)
self.format = kwargs.pop('format', None)
# We include this simply for dependency injection in tests.
# We can't add it as a class attributes or it would expect an
# implicit `self` argument to be passed.
self.reverse = reverse
super().__init__(**kwargs)
def use_pk_only_optimization(self):
return self.lookup_field == 'pk'
def get_object(self, view_name, view_args, view_kwargs):
"""
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
"""
lookup_value = view_kwargs[self.lookup_url_kwarg]
lookup_kwargs = {self.lookup_field: lookup_value}
queryset = self.get_queryset()
try:
return queryset.get(**lookup_kwargs)
except ValueError:
exc = ObjectValueError(str(sys.exc_info()[1]))
raise exc.with_traceback(sys.exc_info()[2])
except TypeError:
exc = ObjectTypeError(str(sys.exc_info()[1]))
raise exc.with_traceback(sys.exc_info()[2])
def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Unsaved objects will not yet have a valid URL.
if hasattr(obj, 'pk') and obj.pk in (None, ''):
return None
lookup_value = getattr(obj, self.lookup_field)
kwargs = {self.lookup_url_kwarg: lookup_value}
return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
def to_internal_value(self, data):
request = self.context.get('request')
try:
http_prefix = data.startswith(('http:', 'https:'))
except AttributeError:
self.fail('incorrect_type', data_type=type(data).__name__)
if http_prefix:
# If needed convert absolute URLs to relative path
data = parse.urlparse(data).path
prefix = get_script_prefix()
if data.startswith(prefix):
data = '/' + data[len(prefix):]
data = uri_to_iri(parse.unquote(data))
try:
match = resolve(data)
except Resolver404:
self.fail('no_match')
try:
expected_viewname = request.versioning_scheme.get_versioned_viewname(
self.view_name, request
)
except AttributeError:
expected_viewname = self.view_name
if match.view_name != expected_viewname:
self.fail('incorrect_match')
try:
return self.get_object(match.view_name, match.args, match.kwargs)
except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
self.fail('does_not_exist')
def to_representation(self, value):
assert 'request' in self.context, (
"`%s` requires the request in the serializer"
" context. Add `context={'request': request}` when instantiating "
"the serializer." % self.__class__.__name__
)
request = self.context['request']
format = self.context.get('format')
# By default use whatever format is given for the current context
# unless the target is a different type to the source.
#
# Eg. Consider a HyperlinkedIdentityField pointing from a json
# representation to an html property of that representation...
#
# '/snippets/1/' should link to '/snippets/1/highlight/'
# ...but...
# '/snippets/1/.json' should link to '/snippets/1/highlight/.html'
if format and self.format and self.format != format:
format = self.format
# Return the hyperlink, or error if incorrectly configured.
try:
url = self.get_url(value, self.view_name, request, format)
except NoReverseMatch:
msg = (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s". You may have failed to include the related '
'model in your API, or incorrectly configured the '
'`lookup_field` attribute on this field.'
)
if value in ('', None):
value_string = {'': 'the empty string', None: 'None'}[value]
msg += (
" WARNING: The value of the field on the model instance "
"was %s, which may be why it didn't match any "
"entries in your URL conf." % value_string
)
raise ImproperlyConfigured(msg % self.view_name)
if url is None:
return None
return Hyperlink(url, value)
| HyperlinkedRelatedField |
python | aimacode__aima-python | agents.py | {
"start": 24465,
"end": 24755
} | class ____(Obstacle):
def __init__(self, coordinates):
"""Coordinates is a list of tuples."""
super().__init__()
self.coordinates = coordinates
# ______________________________________________________________________________
# Vacuum environment
| PolygonObstacle |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 79093,
"end": 82210
} | class ____(Response):
"""
Response of dataviews.delete_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "dataviews"
_action = "delete_many"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"deleted": {
"description": "Indicates whether the dataview was deleted",
"type": "boolean",
},
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, succeeded=None, failed=None, **kwargs):
super(DeleteManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self):
return self._property_succeeded
@succeeded.setter
def succeeded(self, value):
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self):
return self._property_failed
@failed.setter
def failed(self, value):
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
| DeleteManyResponse |
python | huggingface__transformers | src/transformers/models/splinter/modeling_splinter.py | {
"start": 11300,
"end": 12919
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([SplinterLayer(config) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
@can_return_tuple
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = False,
output_hidden_states: Optional[bool] = False,
return_dict: Optional[bool] = True,
**kwargs,
) -> Union[tuple[torch.Tensor], BaseModelOutput]:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
**kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
return BaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
@auto_docstring
| SplinterEncoder |
python | mahmoud__boltons | boltons/iterutils.py | {
"start": 51608,
"end": 57558
} | class ____(GUIDerator):
"""Much like the standard GUIDerator, the SequentialGUIDerator is an
iterator that yields a globally-unique identifier (GUID) on every
iteration. The GUIDs produced are hexadecimal strings.
The SequentialGUIDerator differs in that it picks a starting GUID
value and increments every iteration. This yields GUIDs which are
of course unique, but also ordered and lexicographically sortable.
The SequentialGUIDerator is around 50% faster than the normal
GUIDerator, making it almost 20x as fast as the built-in uuid
module. By default it is also more compact, partly due to its
96-bit (24-hexdigit) default length. 96 bits of randomness means that
there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64
iterations. If more or less uniqueness is desired, the *size*
argument can be adjusted accordingly.
Args:
size (int): character length of the GUID, defaults to 24.
Note that with SequentialGUIDerator there is a chance of GUIDs
growing larger than the size configured. The SequentialGUIDerator
has built-in fork protection that causes it to detect a fork on
next iteration and reseed accordingly.
"""
def reseed(self):
super().reseed()
start_str = self._sha1(self.salt.encode('utf8')).hexdigest()
self.start = int(start_str[:self.size], 16)
self.start |= (1 << ((self.size * 4) - 2))
def __next__(self):
if os.getpid() != self.pid:
self.reseed()
return '%x' % (next(self.count) + self.start)
next = __next__
guid_iter = GUIDerator()
seq_guid_iter = SequentialGUIDerator()
def soft_sorted(iterable, first=None, last=None, key=None, reverse=False):
"""For when you care about the order of some elements, but not about
others.
Use this to float to the top and/or sink to the bottom a specific
ordering, while sorting the rest of the elements according to
normal :func:`sorted` rules.
>>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two'])
['one', 'two', 'a', 'b']
>>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True)
[6, 5, 3, 1, 0, 2, 4]
>>> import string
>>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower))
'aA1023456789cCdDeEfFbB'
Args:
iterable (list): A list or other iterable to sort.
first (list): A sequence to enforce for elements which should
appear at the beginning of the returned list.
last (list): A sequence to enforce for elements which should
appear at the end of the returned list.
key (callable): Callable used to generate a comparable key for
each item to be sorted, same as the key in
:func:`sorted`. Note that entries in *first* and *last*
should be the keys for the items. Defaults to
passthrough/the identity function.
reverse (bool): Whether or not elements not explicitly ordered
by *first* and *last* should be in reverse order or not.
Returns a new list in sorted order.
"""
first = first or []
last = last or []
key = key or (lambda x: x)
seq = list(iterable)
other = [x for x in seq if not (
(first and key(x) in first) or (last and key(x) in last))]
other.sort(key=key, reverse=reverse)
if first:
first = sorted([x for x in seq if key(x) in first],
key=lambda x: first.index(key(x)))
if last:
last = sorted([x for x in seq if key(x) in last],
key=lambda x: last.index(key(x)))
return first + other + last
def untyped_sorted(iterable, key=None, reverse=False):
"""A version of :func:`sorted` which will happily sort an iterable of
heterogeneous types and return a new list, similar to legacy Python's
behavior.
>>> untyped_sorted(['abc', 2.0, 1, 2, 'def'])
[1, 2.0, 2, 'abc', 'def']
Note how mutually orderable types are sorted as expected, as in
the case of the integers and floats above.
.. note::
Results may vary across Python versions and builds, but the
function will produce a sorted list, except in the case of
explicitly unorderable objects.
"""
class _Wrapper:
slots = ('obj',)
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
obj = key(self.obj) if key is not None else self.obj
other = key(other.obj) if key is not None else other.obj
try:
ret = obj < other
except TypeError:
ret = ((type(obj).__name__, id(type(obj)), obj)
< (type(other).__name__, id(type(other)), other))
return ret
if key is not None and not callable(key):
raise TypeError('expected function or callable object for key, not: %r'
% key)
return sorted(iterable, key=_Wrapper, reverse=reverse)
"""
May actually be faster to do an isinstance check for a str path
$ python -m timeit -s "x = [1]" "x[0]"
10000000 loops, best of 3: 0.0207 usec per loop
$ python -m timeit -s "x = [1]" "try: x[0] \nexcept: pass"
10000000 loops, best of 3: 0.029 usec per loop
$ python -m timeit -s "x = [1]" "try: x[1] \nexcept: pass"
1000000 loops, best of 3: 0.315 usec per loop
# setting up try/except is fast, only around 0.01us
# actually triggering the exception takes almost 10x as long
$ python -m timeit -s "x = [1]" "isinstance(x, basestring)"
10000000 loops, best of 3: 0.141 usec per loop
$ python -m timeit -s "x = [1]" "isinstance(x, str)"
10000000 loops, best of 3: 0.131 usec per loop
$ python -m timeit -s "x = [1]" "try: x.split('.')\n except: pass"
1000000 loops, best of 3: 0.443 usec per loop
$ python -m timeit -s "x = [1]" "try: x.split('.') \nexcept AttributeError: pass"
1000000 loops, best of 3: 0.544 usec per loop
"""
| SequentialGUIDerator |
python | django__django | tests/db_functions/models.py | {
"start": 345,
"end": 796
} | class ____(models.Model):
authors = models.ManyToManyField(Author, related_name="articles")
title = models.CharField(max_length=50)
summary = models.CharField(max_length=200, null=True, blank=True)
text = models.TextField()
written = models.DateTimeField()
published = models.DateTimeField(null=True, blank=True)
updated = models.DateTimeField(null=True, blank=True)
views = models.PositiveIntegerField(default=0)
| Article |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/mwaa.py | {
"start": 4753,
"end": 9407
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when an MWAA Task is complete.
:param external_env_name: The external MWAA environment name that contains the Task Instance you want to wait for
(templated)
:param external_dag_id: The DAG ID in the external MWAA environment that contains the Task Instance you want to wait for
(templated)
:param external_dag_run_id: The DAG Run ID in the external MWAA environment that you want to wait for (templated).
If not provided, the latest DAG run is used by default.
:param external_task_id: The Task ID in the external MWAA environment that you want to wait for (templated)
:param success_states: Collection of task instance states that would make this task marked as successful, default is
``{airflow.utils.state.TaskInstanceState.SUCCESS}`` (templated)
:param failure_states: Collection of task instance states that would make this task marked as failed and raise an
AirflowException, default is ``{airflow.utils.state.TaskInstanceState.FAILED}`` (templated)
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 60)
:param waiter_max_attempts: The maximum number of attempts to be made. (default: 720)
:param aws_conn_id: The Airflow connection used for AWS credentials.
"""
def __init__(
self,
*args,
external_env_name: str,
external_dag_id: str,
external_dag_run_id: str | None = None,
external_task_id: str,
success_states: Collection[str] | None = None,
failure_states: Collection[str] | None = None,
waiter_delay: int = 60,
waiter_max_attempts: int = 720,
**kwargs,
) -> None:
self.success_states = (
set(success_states) if success_states else {state.value for state in State.success_states}
)
self.failure_states = (
set(failure_states) if failure_states else {state.value for state in State.failed_states}
)
if len(self.success_states & self.failure_states):
raise ValueError("success_states and failure_states must not have any values in common")
in_progress_states = {s.value for s in TaskInstanceState} - self.success_states - self.failure_states
super().__init__(
serialized_fields={
"external_env_name": external_env_name,
"external_dag_id": external_dag_id,
"external_dag_run_id": external_dag_run_id,
"external_task_id": external_task_id,
"success_states": success_states,
"failure_states": failure_states,
},
waiter_name="mwaa_task_complete",
waiter_args={
"Name": external_env_name,
"Path": f"/dags/{external_dag_id}/dagRuns/{external_dag_run_id}/taskInstances/{external_task_id}",
"Method": "GET",
},
failure_message=f"The task {external_task_id} of DAG run {external_dag_run_id} of DAG {external_dag_id} in MWAA environment {external_env_name} failed with state",
status_message="State of DAG run",
status_queries=["RestApiResponse.state"],
return_key="task_id",
return_value=external_task_id,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
waiter_config_overrides={
"acceptors": _build_waiter_acceptors(
success_states=self.success_states,
failure_states=self.failure_states,
in_progress_states=in_progress_states,
)
},
**kwargs,
)
def hook(self) -> AwsGenericHook:
return MwaaHook(
aws_conn_id=self.aws_conn_id,
region_name=self.region_name,
verify=self.verify,
config=self.botocore_config,
)
def _build_waiter_acceptors(
success_states: set[str], failure_states: set[str], in_progress_states: set[str]
) -> list:
acceptors = []
for state_set, state_waiter_category in (
(success_states, "success"),
(failure_states, "failure"),
(in_progress_states, "retry"),
):
for dag_run_state in state_set:
acceptors.append(
{
"matcher": "path",
"argument": "RestApiResponse.state",
"expected": dag_run_state,
"state": state_waiter_category,
}
)
return acceptors
| MwaaTaskCompletedTrigger |
python | readthedocs__readthedocs.org | readthedocs/notifications/migrations/0004_remove_unused_notification.py | {
"start": 337,
"end": 575
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("notifications", "0003_notification_indexes"),
]
operations = [
migrations.RunPython(remove_unused_notification),
]
| Migration |
python | davidhalter__jedi | jedi/plugins/stdlib.py | {
"start": 8694,
"end": 11768
} | class ____(AttributeOverwrite):
def __init__(self, reversed_obj, iter_list):
super().__init__(reversed_obj)
self._iter_list = iter_list
def py__iter__(self, contextualized_node=None):
return self._iter_list
@publish_method('__next__')
def _next(self, arguments):
return ValueSet.from_sets(
lazy_value.infer() for lazy_value in self._iter_list
)
@argument_clinic('sequence, /', want_value=True, want_arguments=True)
def builtins_reversed(sequences, value, arguments):
# While we could do without this variable (just by using sequences), we
# want static analysis to work well. Therefore we need to generated the
# values again.
key, lazy_value = next(arguments.unpack())
cn = None
if isinstance(lazy_value, LazyTreeValue):
cn = ContextualizedNode(lazy_value.context, lazy_value.data)
ordered = list(sequences.iterate(cn))
# Repack iterator values and then run it the normal way. This is
# necessary, because `reversed` is a function and autocompletion
# would fail in certain cases like `reversed(x).__iter__` if we
# just returned the result directly.
seq, = value.inference_state.typing_module.py__getattribute__('Iterator').execute_with_values()
return ValueSet([ReversedObject(seq, list(reversed(ordered)))])
@argument_clinic('value, type, /', want_arguments=True, want_inference_state=True)
def builtins_isinstance(objects, types, arguments, inference_state):
bool_results = set()
for o in objects:
cls = o.py__class__()
try:
cls.py__bases__
except AttributeError:
# This is temporary. Everything should have a class attribute in
# Python?! Maybe we'll leave it here, because some numpy objects or
# whatever might not.
bool_results = set([True, False])
break
mro = list(cls.py__mro__())
for cls_or_tup in types:
if cls_or_tup.is_class():
bool_results.add(cls_or_tup in mro)
elif cls_or_tup.name.string_name == 'tuple' \
and cls_or_tup.get_root_context().is_builtins_module():
# Check for tuples.
classes = ValueSet.from_sets(
lazy_value.infer()
for lazy_value in cls_or_tup.iterate()
)
bool_results.add(any(cls in mro for cls in classes))
else:
_, lazy_value = list(arguments.unpack())[1]
if isinstance(lazy_value, LazyTreeValue):
node = lazy_value.data
message = 'TypeError: isinstance() arg 2 must be a ' \
'class, type, or tuple of classes and types, ' \
'not %s.' % cls_or_tup
analysis.add(lazy_value.context, 'type-error-isinstance', node, message)
return ValueSet(
compiled.builtin_from_name(inference_state, str(b))
for b in bool_results
)
| ReversedObject |
python | pandas-dev__pandas | pandas/tests/indexes/categorical/test_indexing.py | {
"start": 12585,
"end": 14948
} | class ____:
def test_contains(self):
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=False)
assert "a" in ci
assert "z" not in ci
assert "e" not in ci
assert np.nan not in ci
# assert codes NOT in index
assert 0 not in ci
assert 1 not in ci
def test_contains_nan(self):
ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef"))
assert np.nan in ci
@pytest.mark.parametrize("unwrap", [True, False])
def test_contains_na_dtype(self, unwrap):
dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT)
pi = dti.to_period("D")
tdi = dti - dti[-1]
ci = CategoricalIndex(dti)
obj = ci
if unwrap:
obj = ci._data
assert np.nan in obj
assert None in obj
assert pd.NaT in obj
assert np.datetime64("NaT") in obj
assert np.timedelta64("NaT") not in obj
obj2 = CategoricalIndex(tdi)
if unwrap:
obj2 = obj2._data
assert np.nan in obj2
assert None in obj2
assert pd.NaT in obj2
assert np.datetime64("NaT") not in obj2
assert np.timedelta64("NaT") in obj2
obj3 = CategoricalIndex(pi)
if unwrap:
obj3 = obj3._data
assert np.nan in obj3
assert None in obj3
assert pd.NaT in obj3
assert np.datetime64("NaT") not in obj3
assert np.timedelta64("NaT") not in obj3
@pytest.mark.parametrize(
"item, expected",
[
(pd.Interval(0, 1), True),
(1.5, True),
(pd.Interval(0.5, 1.5), False),
("a", False),
(Timestamp(1), False),
(pd.Timedelta(1), False),
],
ids=str,
)
def test_contains_interval(self, item, expected):
# GH 23705
ci = CategoricalIndex(IntervalIndex.from_breaks(range(3)))
result = item in ci
assert result is expected
def test_contains_list(self):
# GH#21729
idx = CategoricalIndex([1, 2, 3])
assert "a" not in idx
with pytest.raises(TypeError, match="unhashable type"):
["a"] in idx
with pytest.raises(TypeError, match="unhashable type"):
["a", "b"] in idx
| TestContains |
python | getsentry__sentry | tests/sentry/db/models/fields/test_jsonfield.py | {
"start": 556,
"end": 782
} | class ____(models.Model):
null_json = JSONField(null=True)
blank_json = JSONField(blank=True)
class Meta:
app_label = "fixtures"
def default() -> dict[str, int]:
return {"x": 2}
| BlankJSONFieldTestModel |
python | davidhalter__jedi | test/completion/stdlib.py | {
"start": 3869,
"end": 4757
} | class ____():
def __init__(self):
self.my_variable = 3
@staticmethod
def my_func(param):
#? []
param.my_
#? ['upper']
param.uppe
#? str()
return param
@staticmethod
def my_func_without_call(param):
#? []
param.my_
#? []
param.uppe
#?
return param
@classmethod
def my_method_without_call(cls, param):
#?
cls.my_variable
#? ['my_method', 'my_method_without_call']
cls.my_meth
#?
return param
@classmethod
def my_method(cls, param):
#?
cls.my_variable
#? ['my_method', 'my_method_without_call']
cls.my_meth
#?
return param
#? str()
F.my_func('')
#? str()
F.my_method('')
# -----------------
# Unknown metaclass
# -----------------
# Github issue 1321
| F |
python | getsentry__sentry | tests/sentry/db/test_transactions.py | {
"start": 4927,
"end": 5011
} | class ____(CaseMixin, TestCase):
pass
@no_silo_test
| TestDjangoTestCaseTransactions |
python | urllib3__urllib3 | test/test_exceptions.py | {
"start": 2649,
"end": 3210
} | class ____:
def test_pool_property_deprecation_warning(self) -> None:
err = NewConnectionError(HTTPConnection("localhost"), "test")
with pytest.warns(DeprecationWarning) as records:
err_pool = err.pool
assert err_pool is err.conn
msg = (
"The 'pool' property is deprecated and will be removed "
"in urllib3 v2.1.0. Use 'conn' instead."
)
record = records[0]
assert isinstance(record.message, Warning)
assert record.message.args[0] == msg
| TestNewConnectionError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1131866,
"end": 1133541
} | class ____(sgqlc.types.Type, Node):
"""A deployment review."""
__schema__ = github_schema
__field_names__ = ("comment", "database_id", "environments", "state", "user")
comment = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="comment")
"""The comment the user left."""
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
environments = sgqlc.types.Field(
sgqlc.types.non_null(EnvironmentConnection),
graphql_name="environments",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
("before", sgqlc.types.Arg(String, graphql_name="before", default=None)),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
"""The environments approved or rejected
Arguments:
* `after` (`String`): Returns the elements in the list that come
after the specified cursor.
* `before` (`String`): Returns the elements in the list that come
before the specified cursor.
* `first` (`Int`): Returns the first _n_ elements from the list.
* `last` (`Int`): Returns the last _n_ elements from the list.
"""
state = sgqlc.types.Field(sgqlc.types.non_null(DeploymentReviewState), graphql_name="state")
"""The decision of the user."""
user = sgqlc.types.Field(sgqlc.types.non_null("User"), graphql_name="user")
"""The user that reviewed the deployment."""
| DeploymentReview |
python | tiangolo__fastapi | fastapi/params.py | {
"start": 406,
"end": 514
} | class ____(Enum):
query = "query"
header = "header"
path = "path"
cookie = "cookie"
| ParamTypes |
python | ray-project__ray | python/ray/_private/resource_and_label_spec.py | {
"start": 418,
"end": 19661
} | class ____:
"""Represents the resource and label configuration passed to a raylet.
All fields can be None. Before starting services, resolve() should be
called to return a ResourceAndLabelSpec with unknown values filled in with
merged values based on the local machine and user specifications.
"""
def __init__(
self,
num_cpus: Optional[int] = None,
num_gpus: Optional[int] = None,
memory: Optional[float] = None,
object_store_memory: Optional[float] = None,
resources: Optional[Dict[str, float]] = None,
labels: Optional[Dict[str, str]] = None,
):
"""
Initialize a ResourceAndLabelSpec
Args:
num_cpus: The CPUs allocated for this raylet.
num_gpus: The GPUs allocated for this raylet.
memory: The memory allocated for this raylet.
object_store_memory: The object store memory allocated for this raylet.
resources: The custom resources allocated for this raylet.
labels: The labels associated with this node. Labels can be used along
with resources for scheduling.
"""
self.num_cpus = num_cpus
self.num_gpus = num_gpus
self.memory = memory
self.object_store_memory = object_store_memory
self.resources = resources
self.labels = labels
self._is_resolved = False
def resolved(self) -> bool:
"""Returns if resolve() has been called for this ResourceAndLabelSpec
and default values are filled out."""
return self._is_resolved
def _all_fields_set(self) -> bool:
"""Returns whether all fields in this ResourceAndLabelSpec are not None."""
return all(
v is not None
for v in (
self.num_cpus,
self.num_gpus,
self.memory,
self.object_store_memory,
self.resources,
self.labels,
)
)
def to_resource_dict(self):
"""Returns a dict suitable to pass to raylet initialization.
This renames num_cpus / num_gpus to "CPU" / "GPU",
and check types and values.
"""
assert self.resolved()
resources = dict(
self.resources,
CPU=self.num_cpus,
GPU=self.num_gpus,
memory=int(self.memory),
object_store_memory=int(self.object_store_memory),
)
resources = {
resource_label: resource_quantity
for resource_label, resource_quantity in resources.items()
if resource_quantity != 0
}
# Check types.
for resource_label, resource_quantity in resources.items():
assert isinstance(resource_quantity, int) or isinstance(
resource_quantity, float
), (
f"{resource_label} ({type(resource_quantity)}): " f"{resource_quantity}"
)
if (
isinstance(resource_quantity, float)
and not resource_quantity.is_integer()
):
raise ValueError(
"Resource quantities must all be whole numbers. "
"Violated by resource '{}' in {}.".format(resource_label, resources)
)
if resource_quantity < 0:
raise ValueError(
"Resource quantities must be nonnegative. "
"Violated by resource '{}' in {}.".format(resource_label, resources)
)
if resource_quantity > ray_constants.MAX_RESOURCE_QUANTITY:
raise ValueError(
"Resource quantities must be at most {}. "
"Violated by resource '{}' in {}.".format(
ray_constants.MAX_RESOURCE_QUANTITY, resource_label, resources
)
)
return resources
def resolve(
self, is_head: bool, node_ip_address: Optional[str] = None
) -> "ResourceAndLabelSpec":
"""Fills out this ResourceAndLabelSpec instance with merged values from system defaults and user specification.
Args:
is_head: Whether this is the head node.
node_ip_address: The IP address of the node that we are on.
This is used to automatically create a node id resource.
Returns:
ResourceAndLabelSpec: This instance with all fields resolved.
"""
self._resolve_resources(is_head=is_head, node_ip_address=node_ip_address)
# Resolve accelerator-specific resources
(
accelerator_manager,
num_accelerators,
) = ResourceAndLabelSpec._get_current_node_accelerator(
self.num_gpus, self.resources
)
self._resolve_accelerator_resources(accelerator_manager, num_accelerators)
# Default num_gpus value if unset by user and unable to auto-detect.
if self.num_gpus is None:
self.num_gpus = 0
# Resolve and merge node labels from all sources (params, env, and default).
self._resolve_labels(accelerator_manager)
# Resolve memory resources
self._resolve_memory_resources()
self._is_resolved = True
assert self._all_fields_set()
return self
@staticmethod
def _load_env_resources() -> Dict[str, float]:
"""Load resource overrides from the environment, if present."""
env_resources = {}
env_string = os.getenv(ray_constants.RESOURCES_ENVIRONMENT_VARIABLE)
if env_string:
try:
env_resources = json.loads(env_string)
except Exception:
logger.exception(f"Failed to load {env_string}")
raise
logger.debug(f"Autoscaler overriding resources: {env_resources}.")
return env_resources
@staticmethod
def _merge_resources(env_dict: Dict[str, float], params_dict: Dict[str, float]):
"""Merge environment and Ray param-provided resources, with env values taking precedence.
Returns separated special case params (CPU/GPU/memory) and the merged resource dict.
"""
num_cpus = env_dict.pop("CPU", None)
num_gpus = env_dict.pop("GPU", None)
memory = env_dict.pop("memory", None)
object_store_memory = env_dict.pop("object_store_memory", None)
result = params_dict.copy()
result.update(env_dict)
for key in set(env_dict.keys()).intersection(params_dict or {}):
if params_dict[key] != env_dict[key]:
logger.warning(
f"Autoscaler is overriding your resource: {key}: "
f"{params_dict[key]} with {env_dict[key]}."
)
return num_cpus, num_gpus, memory, object_store_memory, result
def _resolve_resources(
self, is_head: bool, node_ip_address: Optional[str] = None
) -> None:
"""Resolve CPU, GPU, and custom resources. Merges resources from environment,
Ray params, and defaults in that order of precedence."""
# Load environment override resources and merge with resources passed
# in from Ray Params. Separates special case params if found in env.
env_resources = ResourceAndLabelSpec._load_env_resources()
(
num_cpus,
num_gpus,
memory,
object_store_memory,
merged_resources,
) = ResourceAndLabelSpec._merge_resources(env_resources, self.resources or {})
self.num_cpus = self.num_cpus if num_cpus is None else num_cpus
self.num_gpus = self.num_gpus if num_gpus is None else num_gpus
self.memory = self.memory if memory is None else memory
self.object_store_memory = (
self.object_store_memory
if object_store_memory is None
else object_store_memory
)
self.resources = merged_resources
if node_ip_address is None:
node_ip_address = ray.util.get_node_ip_address()
# Automatically create a node id resource on each node. This is
# queryable with ray._private.state.node_ids() and
# ray._private.state.current_node_id().
self.resources[NODE_ID_PREFIX + node_ip_address] = 1.0
# Automatically create a head node resource.
if HEAD_NODE_RESOURCE_NAME in self.resources:
raise ValueError(
f"{HEAD_NODE_RESOURCE_NAME}"
" is a reserved resource name, use another name instead."
)
if is_head:
self.resources[HEAD_NODE_RESOURCE_NAME] = 1.0
# Auto-detect CPU count if not explicitly set
if self.num_cpus is None:
self.num_cpus = ray._private.utils.get_num_cpus()
@staticmethod
def _load_env_labels() -> Dict[str, str]:
env_override_labels = {}
env_override_labels_string = os.getenv(
ray_constants.LABELS_ENVIRONMENT_VARIABLE
)
if env_override_labels_string:
try:
env_override_labels = json.loads(env_override_labels_string)
except Exception:
logger.exception(f"Failed to load {env_override_labels_string}")
raise
logger.info(f"Autoscaler overriding labels: {env_override_labels}.")
return env_override_labels
@staticmethod
def _get_default_labels(
accelerator_manager: Optional[AcceleratorManager],
) -> Dict[str, str]:
default_labels = {}
# Get environment variables populated from K8s Pod Spec
node_group = os.environ.get(ray._raylet.NODE_TYPE_NAME_ENV, "")
market_type = os.environ.get(ray._raylet.NODE_MARKET_TYPE_ENV, "")
availability_region = os.environ.get(ray._raylet.NODE_REGION_ENV, "")
availability_zone = os.environ.get(ray._raylet.NODE_ZONE_ENV, "")
# Map environment variables to default ray node labels
if market_type:
default_labels[ray._raylet.RAY_NODE_MARKET_TYPE_KEY] = market_type
if node_group:
default_labels[ray._raylet.RAY_NODE_GROUP_KEY] = node_group
if availability_zone:
default_labels[ray._raylet.RAY_NODE_ZONE_KEY] = availability_zone
if availability_region:
default_labels[ray._raylet.RAY_NODE_REGION_KEY] = availability_region
# Get accelerator type from AcceleratorManager
if accelerator_manager:
accelerator_type = accelerator_manager.get_current_node_accelerator_type()
if accelerator_type:
default_labels[
ray._raylet.RAY_NODE_ACCELERATOR_TYPE_KEY
] = accelerator_type
# Set TPU specific default labels to enable multi-host scheduling.
if accelerator_manager.get_resource_name() == "TPU":
tpu_labels = accelerator_manager.get_current_node_accelerator_labels()
if tpu_labels:
default_labels.update(tpu_labels)
return default_labels
def _resolve_labels(
self, accelerator_manager: Optional[AcceleratorManager]
) -> None:
"""Resolve and merge environment override, user-input from params, and Ray default
labels in that order of precedence."""
# Start with a dictionary filled out with Ray default labels
merged = ResourceAndLabelSpec._get_default_labels(accelerator_manager)
# Merge user-specified labels from Ray params
for key, val in (self.labels or {}).items():
if key in merged and merged[key] != val:
logger.warning(
f"User label is overriding Ray default label: {key}: "
f"{key}: {merged[key]} to "
f"{key}: {self.labels[key]}."
)
merged[key] = val
# Merge autoscaler override labels from environment
env_labels = ResourceAndLabelSpec._load_env_labels()
for key, val in (env_labels or {}).items():
if key in merged and merged[key] != val:
logger.warning(
"Autoscaler is overriding your label:"
f"{key}: {merged[key]} to "
f"{key}: {env_labels[key]}."
)
merged[key] = val
self.labels = merged
def _resolve_accelerator_resources(self, accelerator_manager, num_accelerators):
"""Detect and update accelerator resources on a node."""
if not accelerator_manager:
return
accelerator_resource_name = accelerator_manager.get_resource_name()
visible_accelerator_ids = (
accelerator_manager.get_current_process_visible_accelerator_ids()
)
# Check that the number of accelerators that the raylet wants doesn't
# exceed the amount allowed by visible accelerator ids.
if (
num_accelerators is not None
and visible_accelerator_ids is not None
and num_accelerators > len(visible_accelerator_ids)
):
raise ValueError(
f"Attempting to start raylet with {num_accelerators} "
f"{accelerator_resource_name}, "
f"but {accelerator_manager.get_visible_accelerator_ids_env_var()} "
f"contains {visible_accelerator_ids}."
)
if accelerator_resource_name == "GPU":
self.num_gpus = num_accelerators
else:
self.resources[accelerator_resource_name] = num_accelerators
accelerator_type = accelerator_manager.get_current_node_accelerator_type()
if accelerator_type:
self.resources[f"{RESOURCE_CONSTRAINT_PREFIX}{accelerator_type}"] = 1
additional_resources = (
accelerator_manager.get_current_node_additional_resources()
)
if additional_resources:
self.resources.update(additional_resources)
def _resolve_memory_resources(self):
# Choose a default object store size.
system_memory = ray._common.utils.get_system_memory()
avail_memory = ray._private.utils.estimate_available_memory()
object_store_memory = self.object_store_memory
if object_store_memory is None:
object_store_memory = int(
avail_memory * ray_constants.DEFAULT_OBJECT_STORE_MEMORY_PROPORTION
)
# Set the object_store_memory size to 2GB on Mac
# to avoid degraded performance.
# (https://github.com/ray-project/ray/issues/20388)
if sys.platform == "darwin":
object_store_memory = min(
object_store_memory, ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT
)
object_store_memory_cap = (
ray_constants.DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES
)
# Cap by shm size by default to avoid low performance, but don't
# go lower than REQUIRE_SHM_SIZE_THRESHOLD.
if sys.platform == "linux" or sys.platform == "linux2":
# Multiple by 0.95 to give a bit of wiggle-room.
# https://github.com/ray-project/ray/pull/23034/files
shm_avail = ray._private.utils.get_shared_memory_bytes() * 0.95
shm_cap = max(ray_constants.REQUIRE_SHM_SIZE_THRESHOLD, shm_avail)
object_store_memory_cap = min(object_store_memory_cap, shm_cap)
# Cap memory to avoid memory waste and perf issues on large nodes
if (
object_store_memory_cap
and object_store_memory > object_store_memory_cap
):
logger.debug(
"Warning: Capping object memory store to {}GB. ".format(
object_store_memory_cap // 1e9
)
+ "To increase this further, specify `object_store_memory` "
"when calling ray.init() or ray start."
)
object_store_memory = object_store_memory_cap
memory = self.memory
if memory is None:
memory = avail_memory - object_store_memory
if memory < 100e6 and memory < 0.05 * system_memory:
raise ValueError(
"After taking into account object store and redis memory "
"usage, the amount of memory on this node available for "
"tasks and actors ({} GB) is less than {}% of total. "
"You can adjust these settings with "
"ray.init(memory=<bytes>, "
"object_store_memory=<bytes>).".format(
round(memory / 1e9, 2), int(100 * (memory / system_memory))
)
)
# Set the resolved memory and object_store_memory
self.object_store_memory = object_store_memory
self.memory = memory
@staticmethod
def _get_current_node_accelerator(
num_gpus: Optional[int], resources: Dict[str, float]
) -> Tuple[AcceleratorManager, int]:
"""
Returns the AcceleratorManager and accelerator count for the accelerator
associated with this node. This assumes each node has at most one accelerator type.
If no accelerators are present, returns None.
The resolved accelerator count uses num_gpus (for GPUs) or resources if set, and
otherwise falls back to the count auto-detected by the AcceleratorManager. The
resolved accelerator count is capped by the number of visible accelerators.
Args:
num_gpus: GPU count (if provided by user).
resources: Resource dictionary containing custom resource keys.
Returns:
Tuple[Optional[AcceleratorManager], int]: A tuple containing the accelerator
manager (or None) the final resolved accelerator count.
"""
for resource_name in accelerators.get_all_accelerator_resource_names():
accelerator_manager = accelerators.get_accelerator_manager_for_resource(
resource_name
)
if accelerator_manager is None:
continue
# Respect configured value for GPUs if set
if resource_name == "GPU":
num_accelerators = num_gpus
else:
num_accelerators = resources.get(resource_name)
if num_accelerators is None:
num_accelerators = (
accelerator_manager.get_current_node_num_accelerators()
)
visible_accelerator_ids = (
accelerator_manager.get_current_process_visible_accelerator_ids()
)
if visible_accelerator_ids is not None:
num_accelerators = min(
num_accelerators, len(visible_accelerator_ids)
)
if num_accelerators > 0:
return accelerator_manager, num_accelerators
return None, 0
| ResourceAndLabelSpec |
python | PrefectHQ__prefect | scripts/generate_example_pages.py | {
"start": 656,
"end": 797
} | class ____:
path: anyio.Path
title: str
description: str
icon: str
keywords: list[str]
order: int | None = None
| Example |
python | huggingface__transformers | src/transformers/models/bert_generation/modeling_bert_generation.py | {
"start": 3497,
"end": 6729
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.scaling = self.attention_head_size**-0.5
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.is_decoder = config.is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.attention_head_size)
# get all proj
query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
if past_key_values is not None:
# decoder-only bert can have a simple dynamic cache for example
current_past_key_values = past_key_values
if isinstance(past_key_values, EncoderDecoderCache):
current_past_key_values = past_key_values.self_attention_cache
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
key_layer, value_layer = current_past_key_values.update(
key_layer,
value_layer,
self.layer_idx,
{"cache_position": cache_position},
)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_layer,
key_layer,
value_layer,
attention_mask,
dropout=0.0 if not self.training else self.dropout.p,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
return attn_output, attn_weights
# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->BertGeneration
| BertGenerationSelfAttention |
python | Textualize__textual | docs/examples/widgets/data_table_cursors.py | {
"start": 634,
"end": 1108
} | class ____(App):
def compose(self) -> ComposeResult:
yield DataTable()
def on_mount(self) -> None:
table = self.query_one(DataTable)
table.cursor_type = next(cursors)
table.zebra_stripes = True
table.add_columns(*ROWS[0])
table.add_rows(ROWS[1:])
def key_c(self):
table = self.query_one(DataTable)
table.cursor_type = next(cursors)
app = TableApp()
if __name__ == "__main__":
app.run()
| TableApp |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 262695,
"end": 263050
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("CreatedPullRequestContribution", graphql_name="node")
| CreatedPullRequestContributionEdge |
python | pytorch__pytorch | torch/distributed/fsdp/_optim_utils.py | {
"start": 1882,
"end": 3027
} | class ____:
"""
This holds the consolidated optimizer state on the target rank. Positive-
dimension tensor state is communicated across ranks, while zero-dimension
tensor state and non-tensor state is taken directly from the target rank.
PyTorch version 1.12 moved to using zero-dimension tensors for scalar
values, but user implemented optimizers may still use float (i.e. a
non-tensor). Thus, we support both and handle them identically.
Attributes:
tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
tensor state name to the unsharded flat tensor representing the
state.
zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
dimension tensor state name to its value.
non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
name to its value.
"""
tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
zero_dim_tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
non_tensor_state: dict[str, Any] = field(default_factory=dict)
| _ConsolidatedOptimState |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/deployment.py | {
"start": 501,
"end": 619
} | class ____(BaseModel):
"""GET /api/deployments response."""
items: list[Deployment]
total: int
| DeploymentList |
python | docker__docker-py | docker/api/build.py | {
"start": 135,
"end": 16063
} | class ____:
def build(self, path=None, tag=None, quiet=False, fileobj=None,
nocache=False, rm=False, timeout=None,
custom_context=False, encoding=None, pull=False,
forcerm=False, dockerfile=None, container_limits=None,
decode=False, buildargs=None, gzip=False, shmsize=None,
labels=None, cache_from=None, target=None, network_mode=None,
squash=None, extra_hosts=None, platform=None, isolation=None,
use_config_proxy=True):
"""
Similar to the ``docker build`` command. Either ``path`` or ``fileobj``
needs to be set. ``path`` can be a local path (to a directory
containing a Dockerfile) or a remote URL. ``fileobj`` must be a
readable file-like object to a Dockerfile.
If you have a tar file for the Docker build context (including a
Dockerfile) already, pass a readable file-like object to ``fileobj``
and also pass ``custom_context=True``. If the stream is compressed
also, set ``encoding`` to the correct value (e.g ``gzip``).
Example:
>>> from io import BytesIO
>>> from docker import APIClient
>>> dockerfile = '''
... # Shared Volume
... FROM busybox:buildroot-2014.02
... VOLUME /data
... CMD ["/bin/sh"]
... '''
>>> f = BytesIO(dockerfile.encode('utf-8'))
>>> cli = APIClient(base_url='tcp://127.0.0.1:2375')
>>> response = [line for line in cli.build(
... fileobj=f, rm=True, tag='yourname/volume'
... )]
>>> response
['{"stream":" ---\\u003e a9eb17255234\\n"}',
'{"stream":"Step 1 : VOLUME /data\\n"}',
'{"stream":" ---\\u003e Running in abdc1e6896c6\\n"}',
'{"stream":" ---\\u003e 713bca62012e\\n"}',
'{"stream":"Removing intermediate container abdc1e6896c6\\n"}',
'{"stream":"Step 2 : CMD [\\"/bin/sh\\"]\\n"}',
'{"stream":" ---\\u003e Running in dba30f2a1a7e\\n"}',
'{"stream":" ---\\u003e 032b8b2855fc\\n"}',
'{"stream":"Removing intermediate container dba30f2a1a7e\\n"}',
'{"stream":"Successfully built 032b8b2855fc\\n"}']
Args:
path (str): Path to the directory containing the Dockerfile
fileobj: A file object to use as the Dockerfile. (Or a file-like
object)
tag (str): A tag to add to the final image
quiet (bool): Whether to return the status
nocache (bool): Don't use the cache when set to ``True``
rm (bool): Remove intermediate containers. The ``docker build``
command now defaults to ``--rm=true``, but we have kept the old
default of `False` to preserve backward compatibility
timeout (int): HTTP timeout
custom_context (bool): Optional if using ``fileobj``
encoding (str): The encoding for a stream. Set to ``gzip`` for
compressing
pull (bool): Downloads any updates to the FROM image in Dockerfiles
forcerm (bool): Always remove intermediate containers, even after
unsuccessful builds
dockerfile (str): path within the build context to the Dockerfile
gzip (bool): If set to ``True``, gzip compression/encoding is used
buildargs (dict): A dictionary of build arguments
container_limits (dict): A dictionary of limits applied to each
container created by the build process. Valid keys:
- memory (int): set memory limit for build
- memswap (int): Total memory (memory + swap), -1 to disable
swap
- cpushares (int): CPU shares (relative weight)
- cpusetcpus (str): CPUs in which to allow execution, e.g.,
``"0-3"``, ``"0,1"``
decode (bool): If set to ``True``, the returned stream will be
decoded into dicts on the fly. Default ``False``
shmsize (int): Size of `/dev/shm` in bytes. The size must be
greater than 0. If omitted the system uses 64MB
labels (dict): A dictionary of labels to set on the image
cache_from (:py:class:`list`): A list of images used for build
cache resolution
target (str): Name of the build-stage to build in a multi-stage
Dockerfile
network_mode (str): networking mode for the run commands during
build
squash (bool): Squash the resulting images layers into a
single layer.
extra_hosts (dict): Extra hosts to add to /etc/hosts in building
containers, as a mapping of hostname to IP address.
platform (str): Platform in the format ``os[/arch[/variant]]``
isolation (str): Isolation technology used during build.
Default: `None`.
use_config_proxy (bool): If ``True``, and if the docker client
configuration file (``~/.docker/config.json`` by default)
contains a proxy configuration, the corresponding environment
variables will be set in the container being built.
Returns:
A generator for the build output.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
``TypeError``
If neither ``path`` nor ``fileobj`` is specified.
"""
remote = context = None
headers = {}
container_limits = container_limits or {}
buildargs = buildargs or {}
if path is None and fileobj is None:
raise TypeError("Either path or fileobj needs to be provided.")
if gzip and encoding is not None:
raise errors.DockerException(
'Can not use custom encoding if gzip is enabled'
)
if tag is not None:
if not utils.match_tag(tag):
raise errors.DockerException(
f"invalid tag '{tag}': invalid reference format"
)
for key in container_limits.keys():
if key not in constants.CONTAINER_LIMITS_KEYS:
raise errors.DockerException(
f"invalid tag '{tag}': invalid reference format"
)
if custom_context:
if not fileobj:
raise TypeError("You must specify fileobj with custom_context")
context = fileobj
elif fileobj is not None:
context = utils.mkbuildcontext(fileobj)
elif path.startswith(('http://', 'https://',
'git://', 'github.com/', 'git@')):
remote = path
elif not os.path.isdir(path):
raise TypeError("You must specify a directory to build in path")
else:
dockerignore = os.path.join(path, '.dockerignore')
exclude = None
if os.path.exists(dockerignore):
with open(dockerignore) as f:
exclude = list(filter(
lambda x: x != '' and x[0] != '#',
[line.strip() for line in f.read().splitlines()]
))
dockerfile = process_dockerfile(dockerfile, path)
context = utils.tar(
path, exclude=exclude, dockerfile=dockerfile, gzip=gzip
)
encoding = 'gzip' if gzip else encoding
u = self._url('/build')
params = {
't': tag,
'remote': remote,
'q': quiet,
'nocache': nocache,
'rm': rm,
'forcerm': forcerm,
'pull': pull,
'dockerfile': dockerfile,
}
params.update(container_limits)
if use_config_proxy:
proxy_args = self._proxy_configs.get_environment()
for k, v in proxy_args.items():
buildargs.setdefault(k, v)
if buildargs:
params.update({'buildargs': json.dumps(buildargs)})
if shmsize:
if utils.version_gte(self._version, '1.22'):
params.update({'shmsize': shmsize})
else:
raise errors.InvalidVersion(
'shmsize was only introduced in API version 1.22'
)
if labels:
if utils.version_gte(self._version, '1.23'):
params.update({'labels': json.dumps(labels)})
else:
raise errors.InvalidVersion(
'labels was only introduced in API version 1.23'
)
if cache_from:
if utils.version_gte(self._version, '1.25'):
params.update({'cachefrom': json.dumps(cache_from)})
else:
raise errors.InvalidVersion(
'cache_from was only introduced in API version 1.25'
)
if target:
if utils.version_gte(self._version, '1.29'):
params.update({'target': target})
else:
raise errors.InvalidVersion(
'target was only introduced in API version 1.29'
)
if network_mode:
if utils.version_gte(self._version, '1.25'):
params.update({'networkmode': network_mode})
else:
raise errors.InvalidVersion(
'network_mode was only introduced in API version 1.25'
)
if squash:
if utils.version_gte(self._version, '1.25'):
params.update({'squash': squash})
else:
raise errors.InvalidVersion(
'squash was only introduced in API version 1.25'
)
if extra_hosts is not None:
if utils.version_lt(self._version, '1.27'):
raise errors.InvalidVersion(
'extra_hosts was only introduced in API version 1.27'
)
if isinstance(extra_hosts, dict):
extra_hosts = utils.format_extra_hosts(extra_hosts)
params.update({'extrahosts': extra_hosts})
if platform is not None:
if utils.version_lt(self._version, '1.32'):
raise errors.InvalidVersion(
'platform was only introduced in API version 1.32'
)
params['platform'] = platform
if isolation is not None:
if utils.version_lt(self._version, '1.24'):
raise errors.InvalidVersion(
'isolation was only introduced in API version 1.24'
)
params['isolation'] = isolation
if context is not None:
headers = {'Content-Type': 'application/tar'}
if encoding:
headers['Content-Encoding'] = encoding
self._set_auth_headers(headers)
response = self._post(
u,
data=context,
params=params,
headers=headers,
stream=True,
timeout=timeout,
)
if context is not None and not custom_context:
context.close()
return self._stream_helper(response, decode=decode)
@utils.minimum_version('1.31')
def prune_builds(self, filters=None, keep_storage=None, all=None):
"""
Delete the builder cache
Args:
filters (dict): Filters to process on the prune list.
Needs Docker API v1.39+
Available filters:
- dangling (bool): When set to true (or 1), prune only
unused and untagged images.
- until (str): Can be Unix timestamps, date formatted
timestamps, or Go duration strings (e.g. 10m, 1h30m) computed
relative to the daemon's local time.
keep_storage (int): Amount of disk space in bytes to keep for cache.
Needs Docker API v1.39+
all (bool): Remove all types of build cache.
Needs Docker API v1.39+
Returns:
(dict): A dictionary containing information about the operation's
result. The ``SpaceReclaimed`` key indicates the amount of
bytes of disk space reclaimed.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/build/prune")
if (filters, keep_storage, all) != (None, None, None) \
and utils.version_lt(self._version, '1.39'):
raise errors.InvalidVersion(
'`filters`, `keep_storage`, and `all` args are only available '
'for API version > 1.38'
)
params = {}
if filters is not None:
params['filters'] = utils.convert_filters(filters)
if keep_storage is not None:
params['keep-storage'] = keep_storage
if all is not None:
params['all'] = all
return self._result(self._post(url, params=params), True)
def _set_auth_headers(self, headers):
log.debug('Looking for auth config')
# If we don't have any auth data so far, try reloading the config
# file one more time in case anything showed up in there.
if not self._auth_configs or self._auth_configs.is_empty:
log.debug("No auth config in memory - loading from filesystem")
self._auth_configs = auth.load_config(
credstore_env=self.credstore_env
)
# Send the full auth configuration (if any exists), since the build
# could use any (or all) of the registries.
if self._auth_configs:
auth_data = self._auth_configs.get_all_credentials()
# See https://github.com/docker/docker-py/issues/1683
if (auth.INDEX_URL not in auth_data and
auth.INDEX_NAME in auth_data):
auth_data[auth.INDEX_URL] = auth_data.get(auth.INDEX_NAME, {})
log.debug(
"Sending auth config (%s)",
', '.join(repr(k) for k in auth_data),
)
if auth_data:
headers['X-Registry-Config'] = auth.encode_header(
auth_data
)
else:
log.debug('No auth config found')
def process_dockerfile(dockerfile, path):
if not dockerfile:
return (None, None)
abs_dockerfile = dockerfile
if not os.path.isabs(dockerfile):
abs_dockerfile = os.path.join(path, dockerfile)
if constants.IS_WINDOWS_PLATFORM and path.startswith(
constants.WINDOWS_LONGPATH_PREFIX):
normpath = os.path.normpath(
abs_dockerfile[len(constants.WINDOWS_LONGPATH_PREFIX):])
abs_dockerfile = f'{constants.WINDOWS_LONGPATH_PREFIX}{normpath}'
if (os.path.splitdrive(path)[0] != os.path.splitdrive(abs_dockerfile)[0] or
os.path.relpath(abs_dockerfile, path).startswith('..')):
# Dockerfile not in context - read data to insert into tar later
with open(abs_dockerfile) as df:
return (
f'.dockerfile.{random.getrandbits(160):x}',
df.read()
)
# Dockerfile is inside the context - return path relative to context root
if dockerfile == abs_dockerfile:
# Only calculate relpath if necessary to avoid errors
# on Windows client -> Linux Docker
# see https://github.com/docker/compose/issues/5969
dockerfile = os.path.relpath(abs_dockerfile, path)
return (dockerfile, None)
| BuildApiMixin |
python | pytorch__pytorch | torch/_inductor/runtime/caching/exceptions.py | {
"start": 1581,
"end": 2263
} | class ____(SystemError):
"""Error raised when a file lock operation times out.
This exception is raised when a file lock operation exceeds the specified timeout
limit, indicating that the lock could not be acquired within the allotted time.
"""
def __init__(self, flock: FileLock, timeout: float) -> None:
"""Initialize the file lock timeout error with detailed lock information.
Args:
flock: The file lock object that timed out.
timeout: The timeout limit that was exceeded.
"""
super().__init__(
f"Failed to acquire file lock {flock} within {timeout} seconds."
)
| FileLockTimeoutError |
python | run-llama__llama_index | llama-index-core/llama_index/core/vector_stores/types.py | {
"start": 2481,
"end": 3718
} | class ____(BaseModel):
r"""
Comprehensive metadata filter for vector stores to support more operators.
Value uses Strict types, as int, float and str are compatible types and were all
converted to string before.
See: https://docs.pydantic.dev/latest/usage/types/#strict-types
"""
key: str
value: Optional[
Union[
StrictInt,
StrictFloat,
StrictStr,
List[StrictStr],
List[StrictFloat],
List[StrictInt],
]
]
operator: FilterOperator = FilterOperator.EQ
@classmethod
def from_dict(
cls,
filter_dict: Dict,
) -> "MetadataFilter":
"""
Create MetadataFilter from dictionary.
Args:
filter_dict: Dict with key, value and operator.
"""
return MetadataFilter.model_validate(filter_dict)
# # TODO: Deprecate ExactMatchFilter and use MetadataFilter instead
# # Keep class for now so that AutoRetriever can still work with old vector stores
# class ExactMatchFilter(BaseModel):
# key: str
# value: Union[StrictInt, StrictFloat, StrictStr]
# set ExactMatchFilter to MetadataFilter
ExactMatchFilter = MetadataFilter
| MetadataFilter |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 152997,
"end": 155494
} | class ____(
testing.AssertsCompiledSQL, fixtures.TestBase
):
"""test new custom op dispatch feature added as part of #12948"""
@testing.fixture
def dialect_fixture(self):
class MyCompiler(compiler.SQLCompiler):
def visit_myop_op_binary(self, binary, operator, **kw):
return "|%s| ->%s<-" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
def visit_myop_op_unary(self, unary, operator, **kw):
if operator is unary.modifier:
return "%s->|" % (self.process(unary.element, **kw))
elif operator is unary.operator:
return "|->%s" % (self.process(unary.element, **kw))
class MyDialect(default.DefaultDialect):
statement_compiler = MyCompiler
myop = operators.custom_op(
"---",
precedence=15,
natural_self_precedent=True,
eager_grouping=True,
visit_name="myop",
)
return MyDialect, myop
@testing.variation("dialect", ["default", "custom"])
def test_binary_override(self, dialect_fixture, dialect):
MyDialect, myop = dialect_fixture
if dialect.default:
self.assert_compile(
myop(column("q", String), column("y", String)), "q --- y"
)
elif dialect.custom:
self.assert_compile(
myop(column("q", String), column("y", String)),
"|q| ->y<-",
dialect=MyDialect(),
)
@testing.variation("dialect", ["default", "custom"])
def test_unary_modifier_override(self, dialect_fixture, dialect):
MyDialect, myop = dialect_fixture
unary = UnaryExpression(column("zqr"), modifier=myop, type_=Numeric)
if dialect.default:
self.assert_compile(unary, "zqr ---")
elif dialect.custom:
self.assert_compile(unary, "zqr->|", dialect=MyDialect())
@testing.variation("dialect", ["default", "custom"])
def test_unary_operator_override(self, dialect_fixture, dialect):
MyDialect, myop = dialect_fixture
unary = UnaryExpression(column("zqr"), operator=myop, type_=Numeric)
if dialect.default:
self.assert_compile(unary, "--- zqr")
elif dialect.custom:
self.assert_compile(unary, "|->zqr", dialect=MyDialect())
| CustomOpDialectCompileTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/bad_staticmethod_argument.py | {
"start": 460,
"end": 690
} | class ____:
@staticmethod
def eat(x, self, z):
pass
@staticmethod
def sleep(x, cls, z):
pass
def grow(self, x, y, z):
pass
@classmethod
def graze(cls, x, y, z):
pass
| Foo |
python | scipy__scipy | scipy/optimize/_shgo_lib/_vertex.py | {
"start": 7009,
"end": 13079
} | class ____(VertexCacheBase):
def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(),
workers=1):
"""
Class for a vertex cache for a simplicial complex with an associated
field.
Parameters
----------
field : callable
Scalar or vector field callable.
field_args : tuple, optional
Any additional fixed parameters needed to completely specify the
field function
g_cons : dict or sequence of dict, optional
Constraints definition.
Function(s) ``R**n`` in the form::
g_cons_args : tuple, optional
Any additional fixed parameters needed to completely specify the
constraint functions
workers : int optional
Uses `multiprocessing.Pool <multiprocessing>`) to compute the field
functions in parallel.
"""
super().__init__()
self.index = -1
self.Vertex = VertexScalarField
self.field = field
self.field_args = field_args
self.wfield = FieldWrapper(field, field_args) # if workers is not 1
self.g_cons = g_cons
self.g_cons_args = g_cons_args
self.wgcons = ConstraintWrapper(g_cons, g_cons_args)
self.gpool = set() # A set of tuples to process for feasibility
# Field processing objects
self.fpool = set() # A set of tuples to process for scalar function
self.sfc_lock = False # True if self.fpool is non-Empty
self.workers = workers
self._mapwrapper = MapWrapper(workers)
if workers == 1:
self.process_gpool = self.proc_gpool
if g_cons is None:
self.process_fpool = self.proc_fpool_nog
else:
self.process_fpool = self.proc_fpool_g
else:
self.process_gpool = self.pproc_gpool
if g_cons is None:
self.process_fpool = self.pproc_fpool_nog
else:
self.process_fpool = self.pproc_fpool_g
def __getitem__(self, x, nn=None):
try:
return self.cache[x]
except KeyError:
self.index += 1
xval = self.Vertex(x, field=self.field, nn=nn, index=self.index,
field_args=self.field_args,
g_cons=self.g_cons,
g_cons_args=self.g_cons_args)
self.cache[x] = xval # Define in cache
self.gpool.add(xval) # Add to pool for processing feasibility
self.fpool.add(xval) # Add to pool for processing field values
return self.cache[x]
def __getstate__(self):
self_dict = self.__dict__.copy()
del self_dict['pool']
return self_dict
def process_pools(self):
if self.g_cons is not None:
self.process_gpool()
self.process_fpool()
self.proc_minimisers()
def feasibility_check(self, v):
v.feasible = True
for g, args in zip(self.g_cons, self.g_cons_args):
# constraint may return more than 1 value.
if np.any(g(v.x_a, *args) < 0.0):
v.f = np.inf
v.feasible = False
break
def compute_sfield(self, v):
"""Compute the scalar field values of a vertex object `v`.
Parameters
----------
v : VertexBase or VertexScalarField object
"""
try:
v.f = self.field(v.x_a, *self.field_args)
self.nfev += 1
except AttributeError:
v.f = np.inf
# logging.warning(f"Field function not found at x = {self.x_a}")
if np.isnan(v.f):
v.f = np.inf
def proc_gpool(self):
"""Process all constraints."""
if self.g_cons is not None:
for v in self.gpool:
self.feasibility_check(v)
# Clean the pool
self.gpool = set()
def pproc_gpool(self):
"""Process all constraints in parallel."""
gpool_l = []
for v in self.gpool:
gpool_l.append(v.x_a)
G = self._mapwrapper(self.wgcons.gcons, gpool_l)
for v, g in zip(self.gpool, G):
v.feasible = g # set vertex object attribute v.feasible = g (bool)
def proc_fpool_g(self):
"""Process all field functions with constraints supplied."""
for v in self.fpool:
if v.feasible:
self.compute_sfield(v)
# Clean the pool
self.fpool = set()
def proc_fpool_nog(self):
"""Process all field functions with no constraints supplied."""
for v in self.fpool:
self.compute_sfield(v)
# Clean the pool
self.fpool = set()
def pproc_fpool_g(self):
"""
Process all field functions with constraints supplied in parallel.
"""
self.wfield.func
fpool_l = []
for v in self.fpool:
if v.feasible:
fpool_l.append(v.x_a)
else:
v.f = np.inf
F = self._mapwrapper(self.wfield.func, fpool_l)
for va, f in zip(fpool_l, F):
vt = tuple(va)
self[vt].f = f # set vertex object attribute v.f = f
self.nfev += 1
# Clean the pool
self.fpool = set()
def pproc_fpool_nog(self):
"""
Process all field functions with no constraints supplied in parallel.
"""
self.wfield.func
fpool_l = []
for v in self.fpool:
fpool_l.append(v.x_a)
F = self._mapwrapper(self.wfield.func, fpool_l)
for va, f in zip(fpool_l, F):
vt = tuple(va)
self[vt].f = f # set vertex object attribute v.f = f
self.nfev += 1
# Clean the pool
self.fpool = set()
def proc_minimisers(self):
"""Check for minimisers."""
for v in self:
v.minimiser()
v.maximiser()
| VertexCacheField |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/progress/test_tqdm_progress_bar.py | {
"start": 1416,
"end": 17086
} | class ____(Tqdm):
def __init__(self, *args, **kwargs):
self.n_values = []
self.total_values = []
self.descriptions = []
super().__init__(*args, **kwargs)
self.__n = 0
self.__total = 0
# again to reset additions from `super().__init__`
self.n_values = []
self.total_values = []
self.descriptions = []
@property
def n(self):
return self.__n
@n.setter
def n(self, value):
self.__n = value
# track the changes in the `n` value
if not len(self.n_values) or value != self.n_values[-1]:
self.n_values.append(value)
@property
def total(self):
return self.__total
@total.setter
def total(self, value):
self.__total = value
self.total_values.append(value)
def set_description(self, *args, **kwargs):
super().set_description(*args, **kwargs)
self.descriptions.append(self.desc)
@pytest.mark.parametrize(
"pbar",
[
# won't print but is still set
TQDMProgressBar(refresh_rate=0),
TQDMProgressBar(),
],
)
def test_tqdm_progress_bar_on(tmp_path, pbar):
"""Test different ways the progress bar can be turned on."""
trainer = Trainer(default_root_dir=tmp_path, callbacks=pbar)
progress_bars = [c for c in trainer.callbacks if isinstance(c, ProgressBar)]
assert len(progress_bars) == 1
assert progress_bars[0] is trainer.progress_bar_callback
def test_tqdm_progress_bar_off(tmp_path):
"""Test turning the progress bar off."""
trainer = Trainer(default_root_dir=tmp_path, enable_progress_bar=False)
progress_bars = [c for c in trainer.callbacks if isinstance(c, ProgressBar)]
assert not len(progress_bars)
def test_tqdm_progress_bar_misconfiguration():
"""Test that Trainer doesn't accept multiple progress bars."""
# Trainer supports only a single progress bar callback at the moment
callbacks = [TQDMProgressBar(), TQDMProgressBar(), ModelCheckpoint(dirpath="../trainer")]
with pytest.raises(MisconfigurationException, match=r"^You added multiple progress bar callbacks"):
Trainer(callbacks=callbacks)
with pytest.raises(MisconfigurationException, match=r"enable_progress_bar=False` but found `TQDMProgressBar"):
Trainer(callbacks=TQDMProgressBar(), enable_progress_bar=False)
@patch("lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE", False)
@pytest.mark.parametrize("num_dl", [1, 2])
def test_tqdm_progress_bar_totals(tmp_path, num_dl):
"""Test that the progress finishes with the correct total steps processed."""
class CustomModel(BoringModel):
def _get_dataloaders(self):
dls = [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64))]
return dls[0] if num_dl == 1 else dls
def val_dataloader(self):
return self._get_dataloaders()
def test_dataloader(self):
return self._get_dataloaders()
def predict_dataloader(self):
return self._get_dataloaders()
def validation_step(self, batch, batch_idx, dataloader_idx=0):
return
def test_step(self, batch, batch_idx, dataloader_idx=0):
return
def predict_step(self, batch, batch_idx, dataloader_idx=0):
return
model = CustomModel()
# check the sanity dataloaders
num_sanity_val_steps = 4
trainer = Trainer(
default_root_dir=tmp_path, max_epochs=1, limit_train_batches=0, num_sanity_val_steps=num_sanity_val_steps
)
pbar = trainer.progress_bar_callback
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.fit(model)
expected_sanity_steps = [num_sanity_val_steps] * num_dl
assert not pbar.val_progress_bar.leave
assert trainer.num_sanity_val_batches == expected_sanity_steps
assert pbar.val_progress_bar.total_values == expected_sanity_steps
assert pbar.val_progress_bar.n_values == list(range(num_sanity_val_steps + 1)) * num_dl
assert pbar.val_progress_bar.descriptions == [f"Sanity Checking DataLoader {i}: " for i in range(num_dl)]
# fit
trainer = Trainer(default_root_dir=tmp_path, max_epochs=1)
pbar = trainer.progress_bar_callback
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.fit(model)
n = trainer.num_training_batches
m = trainer.num_val_batches
assert len(trainer.train_dataloader) == n
# train progress bar should have reached the end
assert pbar.train_progress_bar.total == n
assert pbar.train_progress_bar.n == n
assert pbar.train_progress_bar.leave
# check val progress bar total
assert pbar.val_progress_bar.total_values == m
assert pbar.val_progress_bar.n_values == list(range(m[0] + 1)) * num_dl
assert pbar.val_progress_bar.descriptions == [f"Validation DataLoader {i}: " for i in range(num_dl)]
assert not pbar.val_progress_bar.leave
# validate
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.validate(model)
assert trainer.num_val_batches == m
assert pbar.val_progress_bar.total_values == m
assert pbar.val_progress_bar.n_values == list(range(m[0] + 1)) * num_dl
assert pbar.val_progress_bar.descriptions == [f"Validation DataLoader {i}: " for i in range(num_dl)]
# test
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.test(model)
assert pbar.test_progress_bar.leave
k = trainer.num_test_batches
assert pbar.test_progress_bar.total_values == k
assert pbar.test_progress_bar.n_values == list(range(k[0] + 1)) * num_dl
assert pbar.test_progress_bar.descriptions == [f"Testing DataLoader {i}: " for i in range(num_dl)]
assert pbar.test_progress_bar.leave
# predict
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.predict(model)
assert pbar.predict_progress_bar.leave
k = trainer.num_predict_batches
assert pbar.predict_progress_bar.total_values == k
assert pbar.predict_progress_bar.n_values == list(range(k[0] + 1)) * num_dl
assert pbar.predict_progress_bar.descriptions == [f"Predicting DataLoader {i}: " for i in range(num_dl)]
assert pbar.predict_progress_bar.leave
@patch("lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE", False)
def test_tqdm_progress_bar_fast_dev_run(tmp_path):
model = BoringModel()
trainer = Trainer(default_root_dir=tmp_path, fast_dev_run=True)
trainer.fit(model)
pbar = trainer.progress_bar_callback
assert pbar.val_progress_bar.n == 1
assert pbar.val_progress_bar.total == 1
# the train progress bar should display 1 batch
assert pbar.train_progress_bar.total == 1
assert pbar.train_progress_bar.n == 1
trainer.validate(model)
# the validation progress bar should display 1 batch
assert pbar.val_progress_bar.total == 1
assert pbar.val_progress_bar.n == 1
trainer.test(model)
# the test progress bar should display 1 batch
assert pbar.test_progress_bar.total == 1
assert pbar.test_progress_bar.n == 1
@pytest.mark.parametrize("refresh_rate", [0, 1, 50])
def test_tqdm_progress_bar_progress_refresh(tmp_path, refresh_rate: int):
"""Test that the three progress bars get correctly updated when using different refresh rates."""
model = BoringModel()
class CurrentProgressBar(TQDMProgressBar):
train_batches_seen = 0
val_batches_seen = 0
test_batches_seen = 0
def on_train_batch_end(self, *args):
super().on_train_batch_end(*args)
self.train_batches_seen += 1
def on_validation_batch_end(self, *args):
super().on_validation_batch_end(*args)
self.val_batches_seen += 1
def on_test_batch_end(self, *args):
super().on_test_batch_end(*args)
self.test_batches_seen += 1
pbar = CurrentProgressBar(refresh_rate=refresh_rate)
trainer = Trainer(
default_root_dir=tmp_path,
callbacks=[pbar],
limit_train_batches=1.0,
num_sanity_val_steps=2,
max_epochs=3,
)
assert trainer.progress_bar_callback.refresh_rate == refresh_rate
trainer.fit(model)
assert pbar.train_batches_seen == 3 * pbar.train_progress_bar.total
assert pbar.val_batches_seen == 3 * pbar.val_progress_bar.total + trainer.num_sanity_val_steps
assert pbar.test_batches_seen == 0
trainer.validate(model)
assert pbar.train_batches_seen == 3 * pbar.train_progress_bar.total
assert pbar.val_batches_seen == 4 * pbar.val_progress_bar.total + trainer.num_sanity_val_steps
assert pbar.test_batches_seen == 0
trainer.test(model)
assert pbar.train_batches_seen == 3 * pbar.train_progress_bar.total
assert pbar.val_batches_seen == 4 * pbar.val_progress_bar.total + trainer.num_sanity_val_steps
assert pbar.test_batches_seen == pbar.test_progress_bar.total
@pytest.mark.parametrize("limit_val_batches", [0, 5])
def test_num_sanity_val_steps_progress_bar(tmp_path, limit_val_batches: int):
"""Test val_progress_bar total with 'num_sanity_val_steps' Trainer argument."""
class CurrentProgressBar(TQDMProgressBar):
val_pbar_total = 0
sanity_pbar_total = 0
def on_sanity_check_end(self, *args):
self.sanity_pbar_total = self.val_progress_bar.total
super().on_sanity_check_end(*args)
def on_validation_epoch_end(self, *args):
self.val_pbar_total = self.val_progress_bar.total
super().on_validation_epoch_end(*args)
model = BoringModel()
pbar = CurrentProgressBar()
num_sanity_val_steps = 2
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=1,
num_sanity_val_steps=num_sanity_val_steps,
limit_train_batches=1,
limit_val_batches=limit_val_batches,
callbacks=[pbar],
logger=False,
enable_checkpointing=False,
)
trainer.fit(model)
assert pbar.sanity_pbar_total == min(num_sanity_val_steps, limit_val_batches)
assert pbar.val_pbar_total == limit_val_batches
def test_tqdm_progress_bar_default_value(tmp_path):
"""Test that a value of None defaults to refresh rate 1."""
trainer = Trainer(default_root_dir=tmp_path)
assert trainer.progress_bar_callback.refresh_rate == 1
@mock.patch.dict(os.environ, {"COLAB_GPU": "1"})
@patch("lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE", False)
def test_tqdm_progress_bar_value_on_colab(tmp_path):
"""Test that Trainer will override the default in Google COLAB."""
trainer = Trainer(default_root_dir=tmp_path)
assert trainer.progress_bar_callback.refresh_rate == 20
trainer = Trainer(default_root_dir=tmp_path, callbacks=TQDMProgressBar())
assert trainer.progress_bar_callback.refresh_rate == 20
trainer = Trainer(default_root_dir=tmp_path, callbacks=TQDMProgressBar(refresh_rate=19))
assert trainer.progress_bar_callback.refresh_rate == 19
@pytest.mark.parametrize(
("refresh_rate", "env_value", "expected"),
[
(0, 1, 1),
(1, 0, 1),
(1, 1, 1),
(2, 1, 2),
(1, 2, 2),
],
)
def test_tqdm_progress_bar_refresh_rate_via_env_variable(refresh_rate, env_value, expected):
with mock.patch.dict(os.environ, {"TQDM_MINITERS": str(env_value)}):
bar = TQDMProgressBar(refresh_rate=refresh_rate)
assert bar.refresh_rate == expected
@pytest.mark.parametrize(
("train_batches", "val_batches", "refresh_rate", "train_updates", "val_updates"),
[
(2, 3, 1, [0, 1, 2], [0, 1, 2, 3]),
(0, 0, 3, None, None),
(1, 0, 3, [0, 1], None),
(1, 1, 3, [0, 1], [0, 1]),
(5, 0, 3, [0, 3, 5], None),
(5, 2, 3, [0, 3, 5], [0, 2]),
(5, 2, 6, [0, 5], [0, 2]),
],
)
def test_train_progress_bar_update_amount(
tmp_path, train_batches: int, val_batches: int, refresh_rate: int, train_updates, val_updates
):
"""Test that the train progress updates with the correct amount together with the val progress.
At the end of the epoch, the progress must not overshoot if the number of steps is not divisible by the refresh
rate.
"""
model = BoringModel()
progress_bar = TQDMProgressBar(refresh_rate=refresh_rate)
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=1,
limit_train_batches=train_batches,
limit_val_batches=val_batches,
callbacks=[progress_bar],
logger=False,
enable_checkpointing=False,
)
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.fit(model)
if train_batches > 0:
assert progress_bar.train_progress_bar.n_values == train_updates
if val_batches > 0:
assert progress_bar.val_progress_bar.n_values == val_updates
@pytest.mark.parametrize(
("test_batches", "refresh_rate", "updates"), [(1, 3, [0, 1]), (3, 1, [0, 1, 2, 3]), (5, 3, [0, 3, 5])]
)
def test_test_progress_bar_update_amount(tmp_path, test_batches: int, refresh_rate: int, updates: list):
"""Test that test progress updates with the correct amount."""
model = BoringModel()
progress_bar = TQDMProgressBar(refresh_rate=refresh_rate)
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=1,
limit_test_batches=test_batches,
callbacks=[progress_bar],
logger=False,
enable_checkpointing=False,
)
with mock.patch("lightning.pytorch.callbacks.progress.tqdm_progress.Tqdm", MockTqdm):
trainer.test(model)
assert progress_bar.test_progress_bar.n_values == updates
@patch("lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE", False)
def test_tensor_to_float_conversion(tmp_path):
"""Check tensor gets converted to float."""
class TestModel(BoringModel):
def training_step(self, batch, batch_idx):
self.log("a", torch.tensor(0.123), prog_bar=True, on_epoch=False)
self.log("b", torch.tensor([1]), prog_bar=True, on_epoch=False)
self.log("c", 2, prog_bar=True, on_epoch=False)
return super().training_step(batch, batch_idx)
trainer = Trainer(
default_root_dir=tmp_path, max_epochs=1, limit_train_batches=2, logger=False, enable_checkpointing=False
)
with mock.patch.object(sys.stdout, "write") as mock_write:
trainer.fit(TestModel())
bar_updates = "".join(call.args[0] for call in mock_write.call_args_list)
assert "a=0.123" in bar_updates
assert "b=1.000" in bar_updates
assert "c=2.000" in bar_updates
torch.testing.assert_close(trainer.progress_bar_metrics["a"], 0.123)
assert trainer.progress_bar_metrics["b"] == 1.0
assert trainer.progress_bar_metrics["c"] == 2.0
pbar = trainer.progress_bar_callback.train_progress_bar
actual = str(pbar.postfix)
assert actual.endswith("a=0.123, b=1.000, c=2.000"), actual
@pytest.mark.parametrize(
("input_num", "expected"),
[
(1, "1"),
(1.0, "1.000"),
(0.1, "0.100"),
(1e-3, "0.001"),
(1e-5, "1e-5"),
("1.0", "1.000"),
("10000", "10000"),
("abc", "abc"),
],
)
def test_tqdm_format_num(input_num: Union[str, int, float], expected: str):
"""Check that the specialized tqdm.format_num appends 0 to floats and strings."""
assert Tqdm.format_num(input_num) == expected
| MockTqdm |
python | modin-project__modin | modin/polars/groupby.py | {
"start": 928,
"end": 8170
} | class ____:
def __init__(
self,
df: "DataFrame",
*by,
maintain_order: bool = False,
**named_by,
) -> None:
self.df = df
if len(by) == 1:
self.by = by[0]
else:
if all(isinstance(b, str) and b in self.df.columns for b in by):
self.by = self.df[list(by)]._query_compiler
elif all(isinstance(b, type(self._df._query_compiler)) for b in by):
self.by = by
else:
raise NotImplementedError("not yet")
self.named_by = named_by
self.maintain_order = maintain_order
def agg(self, *aggs, **named_aggs):
raise NotImplementedError("not yet")
def all(self):
raise NotImplementedError("not yet")
def map_groups(self, function) -> "DataFrame":
raise NotImplementedError("not yet")
apply = map_groups
def count(self):
return self.len(name="count")
def first(self) -> "DataFrame":
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_first(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs={},
drop=False,
).reset_index(drop=False)
)
def head(self, n: int = 5):
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_head(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs=dict(n=n),
drop=False,
)
)
def last(self) -> "DataFrame":
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_last(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs={},
drop=False,
).reset_index(drop=False)
)
def len(self, name: str | None = None) -> "DataFrame":
if name is None:
name = "len"
result = self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_size(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs={},
drop=False,
)
)
result._query_compiler.columns = [
c if c != "size" else name for c in result.columns
]
return result
def max(self) -> "DataFrame":
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_max(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs={},
drop=False,
)
)
def mean(self) -> "DataFrame":
# TODO: Non numeric columns are dropped, but in Polars they are converted to null
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_mean(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs=dict(numeric_only=True),
drop=False,
).reset_index(drop=False)
)
def median(self) -> "DataFrame":
# TODO: Non numeric columns are dropped, but in Polars they are converted to null
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_median(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs=dict(numeric_only=True),
drop=False,
).reset_index(drop=False)
)
def min(self) -> "DataFrame":
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_min(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs={},
drop=False,
)
)
def n_unique(self) -> "DataFrame":
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_nunique(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs={},
drop=False,
)
)
def quantile(self, quantile: float, interpolation="nearest") -> "DataFrame":
# TODO: Non numeric columns are dropped, but in Polars they are converted to null
# TODO: interpolation types not yet supported
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_quantile(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs=dict(numeric_only=True, q=quantile),
drop=False,
).reset_index(drop=False)
)
def sum(self) -> "DataFrame":
# TODO: Non numeric columns are dropped, but in Polars they are converted to null
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_sum(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=True,
),
agg_args=(),
agg_kwargs=dict(numeric_only=True),
drop=False,
).reset_index(drop=False)
)
def tail(self, n: int = 5):
return self.df.__constructor__(
_query_compiler=self.df._query_compiler.groupby_tail(
self.by,
axis=0,
groupby_kwargs=dict(
sort=not self.maintain_order,
as_index=False,
),
agg_args=(),
agg_kwargs=dict(n=n),
drop=False,
)
)
| GroupBy |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 8291,
"end": 9092
} | class ____:
"""A symbol holding a reference to a definition.
Attributes:
name: The symbol name
typ: The symbol type (e.g. Attribute)
data: The pytype data attached to the symbol
scope: The namespace id (e.g. module.A.f)
ref_scope: The namespace id of the referred symbol (if we can determine it)
target: The LHS of an attribute (e.g. for x.foo, target = typeof(x))
location: The line and column of the symbol in the source code
id: The id
"""
name: str
typ: Any
data: Any
scope: str
ref_scope: str | None
target: Any
location: source.Location
id: str | None = dataclasses.field(default=None, init=False)
def __post_init__(self):
self.id = self.scope + "." + self.name
def format(self):
return self.id
@dataclasses.dataclass
| Reference |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 558254,
"end": 573943
} | class ____:
# Mixin class containing code common to PrimaryCmpNodes
# and CascadedCmpNodes.
special_bool_cmp_function = None
special_bool_cmp_utility_code = None
special_bool_extra_args = []
def infer_type(self, env):
# TODO: Actually implement this (after merging with -unstable).
return py_object_type
def calculate_cascaded_constant_result(self, operand1_result):
func = compile_time_binary_operators[self.operator]
operand2_result = self.operand2.constant_result
if (isinstance(operand1_result, any_string_type) and
isinstance(operand2_result, any_string_type) and
type(operand1_result) != type(operand2_result)):
# string comparison of different types isn't portable
return
if self.operator in ('in', 'not_in'):
if isinstance(self.operand2, (ListNode, TupleNode, SetNode)):
if not self.operand2.args:
self.constant_result = self.operator == 'not_in'
return
elif isinstance(self.operand2, ListNode) and not self.cascade:
# tuples are more efficient to store than lists
self.operand2 = self.operand2.as_tuple()
elif isinstance(self.operand2, DictNode):
if not self.operand2.key_value_pairs:
self.constant_result = self.operator == 'not_in'
return
self.constant_result = func(operand1_result, operand2_result)
def cascaded_compile_time_value(self, operand1, denv):
func = get_compile_time_binop(self)
operand2 = self.operand2.compile_time_value(denv)
try:
result = func(operand1, operand2)
except Exception as e:
self.compile_time_value_error(e)
result = None
if result:
cascade = self.cascade
if cascade:
result = result and cascade.cascaded_compile_time_value(operand2, denv)
return result
def is_cpp_comparison(self):
return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
def find_common_int_type(self, env, op, operand1, operand2):
# type1 != type2 and at least one of the types is not a C int
type1 = operand1.type
type2 = operand2.type
type1_can_be_int = False
type2_can_be_int = False
if operand1.is_string_literal and operand1.can_coerce_to_char_literal():
type1_can_be_int = True
if operand2.is_string_literal and operand2.can_coerce_to_char_literal():
type2_can_be_int = True
if type1.is_int:
if type2_can_be_int:
return type1
elif type2.is_int:
if type1_can_be_int:
return type2
elif type1_can_be_int:
if type2_can_be_int:
if Builtin.unicode_type in (type1, type2):
return PyrexTypes.c_py_ucs4_type
else:
return PyrexTypes.c_uchar_type
return None
def find_common_type(self, env, op, operand1, common_type=None):
operand2 = self.operand2
type1 = operand1.type
type2 = operand2.type
new_common_type = None
# try to use numeric comparisons where possible
if type1.is_complex or type2.is_complex:
if (op not in ('==', '!=')
and (type1.is_complex or type1.is_numeric)
and (type2.is_complex or type2.is_numeric)):
error(self.pos, "complex types are unordered")
new_common_type = error_type
elif type1.is_pyobject:
new_common_type = Builtin.complex_type if type1.subtype_of(Builtin.complex_type) else py_object_type
elif type2.is_pyobject:
new_common_type = Builtin.complex_type if type2.subtype_of(Builtin.complex_type) else py_object_type
else:
new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
elif type1.is_numeric and type2.is_numeric:
new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
elif common_type is None or not common_type.is_pyobject:
new_common_type = self.find_common_int_type(env, op, operand1, operand2)
if new_common_type is None:
# fall back to generic type compatibility tests
if type1.is_ctuple or type2.is_ctuple:
new_common_type = py_object_type
elif type1 == type2:
new_common_type = type1
elif type1.is_pyobject or type2.is_pyobject:
if type2.is_numeric or type2.is_string:
if operand2.check_for_coercion_error(type1, env):
new_common_type = error_type
else:
new_common_type = py_object_type
elif type1.is_numeric or type1.is_string:
if operand1.check_for_coercion_error(type2, env):
new_common_type = error_type
else:
new_common_type = py_object_type
elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
new_common_type = py_object_type
else:
# one Python type and one non-Python type, not assignable
self.invalid_types_error(operand1, op, operand2)
new_common_type = error_type
elif type1.assignable_from(type2):
new_common_type = type1
elif type2.assignable_from(type1):
new_common_type = type2
else:
# C types that we couldn't handle up to here are an error
self.invalid_types_error(operand1, op, operand2)
new_common_type = error_type
if new_common_type.is_string and (isinstance(operand1, BytesNode) or
isinstance(operand2, BytesNode)):
# special case when comparing char* to bytes literal: must
# compare string values!
new_common_type = bytes_type
# recursively merge types
if common_type is None or new_common_type.is_error:
common_type = new_common_type
else:
# we could do a lot better by splitting the comparison
# into a non-Python part and a Python part, but this is
# safer for now
common_type = PyrexTypes.spanning_type(common_type, new_common_type)
if self.cascade:
common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
return common_type
def invalid_types_error(self, operand1, op, operand2):
error(self.pos, "Invalid types for '%s' (%s, %s)" %
(op, operand1.type, operand2.type))
def is_python_comparison(self):
return (not self.is_ptr_contains()
and not self.is_c_string_contains()
and (self.has_python_operands()
or (self.cascade and self.cascade.is_python_comparison())
or self.operator in ('in', 'not_in')))
def coerce_operands_to(self, dst_type, env):
operand2 = self.operand2
if operand2.type != dst_type:
self.operand2 = operand2.coerce_to(dst_type, env)
if self.cascade:
self.cascade.coerce_operands_to(dst_type, env)
def is_python_result(self):
return ((self.has_python_operands() and
self.special_bool_cmp_function is None and
self.operator not in ('is', 'is_not', 'in', 'not_in') and
not self.is_c_string_contains() and
not self.is_ptr_contains())
or (self.cascade and self.cascade.is_python_result()))
def is_c_string_contains(self):
return self.operator in ('in', 'not_in') and \
((self.operand1.type.is_int
and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
(self.operand1.type.is_unicode_char
and self.operand2.type is unicode_type))
def is_ptr_contains(self):
if self.operator in ('in', 'not_in'):
container_type = self.operand2.type
return (container_type.is_ptr or container_type.is_array) \
and not container_type.is_string
def find_special_bool_compare_function(self, env, operand1, result_is_bool=False):
# note: currently operand1 must get coerced to a Python object if we succeed here!
if self.operator in ('==', '!='):
type1, type2 = operand1.type, self.operand2.type
if result_is_bool or (type1.is_builtin_type and type2.is_builtin_type):
if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
self.special_bool_cmp_utility_code = UtilityCode.load_cached("UnicodeEquals", "StringTools.c")
self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
return True
elif type1 is Builtin.bytes_type or type2 is Builtin.bytes_type:
self.special_bool_cmp_utility_code = UtilityCode.load_cached("BytesEquals", "StringTools.c")
self.special_bool_cmp_function = "__Pyx_PyBytes_Equals"
return True
elif result_is_bool:
from .Optimize import optimise_numeric_binop
result = optimise_numeric_binop(
"Eq" if self.operator == "==" else "Ne",
self,
PyrexTypes.c_bint_type,
operand1,
self.operand2
)
if result:
(self.special_bool_cmp_function,
self.special_bool_cmp_utility_code,
self.special_bool_extra_args,
_) = result
return True
elif self.operator in ('in', 'not_in'):
if self.operand2.type is Builtin.dict_type:
self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
self.special_bool_cmp_utility_code = UtilityCode.load_cached("PyDictContains", "ObjectHandling.c")
self.special_bool_cmp_function = "__Pyx_PyDict_ContainsTF"
return True
elif self.operand2.type is Builtin.set_type:
self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
self.special_bool_cmp_utility_code = UtilityCode.load_cached("PySetContains", "ObjectHandling.c")
self.special_bool_cmp_function = "__Pyx_PySet_ContainsTF"
return True
elif self.operand2.type is Builtin.unicode_type:
self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
self.special_bool_cmp_utility_code = UtilityCode.load_cached("PyUnicodeContains", "StringTools.c")
self.special_bool_cmp_function = "__Pyx_PyUnicode_ContainsTF"
return True
else:
if not self.operand2.type.is_pyobject:
self.operand2 = self.operand2.coerce_to_pyobject(env)
self.special_bool_cmp_utility_code = UtilityCode.load_cached("PySequenceContains", "ObjectHandling.c")
self.special_bool_cmp_function = "__Pyx_PySequence_ContainsTF"
return True
return False
def generate_operation_code(self, code, result_code,
operand1, op, operand2):
if self.type.is_pyobject:
error_clause = code.error_goto_if_null
got_ref = "__Pyx_XGOTREF(%s); " % result_code
if self.special_bool_cmp_function:
code.globalstate.use_utility_code(
UtilityCode.load_cached("PyBoolOrNullFromLong", "ObjectHandling.c"))
coerce_result = "__Pyx_PyBoolOrNull_FromLong"
else:
coerce_result = "__Pyx_PyBool_FromLong"
else:
error_clause = code.error_goto_if_neg
got_ref = ""
coerce_result = ""
if self.special_bool_cmp_function:
if operand1.type.is_pyobject:
result1 = operand1.py_result()
else:
result1 = operand1.result()
if operand2.type.is_pyobject:
result2 = operand2.py_result()
else:
result2 = operand2.result()
special_bool_extra_args_result = ", ".join([
extra_arg.result() for extra_arg in self.special_bool_extra_args
])
if self.special_bool_cmp_utility_code:
code.globalstate.use_utility_code(self.special_bool_cmp_utility_code)
code.putln(
"%s = %s(%s(%s, %s, %s)); %s%s" % (
result_code,
coerce_result,
self.special_bool_cmp_function,
result1, result2,
special_bool_extra_args_result if self.special_bool_extra_args else richcmp_constants[op],
got_ref,
error_clause(result_code, self.pos)))
elif operand1.type.is_pyobject and op not in ('is', 'is_not'):
assert op not in ('in', 'not_in'), op
assert self.type.is_pyobject or self.type is PyrexTypes.c_bint_type
code.putln("%s = PyObject_RichCompare%s(%s, %s, %s); %s%s" % (
result_code,
"" if self.type.is_pyobject else "Bool",
operand1.py_result(),
operand2.py_result(),
richcmp_constants[op],
got_ref,
error_clause(result_code, self.pos)))
elif operand1.type.is_complex:
code.putln("%s = %s(%s%s(%s, %s));" % (
result_code,
coerce_result,
op == "!=" and "!" or "",
operand1.type.unary_op('eq'),
operand1.result(),
operand2.result()))
else:
type1 = operand1.type
type2 = operand2.type
if (type1.is_extension_type or type2.is_extension_type) \
and not type1.same_as(type2):
common_type = py_object_type
elif type1.is_numeric:
common_type = PyrexTypes.widest_numeric_type(type1, type2)
else:
common_type = type1
code1 = operand1.result_as(common_type)
code2 = operand2.result_as(common_type)
statement = "%s = %s(%s %s %s);" % (
result_code,
coerce_result,
code1,
self.c_operator(op),
code2)
if self.is_cpp_comparison() and self.exception_check == '+':
translate_cpp_exception(
code,
self.pos,
statement,
result_code if self.type.is_pyobject else None,
self.exception_value,
self.in_nogil_context)
else:
code.putln(statement)
def c_operator(self, op):
if op == 'is':
return "=="
elif op == 'is_not':
return "!="
else:
return op
| CmpNode |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py | {
"start": 8552,
"end": 10575
} | class ____(object):
"""
Base file system event handler that you can override methods from.
"""
def dispatch(self, event):
"""Dispatches events to the appropriate methods.
:param event:
The event object representing the file system event.
:type event:
:class:`FileSystemEvent`
"""
self.on_any_event(event)
_method_map = {
EVENT_TYPE_MODIFIED: self.on_modified,
EVENT_TYPE_MOVED: self.on_moved,
EVENT_TYPE_CREATED: self.on_created,
EVENT_TYPE_DELETED: self.on_deleted,
}
event_type = event.event_type
_method_map[event_type](event)
def on_any_event(self, event):
"""Catch-all event handler.
:param event:
The event object representing the file system event.
:type event:
:class:`FileSystemEvent`
"""
def on_moved(self, event):
"""Called when a file or a directory is moved or renamed.
:param event:
Event representing file/directory movement.
:type event:
:class:`DirMovedEvent` or :class:`FileMovedEvent`
"""
def on_created(self, event):
"""Called when a file or directory is created.
:param event:
Event representing file/directory creation.
:type event:
:class:`DirCreatedEvent` or :class:`FileCreatedEvent`
"""
def on_deleted(self, event):
"""Called when a file or directory is deleted.
:param event:
Event representing file/directory deletion.
:type event:
:class:`DirDeletedEvent` or :class:`FileDeletedEvent`
"""
def on_modified(self, event):
"""Called when a file or directory is modified.
:param event:
Event representing file/directory modification.
:type event:
:class:`DirModifiedEvent` or :class:`FileModifiedEvent`
"""
| FileSystemEventHandler |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_values_test.py | {
"start": 2874,
"end": 3945
} | class ____(test.TestCase, parameterized.TestCase):
config = config_pb2.ConfigProto()
config.allow_soft_placement = True
def tearDown(self):
super().tearDown()
context._reset_context()
@test_util.run_in_graph_and_eager_modes(config=config)
def testProperties(self):
if context.num_gpus() < 1 and context.executing_eagerly():
self.skipTest("A GPU is not available for this test in eager mode.")
mirrored = _make_mirrored()
v = mirrored.values[0]
self.assertEqual(v.name, mirrored.name)
self.assertEqual(v.dtype, mirrored.dtype)
self.assertEqual(v.shape, mirrored.shape)
@test_util.run_in_graph_and_eager_modes(config=config)
def testVariableOnAnotherDevice(self):
v = variable_scope.get_variable(
name="v", initializer=[1.], use_resource=True)
mirrored = values_lib.MirroredVariable(
None, (v,), variable_scope.VariableAggregation.MEAN)
self.assertEqual(v.name, mirrored.name)
self.assertEqual(v.dtype, mirrored.dtype)
self.assertEqual(v.shape, mirrored.shape)
| MirroredVariableTest |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 17027,
"end": 18055
} | class ____(Benchmark):
param_names = ['size']
params = [[10, 100, 1000, 10000]]
def setup(self, size):
num_rows = 4
num_cols = 3
self.df = 5
self.M = np.full((num_rows,num_cols), 0.3)
self.U = 0.5 * np.identity(num_rows) + np.full(
(num_rows, num_rows), 0.5
)
self.V = 0.7 * np.identity(num_cols) + np.full(
(num_cols, num_cols), 0.3
)
self.rng = np.random.default_rng(42)
def time_matrix_normal(self, size):
stats.matrix_normal.rvs(mean=self.M, rowcov=self.U,
colcov=self.V, size=size, random_state=self.rng)
def time_invwishart(self, size):
stats.invwishart.rvs(df=self.df, scale=self.V,
size=size, random_state=self.rng)
def time_matrix_t(self, size):
stats.matrix_t.rvs(mean=self.M, row_spread=self.U, col_spread=self.V,
df=self.df, size=size, random_state=self.rng)
| MatrixSampling |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 420,
"end": 660
} | class ____(BaseEvent):
"""Event emitted when the total number of pages to process is determined."""
total_pages: int
@classmethod
def class_name(cls) -> str:
return "TotalPagesToProcessEvent"
| TotalPagesToProcessEvent |
python | zostera__django-bootstrap4 | example/app/forms.py | {
"start": 3146,
"end": 3450
} | class ____(forms.Form):
text1 = forms.CharField()
file1 = forms.FileField()
file2 = forms.FileField(required=False)
file3 = forms.FileField(widget=forms.ClearableFileInput)
file5 = forms.ImageField()
file4 = forms.FileField(required=False, widget=forms.ClearableFileInput)
| FilesForm |
python | pypa__warehouse | tests/functional/manage/test_account_publishing.py | {
"start": 388,
"end": 6401
} | class ____:
@responses.activate
def test_add_pending_github_publisher_succeeds(self, webtest):
"""
An authenticated user add a new pending GitHub publisher
via the form on their account publishing page.
"""
# Arrange: Create a user with verified email
user = UserFactory.create(
with_verified_primary_email=True,
with_terms_of_service_agreement=True,
clear_pwd="password",
)
UserUniqueLoginFactory.create(
user=user, ip_address=REMOTE_ADDR, status=UniqueLoginStatus.CONFIRMED
)
# Create a response from GitHub API for owner details
# during form submission validation.
responses.add(
responses.GET,
"https://api.github.com/users/test-owner",
json={
"id": 123456,
"login": "test-owner",
},
status=200,
)
# Act: Log in
login_page = webtest.get("/account/login/", status=HTTPStatus.OK)
login_form = login_page.forms["login-form"]
csrf_token = login_form["csrf_token"].value
login_form["username"] = user.username
login_form["password"] = "password"
# Handle 2FA
two_factor_page = login_form.submit().follow(status=HTTPStatus.OK)
two_factor_form = two_factor_page.forms["totp-auth-form"]
two_factor_form["csrf_token"] = csrf_token
two_factor_form["totp_value"] = (
_get_totp(user.totp_secret).generate(time.time()).decode()
)
two_factor_form.submit().follow(status=HTTPStatus.OK)
# Navigate to publishing page
publishing_page = webtest.get(
"/manage/account/publishing/", status=HTTPStatus.OK
)
# Get logged-in CSRF token
logged_in_csrf_token = publishing_page.html.find(
"input", {"name": "csrf_token"}
)["value"]
# Fill out the GitHub publisher form
github_form = publishing_page.forms["pending-github-publisher-form"]
github_form["csrf_token"] = logged_in_csrf_token
github_form["project_name"] = "test-project"
github_form["owner"] = "test-owner"
github_form["repository"] = "test-repo"
github_form["workflow_filename"] = "release.yml"
# Submit the form, redirects back to the same page on success
response = github_form.submit(status=HTTPStatus.SEE_OTHER)
# Follow the redirect and verify the page loads
response.follow(status=HTTPStatus.OK)
# Assert: Verify success
# Check flash messages via the JavaScript endpoint
# Note: Despite the "unauthed" path, this endpoint shows session flash
# messages for any user (authed or unauthed). The name is misleading.
# WebTest maintains session cookies, so the flash message is available.
flash_messages = webtest.get(
"/_includes/unauthed/flash-messages/", status=HTTPStatus.OK
)
success_message = flash_messages.html.find(
"span", {"class": "notification-bar__message"}
)
assert success_message is not None
assert "Registered a new pending publisher" in success_message.text
assert "test-project" in success_message.text
def test_add_pending_gitlab_publisher_succeeds(self, webtest):
"""
An authenticated user can add a new Pending GitLab publisher
via the form on their account publishing page.
"""
# Arrange: Create a user with verified email
user = UserFactory.create(
with_verified_primary_email=True,
with_terms_of_service_agreement=True,
clear_pwd="password",
)
UserUniqueLoginFactory.create(
user=user, ip_address=REMOTE_ADDR, status=UniqueLoginStatus.CONFIRMED
)
# Act: Log in
login_page = webtest.get("/account/login/", status=HTTPStatus.OK)
login_form = login_page.forms["login-form"]
csrf_token = login_form["csrf_token"].value
login_form["username"] = user.username
login_form["password"] = "password"
# Handle 2FA
two_factor_page = login_form.submit().follow(status=HTTPStatus.OK)
two_factor_form = two_factor_page.forms["totp-auth-form"]
two_factor_form["csrf_token"] = csrf_token
two_factor_form["totp_value"] = (
_get_totp(user.totp_secret).generate(time.time()).decode()
)
two_factor_form.submit().follow(status=HTTPStatus.OK)
# Navigate to publishing page
publishing_page = webtest.get(
"/manage/account/publishing/", status=HTTPStatus.OK
)
# Get logged-in CSRF token
logged_in_csrf_token = publishing_page.html.find(
"input", {"name": "csrf_token"}
)["value"]
# Fill out the GitLab publisher form
gitlab_form = publishing_page.forms["pending-gitlab-publisher-form"]
gitlab_form["csrf_token"] = logged_in_csrf_token
gitlab_form["project_name"] = "gitlab-project"
gitlab_form["namespace"] = "gitlab-namespace"
gitlab_form["project"] = "gitlab-project"
gitlab_form["workflow_filepath"] = "ci.yml"
# Submit the form
response = gitlab_form.submit(status=HTTPStatus.SEE_OTHER)
# Follow the redirect and verify the page loads
response.follow(status=HTTPStatus.OK)
# Assert: Verify success
# Check flash messages via the JavaScript endpoint
flash_messages = webtest.get(
"/_includes/unauthed/flash-messages/", status=HTTPStatus.OK
)
success_message = flash_messages.html.find(
"span", {"class": "notification-bar__message"}
)
assert success_message is not None
assert "Registered a new pending publisher" in success_message.text
assert "gitlab-project" in success_message.text
| TestManageAccountPublishing |
python | getsentry__sentry | src/sentry/utils/circuit_breaker.py | {
"start": 499,
"end": 588
} | class ____(TypedDict, total=True):
limit: int
window: int
| CircuitBreakerPassthrough |
python | django-guardian__django-guardian | guardian/testapp/migrations/0005_uuidpkmodel.py | {
"start": 105,
"end": 486
} | class ____(migrations.Migration):
dependencies = [
("testapp", "0004_childtestmodel_parenttestmodel"),
]
operations = [
migrations.CreateModel(
name="UUIDPKModel",
fields=[
("uuid_pk", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
],
),
]
| Migration |
python | pytorch__pytorch | torch/fx/experimental/partitioner_utils.py | {
"start": 2830,
"end": 12295
} | class ____(NamedTuple):
devices: list[Device]
mode: PartitionMode = PartitionMode.size_based
transfer_rate_bytes_per_sec: float = 0.0
node_to_latency_mapping: dict[Node, NodeLatency] = {}
node_to_partition_mapping: dict[Node, int] = {}
partition_to_logical_device_mapping: dict[int, list[int]] = {}
# Saturate host by replicating partitions to the remaining idle devices.
saturate_host: bool = False
def get_extra_size_of(node: Node, nodes: set[Node]) -> int:
"""Given a node and a set of nodes,
this function return the extra size that needed
if this node is included in this set.
"""
# Find all its input nodes
input_nodes: dict[Node, None] = {}
map_arg(node.args, input_nodes.setdefault)
map_arg(node.kwargs, input_nodes.setdefault)
# Calculate total size of related nodes
total_size_of_input_nodes = 0
for n in input_nodes:
# Make sure this node hasn't been in this set yet
if n not in nodes:
size_bytes = getattr(n, "size_bytes", None)
if size_bytes:
total_size_of_input_nodes += size_bytes.output_size
else:
raise RuntimeError("node has no size_bytes attr")
# Don't forget the op node itself
size_bytes = getattr(node, "size_bytes", None)
if size_bytes:
total_size_of_input_nodes += size_bytes.total_size
else:
raise RuntimeError("node has no size_bytes attr")
return total_size_of_input_nodes
def get_latency_of_one_partition(
partition: Partition, node_to_latency_mapping: dict[Node, NodeLatency]
) -> PartitionLatency:
"""Given a partition and its nodes' latency, return a PartitionLatency for this partition"""
def get_top_nodes(partition: Partition) -> list[Node]:
"""Given a partition, return a list of nodes on the top bfs level"""
top_nodes: list[Node] = []
for node in partition.nodes:
# Skip placeholder and get_attr nodes
if node.op in {"placeholder", "get_attr"}:
continue
input_nodes: dict[Node, None] = {}
map_arg(node.args, input_nodes.setdefault)
map_arg(node.kwargs, input_nodes.setdefault)
# If a node has no input nodes in this partition,
# or its input nodes in this partition are placeholders and get_attrs
# this node is on the top bfs level in this partition
if not any(
n in partition.nodes and n.op not in {"placeholder", "get_attr"}
for n in input_nodes
):
top_nodes.append(node)
return top_nodes
def dfs_helper(node: Node, partition_latency) -> PartitionLatency:
"""Given a top node of a partition, this function returns
the latency of the critical path in the partition
"""
node_latency = node_to_latency_mapping[node]
# Calculate the current overall latency of the partition
overall_latency_sec = partition_latency.overall_latency_sec + max(
node_latency.computer_latency_sec, node_latency.mem_latency_sec
)
# Update the mem latency of this path
mem_latency_sec = (
partition_latency.mem_latency_sec + node_latency.mem_latency_sec
)
# Update the compute latency of this path
computer_latency_sec = (
partition_latency.computer_latency_sec + node_latency.computer_latency_sec
)
# Get all users of this node that are in this partition
users = set(node.users).intersection(partition.nodes)
if users:
max_latency = PartitionLatency(
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
)
for n in users:
# Get new partition latency recursively
new_partition_latency = dfs_helper(
n,
PartitionLatency(
mem_latency_sec, computer_latency_sec, overall_latency_sec
),
)
if (
new_partition_latency.overall_latency_sec
> max_latency.overall_latency_sec
):
max_latency = new_partition_latency
return max_latency
# If there is no user, the node is at bottom of the partition
return PartitionLatency(
mem_latency_sec, computer_latency_sec, overall_latency_sec
)
# Main part starts
# Get all top level nodes of this partition
top_nodes = get_top_nodes(partition)
critical_path_latency = PartitionLatency(
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
)
# Go through all top nodes and find the largest latency (critical pass latency)
for node in top_nodes:
partition_latency = dfs_helper(
node,
PartitionLatency(
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
),
)
if (
partition_latency.overall_latency_sec
> critical_path_latency.overall_latency_sec
):
critical_path_latency = partition_latency
return critical_path_latency
def get_partition_to_latency_mapping(
partitions: list[Partition], node_to_latency_mapping: dict[Node, NodeLatency]
) -> dict[Partition, PartitionLatency]:
"""Given all the partitions and node_to_latency_mapping dictionary,
return a mapping dictionary of each partition to its overall latency
"""
partition_to_latency_mapping: dict[Partition, PartitionLatency] = {}
# Go through each partition and get its latency
for partition in partitions:
partition_latency = get_latency_of_one_partition(
partition, node_to_latency_mapping
)
partition_to_latency_mapping[partition] = partition_latency
return partition_to_latency_mapping
def get_comm_latency_between(
parent_partition: Partition,
child_partition: Partition,
transfer_rate_bytes_per_sec: float,
):
"""Given two partitions (parent and child),
calculate the communication latency between the two.
"""
# If two partitions are on the same device, the comm latency is 0.
if (
parent_partition.logical_device_ids != []
and child_partition.logical_device_ids != []
and parent_partition.logical_device_ids == child_partition.logical_device_ids
):
return 0.0
# Keep tracking the communication size between parent and child
comm_size = 0
# Keep tracking all the counted node
visited_nodes = set()
# Go through all nodes in the child partition
# If a node has input nodes from the parent partition,
# the output size of those input nodes will be counted
# and added to comm_size
for node in child_partition.nodes:
input_nodes: dict[Node, None] = {}
map_arg(node.args, input_nodes.setdefault)
map_arg(node.kwargs, input_nodes.setdefault)
for n in input_nodes:
if n in parent_partition.nodes and n not in visited_nodes:
size_bytes = getattr(n, "size_bytes", None)
if size_bytes is not None:
comm_size += size_bytes.output_size
visited_nodes.add(n)
return comm_size / transfer_rate_bytes_per_sec
def get_latency_of_partitioned_graph(
partitions: list[Partition],
partition_to_latency_mapping: dict[Partition, PartitionLatency],
transfer_rate_bytes_per_sec: float,
):
"""Given all partitions in a graph, find the critical path among all partitions
and return its latency as the latency of the whole graph
"""
def dfs_helper(partition: Partition, latency_so_far_sec: float) -> float:
"""This function helps to recursively get the latency of a path of partitions"""
# Update latency by adding current partition's latency
latency_so_far_sec += partition_to_latency_mapping[
partition
].overall_latency_sec
if partition.children:
max_latency_sec = 0.0
for child in partition.children:
# Calculate latency between
comm_latency_sec = get_comm_latency_between(
partition, child, transfer_rate_bytes_per_sec
)
new_latency_sec = dfs_helper(
child, latency_so_far_sec + comm_latency_sec
)
if new_latency_sec > max_latency_sec:
max_latency_sec = new_latency_sec
return max_latency_sec
return latency_so_far_sec
def get_top_partitions(partitions: list[Partition]) -> list[Partition]:
"""This function is to return all the partitions without parents
as the starting points of all the paths
"""
# If a partition has no parents, then it is a top partition
top_partitions = [
partition for partition in partitions if len(partition.parents) == 0
]
return top_partitions
top_partitions = get_top_partitions(partitions)
critical_path_latency_sec = 0.0
for partition in top_partitions:
latency_sec = dfs_helper(partition, 0.0)
if latency_sec > critical_path_latency_sec:
critical_path_latency_sec = latency_sec
return critical_path_latency_sec
| PartitionerConfig |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/normalization.py | {
"start": 2339,
"end": 4123
} | class ____(torch.nn.GroupNorm):
r"""This is the quantized version of :class:`~torch.nn.GroupNorm`.
Additional args:
* **scale** - quantization scale of the output, type: double.
* **zero_point** - quantization zero point of the output, type: long.
"""
__constants__ = ["num_groups", "num_channels", "eps", "affine"]
def __init__(
self,
num_groups,
num_channels,
weight,
bias,
scale,
zero_point,
eps=1e-5,
affine=True,
device=None,
dtype=None,
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super().__init__(num_groups, num_channels, eps, affine, **factory_kwargs)
self.weight = weight
self.bias = bias
# pyrefly: ignore [bad-argument-type]
self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
# pyrefly: ignore [bad-argument-type]
self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
def forward(self, input):
return torch.ops.quantized.group_norm(
input,
self.num_groups,
self.weight,
self.bias,
self.eps,
self.scale,
self.zero_point,
)
def _get_name(self):
return "QuantizedGroupNorm"
@classmethod
def from_float(cls, mod, use_precomputed_fake_quant=False):
scale, zero_point = mod.activation_post_process.calculate_qparams()
new_mod = cls(
mod.num_groups,
mod.num_channels,
mod.weight,
mod.bias,
float(scale),
int(zero_point),
mod.eps,
mod.affine,
)
return new_mod
| GroupNorm |
python | coleifer__peewee | tests/fields.py | {
"start": 3086,
"end": 3181
} | class ____(TestModel):
value = FloatField()
value_null = FloatField(null=True)
| FloatModel |
python | wandb__wandb | wandb/vendor/pygments/lexers/matlab.py | {
"start": 26640,
"end": 29146
} | class ____(RegexLexer):
"""
For Scilab source code.
.. versionadded:: 1.5
"""
name = 'Scilab'
aliases = ['scilab']
filenames = ['*.sci', '*.sce', '*.tst']
mimetypes = ['text/scilab']
tokens = {
'root': [
(r'//.*?$', Comment.Single),
(r'^\s*function', Keyword, 'deffunc'),
(words((
'__FILE__', '__LINE__', 'break', 'case', 'catch', 'classdef', 'continue', 'do', 'else',
'elseif', 'end', 'end_try_catch', 'end_unwind_protect', 'endclassdef',
'endevents', 'endfor', 'endfunction', 'endif', 'endmethods', 'endproperties',
'endswitch', 'endwhile', 'events', 'for', 'function', 'get', 'global', 'if', 'methods',
'otherwise', 'persistent', 'properties', 'return', 'set', 'static', 'switch', 'try',
'until', 'unwind_protect', 'unwind_protect_cleanup', 'while'), suffix=r'\b'),
Keyword),
(words(_scilab_builtins.functions_kw +
_scilab_builtins.commands_kw +
_scilab_builtins.macros_kw, suffix=r'\b'), Name.Builtin),
(words(_scilab_builtins.variables_kw, suffix=r'\b'), Name.Constant),
# operators:
(r'-|==|~=|<|>|<=|>=|&&|&|~|\|\|?', Operator),
# operators requiring escape for re:
(r'\.\*|\*|\+|\.\^|\.\\|\.\/|\/|\\', Operator),
# punctuation:
(r'[\[\](){}@.,=:;]', Punctuation),
(r'"[^"]*"', String),
# quote can be transpose, instead of string:
# (not great, but handles common cases...)
(r'(?<=[\w)\].])\'+', Operator),
(r'(?<![\w)\].])\'', String, 'string'),
(r'(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?', Number.Float),
(r'\d+[eEf][+-]?[0-9]+', Number.Float),
(r'\d+', Number.Integer),
(r'[a-zA-Z_]\w*', Name),
(r'.', Text),
],
'string': [
(r"[^']*'", String, '#pop'),
(r'.', String, '#pop'),
],
'deffunc': [
(r'(\s*)(?:(.+)(\s*)(=)(\s*))?(.+)(\()(.*)(\))(\s*)',
bygroups(Whitespace, Text, Whitespace, Punctuation,
Whitespace, Name.Function, Punctuation, Text,
Punctuation, Whitespace), '#pop'),
# function with no args
(r'(\s*)([a-zA-Z_]\w*)', bygroups(Text, Name.Function), '#pop'),
],
}
| ScilabLexer |
python | jd__tenacity | tenacity/__init__.py | {
"start": 3613,
"end": 4104
} | class ____:
actions: t.List[t.Callable[["RetryCallState"], t.Any]] = dataclasses.field(
default_factory=list
)
retry_run_result: bool = False
delay_since_first_attempt: int = 0
stop_run_result: bool = False
is_explicit_retry: bool = False
def reset(self) -> None:
self.actions = []
self.retry_run_result = False
self.delay_since_first_attempt = 0
self.stop_run_result = False
self.is_explicit_retry = False
| IterState |
python | plotly__plotly.py | plotly/graph_objs/sankey/node/_hoverlabel.py | {
"start": 233,
"end": 11269
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sankey.node"
_path_str = "sankey.node.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
"showarrow",
}
@property
def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `align`.
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"]
@alignsrc.setter
def alignsrc(self, val):
self["alignsrc"] = val
@property
def bgcolor(self):
"""
Sets the background color of the hover labels for this trace
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bgcolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `bgcolor`.
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bgcolorsrc"]
@bgcolorsrc.setter
def bgcolorsrc(self, val):
self["bgcolorsrc"] = val
@property
def bordercolor(self):
"""
Sets the border color of the hover labels for this trace.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def bordercolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bordercolorsrc"]
@bordercolorsrc.setter
def bordercolorsrc(self, val):
self["bordercolorsrc"] = val
@property
def font(self):
"""
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.sankey.node.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.sankey.node.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def namelength(self):
"""
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["namelength"]
@namelength.setter
def namelength(self, val):
self["namelength"] = val
@property
def namelengthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`namelength`.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["namelengthsrc"]
@namelengthsrc.setter
def namelengthsrc(self, val):
self["namelengthsrc"] = val
@property
def showarrow(self):
"""
Sets whether or not to show the hover label arrow/triangle
pointing to the data point.
The 'showarrow' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showarrow"]
@showarrow.setter
def showarrow(self, val):
self["showarrow"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
"""
def __init__(
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
showarrow=None,
**kwargs,
):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sankey.node.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
Returns
-------
Hoverlabel
"""
super().__init__("hoverlabel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.sankey.node.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sankey.node.Hoverlabel`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("alignsrc", arg, alignsrc)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bgcolorsrc", arg, bgcolorsrc)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("bordercolorsrc", arg, bordercolorsrc)
self._set_property("font", arg, font)
self._set_property("namelength", arg, namelength)
self._set_property("namelengthsrc", arg, namelengthsrc)
self._set_property("showarrow", arg, showarrow)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Hoverlabel |
python | PyCQA__pylint | tests/functional/n/no/no_member_if_statements.py | {
"start": 523,
"end": 1832
} | class ____:
_attr_state: Union[str, datetime] = "Unknown"
@property
def state(self) -> Union[str, datetime]:
return self._attr_state
def some_function(self) -> str:
state = self.state
if isinstance(state, datetime):
return state.isoformat()
return str(state)
# https://github.com/pylint-dev/pylint/issues/1990
# Attribute access after 'isinstance' should not cause 'no-member' error
import subprocess # pylint: disable=wrong-import-position # noqa: E402
try:
subprocess.check_call(['ls', '-']) # Deliberately made error in this line
except Exception as err:
if isinstance(err, subprocess.CalledProcessError):
print(f'Subprocess error occurred. Return code: {err.returncode}')
else:
print(f'An error occurred: {str(err)}')
raise
# https://github.com/pylint-dev/pylint/issues/4168
# 'encode' for 'arg' should not cause 'no-member' error
mixed_tuple = (b"a", b"b", b"c", b"d")
byte_tuple = [arg.encode('utf8') if isinstance(arg, str) else arg for arg in mixed_tuple]
for arg in mixed_tuple:
if isinstance(arg, str):
print(arg.encode('utf8'))
else:
print(arg)
# https://github.com/pylint-dev/pylint/issues/1162
# Attribute access after 'isinstance' should not cause 'no-member' error
| Base |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 16848,
"end": 17268
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.httpexceptions import HTTPForbidden
return HTTPForbidden(*arg, **kw)
def test_it_result_not_passed(self):
exc = self._makeOne()
self.assertEqual(exc.result, None)
def test_it_result_passed(self):
exc = self._makeOne(result='foo')
self.assertEqual(exc.result, 'foo')
| TestHTTPForbidden |
python | pytorch__pytorch | tools/testing/target_determination/heuristics/llm.py | {
"start": 520,
"end": 1840
} | class ____(HeuristicInterface):
def __init__(self, **kwargs: dict[str, Any]) -> None:
super().__init__(**kwargs)
def get_prediction_confidence(self, tests: list[str]) -> TestPrioritizations:
critical_tests = self.get_mappings()
filter_valid_tests = {
TestRun(test): score
for test, score in critical_tests.items()
if test in tests
}
normalized_scores = normalize_ratings(filter_valid_tests, 0.25)
return TestPrioritizations(tests, normalized_scores)
def get_mappings(self) -> dict[str, float]:
path = (
REPO_ROOT
/ ADDITIONAL_CI_FILES_FOLDER
/ "llm_results/mappings/indexer-files-gitdiff-output.json"
)
if not os.path.exists(path):
print(f"could not find path {path}")
return {}
with open(path) as f:
# Group by file
r = defaultdict(list)
for key, value in json.load(f).items():
re_match = re.match("(.*).py", key)
if re_match:
file = re_match.group(1)
r[file].append(value)
# Average the scores for each file
r = {file: sum(scores) / len(scores) for file, scores in r.items()}
return r
| LLM |
python | getsentry__sentry | src/sentry/replays/endpoints/organization_replay_selector_index.py | {
"start": 2134,
"end": 2322
} | class ____(TypedDict, total=False):
count_dead_clicks: int
count_rage_clicks: int
dom_element: str
element: ElementResponseType
project_id: str
| ReplaySelectorResponseData |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 24600,
"end": 32527
} | class ____(PreTrainedModel):
config: ModernBertConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["ModernBertEmbeddings", "ModernBertEncoderLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = False
@torch.no_grad()
def _init_weights(self, module: nn.Module):
cutoff_factor = self.config.initializer_cutoff_factor
if cutoff_factor is None:
cutoff_factor = 3
def init_weight(module: nn.Module, std: float):
init.trunc_normal_(
module.weight,
mean=0.0,
std=std,
a=-cutoff_factor * std,
b=cutoff_factor * std,
)
if isinstance(module, nn.Linear):
if module.bias is not None:
init.zeros_(module.bias)
stds = {
"in": self.config.initializer_range,
"out": self.config.initializer_range / math.sqrt(2.0 * self.config.num_hidden_layers),
"embedding": self.config.initializer_range,
"final_out": self.config.hidden_size**-0.5,
}
if isinstance(module, ModernBertEmbeddings):
init_weight(module.tok_embeddings, stds["embedding"])
elif isinstance(module, ModernBertMLP):
init_weight(module.Wi, stds["in"])
init_weight(module.Wo, stds["out"])
elif isinstance(module, ModernBertAttention):
init_weight(module.Wqkv, stds["in"])
init_weight(module.Wo, stds["out"])
elif isinstance(module, ModernBertPredictionHead):
init_weight(module.dense, stds["out"])
elif isinstance(module, ModernBertForMaskedLM):
init_weight(module.decoder, stds["out"])
elif isinstance(
module,
(
ModernBertForSequenceClassification,
ModernBertForMultipleChoice,
ModernBertForTokenClassification,
ModernBertForQuestionAnswering,
),
):
init_weight(module.classifier, stds["final_out"])
elif isinstance(module, nn.LayerNorm):
init.ones_(module.weight)
if module.bias is not None:
init.zeros_(module.bias)
def _check_and_adjust_attn_implementation(
self, attn_implementation: Optional[str], is_init_check: bool = False
) -> str:
"""
Checks and dispatches to hhe requested attention implementation.
"""
# If the user didn't specify anything, try to use flash_attention_2 if available.
# Otherwise we fall back to the default SDPA -> Eager from the super() method.
# ModernBert's FA2 implementation correctly handles non-fp16/bf16 dtypes, we don't
# need the FA2 warning for non-fp16/bf16 dtypes so we set fp16 for the FA2 check.
try:
attn_implementation = (
"flash_attention_2"
if attn_implementation is None and self._flash_attn_2_can_dispatch()
else attn_implementation
)
except (ValueError, ImportError):
pass
return super()._check_and_adjust_attn_implementation(
attn_implementation=attn_implementation, is_init_check=is_init_check
)
def _maybe_set_compile(self):
if self.config.reference_compile is False:
return
if hasattr(self, "hf_device_map") and len(self.hf_device_map) > 1:
if self.config.reference_compile:
logger.warning_once(
"If `accelerate` split the model across devices, `torch.compile` will not work. "
"Falling back to non-compiled mode."
)
self.config.reference_compile = False
if self.device.type == "mps":
if self.config.reference_compile:
logger.warning_once(
"Compiling the model with `torch.compile` and using a `torch.mps` device is not supported. "
"Falling back to non-compiled mode."
)
self.config.reference_compile = False
if self.device.type == "cpu":
if self.config.reference_compile:
logger.warning_once(
"Compiling the model with `torch.compile` and using a `torch.cpu` device is not supported. "
"Falling back to non-compiled mode."
)
self.config.reference_compile = False
if self.config.reference_compile is None:
self.config.reference_compile = is_triton_available()
def resize_token_embeddings(self, *args, **kwargs):
model_embeds = super().resize_token_embeddings(*args, **kwargs)
if self.config.reference_compile in {True, None}:
if self.config.reference_compile:
logger.warning_once(
"Resizing token embeddings with `torch.compile` is not supported. Falling back to non-compiled mode."
)
self.config.reference_compile = False
return model_embeds
def _unpad_modernbert_input(
inputs: torch.Tensor,
attention_mask: torch.Tensor,
position_ids: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Remove padding from input sequences.
Args:
inputs: (batch, seqlen, ...) or (batch, seqlen)
attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
position_ids: (batch, seqlen), int, position ids
labels: (batch, seqlen), int, labels
Returns:
unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask.
indices: (total_nnz)
cu_seqlens: (batch + 1), the cumulative sequence lengths
max_seqlen_in_batch: int
unpadded_position_ids: (total_nnz) or None
unpadded_labels: (total_nnz) or None
"""
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen_in_batch = int(seqlens_in_batch.max().item())
cu_seqlens = torch.nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
if inputs.dim() == 2:
unpadded_inputs = inputs.flatten()[indices]
else:
batch, seqlen, *rest = inputs.shape
shape = batch * seqlen
unpadded_inputs = inputs.view(shape, *rest)[indices]
unpadded_position_ids = position_ids.flatten()[indices] if position_ids is not None else None
unpadded_labels = labels.flatten()[indices] if labels is not None else None
return unpadded_inputs, indices, cu_seqlens, max_seqlen_in_batch, unpadded_position_ids, unpadded_labels
def _pad_modernbert_output(
inputs: torch.Tensor,
indices: torch.Tensor,
batch: int,
seqlen: int,
) -> torch.Tensor:
"""
Add padding to sequences.
Args:
inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
indices: (total_nnz)
batch: int, batch size
seqlen: int, max sequence length
Returns:
padded_inputs: (batch, seqlen, ...) or (batch, seqlen)
"""
if inputs.dim() == 1:
output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
output[indices] = inputs
padded_inputs = output.view(batch, seqlen)
else:
_, *rest = inputs.shape
output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device)
output[indices] = inputs
padded_inputs = output.view(batch, seqlen, *rest)
return padded_inputs
@auto_docstring
| ModernBertPreTrainedModel |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_kolmogoro_smirnov_test_p_value_to_be_greater_than.py | {
"start": 622,
"end": 2143
} | class ____(TableMetricProvider):
# This is the id string that will be used to reference your Metric.
metric_name = "column.p_value_greater_than_threshold"
value_keys = (
"column_a",
"column_b",
)
# This method implements the core logic for the PandasExecutionEngine
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine,
metric_domain_kwargs,
metric_value_kwargs,
metrics,
runtime_configuration,
):
df, _, _ = execution_engine.get_compute_domain(
metric_domain_kwargs, domain_type=MetricDomainTypes.TABLE
)
# metric value kwargs: kwargs passed in through the expectation
column_a = metric_value_kwargs.get("column_a")
column_b = metric_value_kwargs.get("column_b")
column_a_values = df[column_a].to_list()
column_b_values = df[column_b].to_list()
test_statistic, p_value = stats.ks_2samp(column_a_values, column_b_values)
return test_statistic, p_value
@classmethod
def _get_evaluation_dependencies(
cls,
metric: MetricConfiguration,
configuration: Optional[ExpectationConfiguration] = None,
execution_engine: Optional[ExecutionEngine] = None,
runtime_configuration: Optional[dict] = None,
):
return {
"table.columns": MetricConfiguration("table.columns", metric.metric_domain_kwargs),
}
| ColumnKolmogorovSmirnovTestPValueGreaterThan |
python | viewflow__viewflow | viewflow/workflow/flow/views/filters.py | {
"start": 1274,
"end": 1867
} | class ____(FilterSet):
process = ModelChoiceFilter(queryset=this.queue_processes_query)
flow_task = ChoiceFilter()
created = DateRangeFilter()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filters["flow_task"].field.choices = get_queryset_flow_task_choices(
self.queryset
)
def queue_processes_query(self, request):
return Process.objects.filter(pk__in=self.queryset.values("process"))
class Meta:
model = Task
fields = ("process", "flow_task", "created")
| FlowUserTaskListFilter |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_hybrid_shard.py | {
"start": 2489,
"end": 2592
} | class ____(Enum):
ALL_HYBRID_SHARD = auto()
MIXED_HYBRID_FULL_SHARD = auto()
| ShardingStrategyMode |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/primitives.py | {
"start": 264,
"end": 2672
} | class ____:
"""
A thread-safe async event.
Unlike `asyncio.Event` this implementation does not bind to a loop on creation. This
matches the behavior of `asyncio.Event` in Python 3.10+, but differs from earlier
versions.
This event also does not support a `clear()` operation. This matches the behavior of
`anyio.Event` types and prevents sneaky bugs; create a new event instead.
"""
def __init__(self) -> None:
self._waiters: collections.deque[asyncio.Future[bool]] = collections.deque()
self._value = False
self._lock = threading.Lock()
def set(self) -> None:
"""
Set the flag, notifying all waiters.
Unlike `asyncio.Event`, waiters may not be notified immediately when this is
called; instead, notification will be placed on the owning loop of each waiter
for thread safety.
"""
with self._lock:
if not self._value:
self._value = True
# We freeze the waiters queue during iteration so removal in `wait()`
# does not change the size during iteration. The lock ensures that no
# waiters are added until after we finish here.
for fut in tuple(self._waiters):
if not fut.done():
# The `asyncio.Future.set_result` method is not thread-safe
# and must be run in the loop that owns the future
call_soon_in_loop(fut._loop, fut.set_result, True)
def is_set(self):
return self._value
async def wait(self) -> Literal[True]:
"""
Block until the internal flag is true.
If the internal flag is true on entry, return True immediately.
Otherwise, block until another `set()` is called, then return True.
"""
# Taking a sync lock in an async context is generally not recommended, but this
# lock should only ever be held very briefly and we need to prevent race
# conditions during between `set()` and `wait()`
with self._lock:
if self._value:
return True
fut: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
self._waiters.append(fut)
try:
await fut
return True
finally:
self._waiters.remove(fut)
| Event |
python | wandb__wandb | wandb/vendor/pygments/lexers/objective.py | {
"start": 8244,
"end": 8561
} | class ____(objective(CLexer)):
"""
For Objective-C source code with preprocessor directives.
"""
name = 'Objective-C'
aliases = ['objective-c', 'objectivec', 'obj-c', 'objc']
filenames = ['*.m', '*.h']
mimetypes = ['text/x-objective-c']
priority = 0.05 # Lower than C
| ObjectiveCLexer |
python | doocs__leetcode | solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/Solution.py | {
"start": 0,
"end": 320
} | class ____:
def minSum(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1) + nums1.count(0)
s2 = sum(nums2) + nums2.count(0)
if s1 > s2:
return self.minSum(nums2, nums1)
if s1 == s2:
return s1
return -1 if nums1.count(0) == 0 else s2
| Solution |
python | pytorch__pytorch | torch/testing/_internal/distributed/nn/api/remote_module_test.py | {
"start": 2675,
"end": 2996
} | class ____:
def __init__(self, first_arg, first_kwarg=-1):
pass
def create_scripted_module(first_arg, first_kwarg=-1):
module = MyModule(first_arg, first_kwarg=first_kwarg)
scripted_module = torch.jit.script(module)
return scripted_module
# Common utils for both CPU and CUDA test suites
| BadModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 352916,
"end": 353515
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateIssueComment"""
__schema__ = github_schema
__field_names__ = ("id", "body", "client_mutation_id")
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
"""The ID of the IssueComment to modify."""
body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body")
"""The updated text of the comment."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UpdateIssueCommentInput |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 16273,
"end": 16342
} | class ____(TypedDict):
extras: PipesExtras
| PipesLogWriterOpenedData |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 51062,
"end": 56616
} | class ____:
@pytest.mark.parametrize("pad_width", [
(4, 5, 6, 7),
((1,), (2,), (3,)),
((1, 2), (3, 4), (5, 6)),
((3, 4, 5), (0, 1, 2)),
])
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_misshaped_pad_width(self, pad_width, mode):
arr = np.arange(30).reshape((6, 5))
match = "operands could not be broadcast together"
with pytest.raises(ValueError, match=match):
np.pad(arr, pad_width, mode)
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_misshaped_pad_width_2(self, mode):
arr = np.arange(30).reshape((6, 5))
match = ("input operand has more dimensions than allowed by the axis "
"remapping")
with pytest.raises(ValueError, match=match):
np.pad(arr, (((3,), (4,), (5,)), ((0,), (1,), (2,))), mode)
@pytest.mark.parametrize(
"pad_width", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))])
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_negative_pad_width(self, pad_width, mode):
arr = np.arange(30).reshape((6, 5))
match = "index can't contain negative values"
with pytest.raises(ValueError, match=match):
np.pad(arr, pad_width, mode)
@pytest.mark.parametrize("pad_width, dtype", [
("3", None),
("word", None),
(None, None),
(object(), None),
(3.4, None),
(((2, 3, 4), (3, 2)), object),
(complex(1, -1), None),
(((-2.1, 3), (3, 2)), None),
])
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_bad_type(self, pad_width, dtype, mode):
arr = np.arange(30).reshape((6, 5))
match = "`pad_width` must be of integral type."
if dtype is not None:
# avoid DeprecationWarning when not specifying dtype
with pytest.raises(TypeError, match=match):
np.pad(arr, np.array(pad_width, dtype=dtype), mode)
else:
with pytest.raises(TypeError, match=match):
np.pad(arr, pad_width, mode)
with pytest.raises(TypeError, match=match):
np.pad(arr, np.array(pad_width), mode)
def test_pad_width_as_ndarray(self):
a = np.arange(12)
a = np.reshape(a, (4, 3))
a = np.pad(a, np.array(((2, 3), (3, 2))), 'edge')
b = np.array(
[[0, 0, 0, 0, 1, 2, 2, 2],
[0, 0, 0, 0, 1, 2, 2, 2],
[0, 0, 0, 0, 1, 2, 2, 2],
[3, 3, 3, 3, 4, 5, 5, 5],
[6, 6, 6, 6, 7, 8, 8, 8],
[9, 9, 9, 9, 10, 11, 11, 11],
[9, 9, 9, 9, 10, 11, 11, 11],
[9, 9, 9, 9, 10, 11, 11, 11],
[9, 9, 9, 9, 10, 11, 11, 11]]
)
assert_array_equal(a, b)
@pytest.mark.parametrize("pad_width", [0, (0, 0), ((0, 0), (0, 0))])
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_zero_pad_width(self, pad_width, mode):
arr = np.arange(30).reshape(6, 5)
assert_array_equal(arr, np.pad(arr, pad_width, mode=mode))
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_kwargs(mode):
"""Test behavior of pad's kwargs for the given mode."""
allowed = _all_modes[mode]
not_allowed = {}
for kwargs in _all_modes.values():
if kwargs != allowed:
not_allowed.update(kwargs)
# Test if allowed keyword arguments pass
np.pad([1, 2, 3], 1, mode, **allowed)
# Test if prohibited keyword arguments of other modes raise an error
for key, value in not_allowed.items():
match = f"unsupported keyword arguments for mode '{mode}'"
with pytest.raises(ValueError, match=match):
np.pad([1, 2, 3], 1, mode, **{key: value})
def test_constant_zero_default():
arr = np.array([1, 1])
assert_array_equal(np.pad(arr, 2), [0, 0, 1, 1, 0, 0])
@pytest.mark.parametrize("mode", [1, "const", object(), None, True, False])
def test_unsupported_mode(mode):
match = f"mode '{mode}' is not supported"
with pytest.raises(ValueError, match=match):
np.pad([1, 2, 3], 4, mode=mode)
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_non_contiguous_array(mode):
arr = np.arange(24).reshape(4, 6)[::2, ::2]
result = np.pad(arr, (2, 3), mode)
assert result.shape == (7, 8)
assert_equal(result[2:-3, 2:-3], arr)
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_memory_layout_persistence(mode):
"""Test if C and F order is preserved for all pad modes."""
x = np.ones((5, 10), order='C')
assert np.pad(x, 5, mode).flags["C_CONTIGUOUS"]
x = np.ones((5, 10), order='F')
assert np.pad(x, 5, mode).flags["F_CONTIGUOUS"]
@pytest.mark.parametrize("dtype", _numeric_dtypes)
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_dtype_persistence(dtype, mode):
arr = np.zeros((3, 2, 1), dtype=dtype)
result = np.pad(arr, 1, mode=mode)
assert result.dtype == dtype
@pytest.mark.parametrize("input_shape, pad_width, expected_shape", [
((3, 4, 5), {-2: (1, 3)}, (3, 4 + 1 + 3, 5)),
((3, 4, 5), {0: (5, 2)}, (3 + 5 + 2, 4, 5)),
((3, 4, 5), {0: (5, 2), -1: (3, 4)}, (3 + 5 + 2, 4, 5 + 3 + 4)),
((3, 4, 5), {1: 5}, (3, 4 + 2 * 5, 5)),
])
def test_pad_dict_pad_width(input_shape, pad_width, expected_shape):
a = np.zeros(input_shape)
result = np.pad(a, pad_width)
assert result.shape == expected_shape
| TestPadWidth |
python | bokeh__bokeh | src/bokeh/document/locking.py | {
"start": 3453,
"end": 4965
} | class ____: # TODO(mypy): this needs to implement Document interface
''' Wrap a Document object so that only methods that can safely be used
from unlocked callbacks or threads are exposed. Attempts to otherwise
access or change the Document results in an exception.
'''
def __init__(self, doc: Document) -> None:
'''
'''
self._doc = doc
def __getattr__(self, attr: str) -> Any:
'''
'''
raise AttributeError(UNSAFE_DOC_ATTR_USAGE_MSG)
def add_next_tick_callback(self, callback: Callback) -> NextTickCallback:
''' Add a "next tick" callback.
Args:
callback (callable) :
'''
return self._doc.add_next_tick_callback(callback)
def remove_next_tick_callback(self, callback: NextTickCallback) -> None:
''' Remove a "next tick" callback.
Args:
callback (callable) :
'''
self._doc.remove_next_tick_callback(callback)
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| UnlockedDocumentProxy |
python | scipy__scipy | scipy/special/tests/test_kolmogorov.py | {
"start": 11413,
"end": 15773
} | class ____:
def test_nan(self):
assert_(np.isnan(kolmogorov(np.nan)))
def test_basic(self):
dataset = [(0, 1.0),
(0.5, 0.96394524366487511),
(0.8275735551899077, 0.5000000000000000),
(1, 0.26999967167735456),
(2, 0.00067092525577969533)]
dataset = np.asarray(dataset)
FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
def test_linspace(self):
x = np.linspace(0, 2.0, 21)
dataset = [1.0000000000000000, 1.0000000000000000, 0.9999999999994950,
0.9999906941986655, 0.9971923267772983, 0.9639452436648751,
0.8642827790506042, 0.7112351950296890, 0.5441424115741981,
0.3927307079406543, 0.2699996716773546, 0.1777181926064012,
0.1122496666707249, 0.0680922218447664, 0.0396818795381144,
0.0222179626165251, 0.0119520432391966, 0.0061774306344441,
0.0030676213475797, 0.0014636048371873, 0.0006709252557797]
dataset_c = [0.0000000000000000, 6.609305242245699e-53, 5.050407338670114e-13,
9.305801334566668e-06, 0.0028076732227017, 0.0360547563351249,
0.1357172209493958, 0.2887648049703110, 0.4558575884258019,
0.6072692920593457, 0.7300003283226455, 0.8222818073935988,
0.8877503333292751, 0.9319077781552336, 0.9603181204618857,
0.9777820373834749, 0.9880479567608034, 0.9938225693655559,
0.9969323786524203, 0.9985363951628127, 0.9993290747442203]
dataset = np.column_stack([x, dataset])
FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
dataset_c = np.column_stack([x, dataset_c])
FuncData(_kolmogc, dataset_c, (0,), 1, rtol=_rtol).check()
def test_linspacei(self):
p = np.linspace(0, 1.0, 21, endpoint=True)
dataset = [np.inf, 1.3580986393225507, 1.2238478702170823,
1.1379465424937751, 1.0727491749396481, 1.0191847202536859,
0.9730633753323726, 0.9320695842357622, 0.8947644549851197,
0.8601710725555463, 0.8275735551899077, 0.7964065373291559,
0.7661855555617682, 0.7364542888171910, 0.7067326523068980,
0.6764476915028201, 0.6448126061663567, 0.6105590999244391,
0.5711732651063401, 0.5196103791686224, 0.0000000000000000]
dataset_c = [0.0000000000000000, 0.5196103791686225, 0.5711732651063401,
0.6105590999244391, 0.6448126061663567, 0.6764476915028201,
0.7067326523068980, 0.7364542888171910, 0.7661855555617682,
0.7964065373291559, 0.8275735551899077, 0.8601710725555463,
0.8947644549851196, 0.9320695842357622, 0.9730633753323727,
1.0191847202536859, 1.0727491749396481, 1.1379465424937754,
1.2238478702170825, 1.3580986393225509, np.inf]
dataset = np.column_stack([p[1:], dataset[1:]])
FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
dataset_c = np.column_stack([p[:-1], dataset_c[:-1]])
FuncData(_kolmogci, dataset_c, (0,), 1, rtol=_rtol).check()
def test_smallx(self):
epsilon = 0.1 ** np.arange(1, 14)
x = np.array([0.571173265106, 0.441027698518, 0.374219690278, 0.331392659217,
0.300820537459, 0.277539353999, 0.259023494805, 0.243829561254,
0.231063086389, 0.220135543236, 0.210641372041, 0.202290283658,
0.19487060742])
dataset = np.column_stack([x, 1-epsilon])
FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
def test_round_trip(self):
def _ki_k(_x):
return kolmogi(kolmogorov(_x))
def _kci_kc(_x):
return _kolmogci(_kolmogc(_x))
x = np.linspace(0.0, 2.0, 21, endpoint=True)
# Exclude 0.1, 0.2. 0.2 almost makes succeeds, but 0.1 has no chance.
x02 = x[(x == 0) | (x > 0.21)]
dataset02 = np.column_stack([x02, x02])
FuncData(_ki_k, dataset02, (0,), 1, rtol=_rtol).check()
dataset = np.column_stack([x, x])
FuncData(_kci_kc, dataset, (0,), 1, rtol=_rtol).check()
| TestKolmogorov |
python | networkx__networkx | networkx/algorithms/tests/test_dominance.py | {
"start": 39,
"end": 3442
} | class ____:
@pytest.mark.parametrize("G", [nx.Graph(), nx.MultiGraph()])
def test_raises_undirected(self, G):
"""Check that `immediate_dominators` raises for undirected graphs."""
with pytest.raises(
nx.NetworkXNotImplemented, match=r"not implemented for undirected"
):
nx.immediate_dominators(G, 0)
def test_raises_node(self):
"""Check that `immediate_dominators` raises when `start` is not in the graph."""
G = nx.empty_graph(1, create_using=nx.DiGraph)
with pytest.raises(nx.NetworkXError, match=r"not in G"):
nx.immediate_dominators(G, 1)
def test_singleton(self):
G = nx.DiGraph()
G.add_node(0)
assert nx.immediate_dominators(G, 0) == {}
G.add_edge(0, 0)
assert nx.immediate_dominators(G, 0) == {}
@pytest.mark.parametrize("gen", [nx.path_graph, nx.cycle_graph])
@pytest.mark.parametrize("n", [5, 10, 20])
def test_path_and_cycle(self, gen, n):
"""Check `immediate_dominators` is correct for path and cycle graphs."""
G = gen(n, create_using=nx.DiGraph())
idom = nx.immediate_dominators(G, 0)
assert idom == {i: i - 1 for i in range(1, n)}
def test_unreachable(self):
n = 5
G = nx.path_graph(n, create_using=nx.DiGraph())
idom = nx.immediate_dominators(G, 1)
assert idom == {i: i - 1 for i in range(2, n)}
@pytest.mark.parametrize(
["edgelist", "start"],
[
([(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)], 5),
(
[
(1, 2),
(2, 1),
(2, 3),
(3, 2),
(4, 2),
(4, 3),
(5, 1),
(6, 4),
(6, 5),
],
6,
),
],
)
def test_irreducible(self, edgelist, start):
"""
Check `immediate_dominators` on irreducible reference graphs.
Graphs taken from figures 2 and 4 of "A simple, fast dominance algorithm." (2006).
https://hdl.handle.net/1911/96345
"""
G = nx.DiGraph(edgelist)
idom = nx.immediate_dominators(G, start)
assert idom == dict.fromkeys(range(1, start), start)
def test_domrel_png(self):
# Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png
edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)]
G = nx.DiGraph(edges)
result = nx.immediate_dominators(G, 1)
assert result == {2: 1, 3: 2, 4: 2, 5: 2, 6: 2}
# Test postdominance.
result = nx.immediate_dominators(G.reverse(copy=False), 6)
assert result == {1: 2, 2: 6, 3: 5, 4: 5, 5: 2}
def test_boost_example(self):
# Graph taken from Figure 1 of
# http://www.boost.org/doc/libs/1_56_0/libs/graph/doc/lengauer_tarjan_dominator.htm
edges = [(0, 1), (1, 2), (1, 3), (2, 7), (3, 4), (4, 5), (4, 6), (5, 7), (6, 4)]
G = nx.DiGraph(edges)
result = nx.immediate_dominators(G, 0)
assert result == {1: 0, 2: 1, 3: 1, 4: 3, 5: 4, 6: 4, 7: 1}
# Test postdominance.
result = nx.immediate_dominators(G.reverse(copy=False), 7)
assert result == {0: 1, 1: 7, 2: 7, 3: 4, 4: 5, 5: 7, 6: 4}
| TestImmediateDominators |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_apps.py | {
"start": 6500,
"end": 9993
} | class ____(SentryAppsTest):
def setUp(self) -> None:
super().setUp()
self.setup_apps()
self.superuser = self.create_user(is_superuser=True)
self.login_as(self.superuser, superuser=True)
def test_staff_sees_all_apps(self) -> None:
staff_user = self.create_user(is_staff=True)
self.login_as(staff_user, staff=True)
response = self.get_success_response(status_code=200)
response_uuids = {o["uuid"] for o in response.data}
assert self.published_app.uuid in response_uuids
assert self.unpublished_app.uuid in response_uuids
assert self.unowned_unpublished_app.uuid in response_uuids
with self.settings(SENTRY_SELF_HOSTED=False):
self.get_success_response(status_code=200)
def test_superuser_sees_all_apps(self) -> None:
response = self.get_success_response(status_code=200)
response_uuids = {o["uuid"] for o in response.data}
assert self.published_app.uuid in response_uuids
assert self.unpublished_app.uuid in response_uuids
assert self.unowned_unpublished_app.uuid in response_uuids
with self.settings(SENTRY_SELF_HOSTED=False):
self.get_success_response(status_code=200)
@override_settings(SENTRY_SELF_HOSTED=False)
@override_options({"superuser.read-write.ga-rollout": True})
def test_superuser_read_write_sees_all_apps(self) -> None:
self.get_success_response(status_code=200)
self.add_user_permission(self.superuser, "superuser.write")
self.get_success_response(status_code=200)
def test_superusers_filter_on_internal_apps(self) -> None:
self.setup_internal_app()
new_org = self.create_organization()
self.create_project(organization=new_org)
internal_app = self.create_internal_integration(name="Internal Nosee", organization=new_org)
response = self.get_success_response(qs_params={"status": "internal"}, status_code=200)
self.assert_response_has_serialized_sentry_app(
response=response, sentry_app=self.internal_app, organization=self.internal_organization
)
response_uuids = {o["uuid"] for o in response.data}
assert internal_app.uuid in response_uuids
assert self.published_app.uuid not in response_uuids
assert self.unpublished_app.uuid not in response_uuids
assert self.unowned_unpublished_app.uuid not in response_uuids
def test_superuser_filter_on_published(self) -> None:
response = self.get_success_response(qs_params={"status": "published"}, status_code=200)
self.assert_response_has_serialized_sentry_app(
response=response,
sentry_app=self.published_app,
organization=self.organization,
has_features=True,
)
response_uuids = {o["uuid"] for o in response.data}
assert self.unpublished_app.uuid not in response_uuids
assert self.unowned_unpublished_app.uuid not in response_uuids
def test_superuser_filter_on_unpublished(self) -> None:
response = self.get_success_response(qs_params={"status": "unpublished"}, status_code=200)
response_uuids = {o["uuid"] for o in response.data}
assert self.unpublished_app.uuid in response_uuids
assert self.unowned_unpublished_app.uuid in response_uuids
assert self.published_app.uuid not in response_uuids
@control_silo_test
| SuperuserStaffGetSentryAppsTest |
python | kamyu104__LeetCode-Solutions | Python/peak-index-in-a-mountain-array.py | {
"start": 32,
"end": 416
} | class ____(object):
def peakIndexInMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
left, right = 0, len(arr)-1
while left <= right:
mid = left + (right-left)//2
if arr[mid] > arr[mid+1]:
right = mid-1
else:
left = mid+1
return left
| Solution |
python | pytorch__pytorch | torch/_lazy/closure.py | {
"start": 160,
"end": 475
} | class ____:
def __init__(self) -> None:
pass
def run(self, closure):
"""Run closure function
Args:
closure: callable function to run
"""
closure()
def __call__(self, closures):
for closure in closures:
self.run(closure)
| ClosureHandler |
python | huggingface__transformers | src/transformers/models/codegen/modeling_codegen.py | {
"start": 11570,
"end": 11869
} | class ____(PreTrainedModel):
config: CodeGenConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_no_split_modules = ["CodeGenBlock"]
_skip_keys_device_placement = "past_key_values"
_can_compile_fullgraph = True
@auto_docstring
| CodeGenPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/task_runners.py | {
"start": 7861,
"end": 17233
} | class ____(TaskRunner[PrefectConcurrentFuture[R]]):
"""
A task runner that executes tasks in a separate thread pool.
Attributes:
max_workers: The maximum number of threads to use for executing tasks.
Defaults to `PREFECT_TASK_RUNNER_THREAD_POOL_MAX_WORKERS` or `sys.maxsize`.
Note:
This runner uses `contextvars.copy_context()` for thread-safe context propagation.
However, because contextvars are thread-local, frequent task submissions
that modify context (e.g., using `prefect.tags` in a loop) can lead to
new thread creation per task. This may cause an increase in threads and
file descriptors, potentially hitting OS limits (`OSError: Too many open files`).
If this occurs, consider minimizing context changes within looped tasks or
adjusting system limits for open file descriptors.
Examples:
Use a thread pool task runner with a flow:
```python
from prefect import flow, task
from prefect.task_runners import ThreadPoolTaskRunner
@task
def some_io_bound_task(x: int) -> int:
# making a query to a database, reading a file, etc.
return x * 2
@flow(task_runner=ThreadPoolTaskRunner(max_workers=3)) # use at most 3 threads at a time
def my_io_bound_flow():
futures = []
for i in range(10):
future = some_io_bound_task.submit(i * 100)
futures.append(future)
return [future.result() for future in futures]
```
Use a thread pool task runner as a context manager:
```python
from prefect.task_runners import ThreadPoolTaskRunner
@task
def some_io_bound_task(x: int) -> int:
# making a query to a database, reading a file, etc.
return x * 2
# Use the runner directly
with ThreadPoolTaskRunner(max_workers=2) as runner:
future1 = runner.submit(some_io_bound_task, {"x": 1})
future2 = runner.submit(some_io_bound_task, {"x": 2})
result1 = future1.result() # 2
result2 = future2.result() # 4
```
Configure max workers via settings:
```python
# Set via environment variable
# export PREFECT_TASK_RUNNER_THREAD_POOL_MAX_WORKERS=8
from prefect import flow
from prefect.task_runners import ThreadPoolTaskRunner
@flow(task_runner=ThreadPoolTaskRunner()) # Uses 8 workers from setting
def my_flow():
...
```
"""
def __init__(self, max_workers: int | None = None):
super().__init__()
current_settings = get_current_settings()
self._executor: ThreadPoolExecutor | None = None
self._max_workers = (
(current_settings.tasks.runner.thread_pool_max_workers or sys.maxsize)
if max_workers is None
else max_workers
)
self._cancel_events: dict[uuid.UUID, threading.Event] = {}
def duplicate(self) -> "ThreadPoolTaskRunner[R]":
return type(self)(max_workers=self._max_workers)
@overload
def submit(
self,
task: "Task[P, CoroutineType[Any, Any, R]]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
dependencies: dict[str, set[RunInput]] | None = None,
) -> PrefectConcurrentFuture[R]: ...
@overload
def submit(
self,
task: "Task[Any, R]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
dependencies: dict[str, set[RunInput]] | None = None,
) -> PrefectConcurrentFuture[R]: ...
def submit(
self,
task: "Task[P, R | CoroutineType[Any, Any, R]]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
dependencies: dict[str, set[RunInput]] | None = None,
) -> PrefectConcurrentFuture[R]:
"""
Submit a task to the task run engine running in a separate thread.
Args:
task: The task to submit.
parameters: The parameters to use when running the task.
wait_for: A list of futures that the task depends on.
Returns:
A future object that can be used to wait for the task to complete and
retrieve the result.
"""
if not self._started or self._executor is None:
raise RuntimeError("Task runner is not started")
if wait_for and task.tags and (self._max_workers <= len(task.tags)):
self.logger.warning(
f"Task {task.name} has {len(task.tags)} tags but only {self._max_workers} workers available"
"This may lead to dead-locks. Consider increasing the value of `PREFECT_TASK_RUNNER_THREAD_POOL_MAX_WORKERS` or `max_workers`."
)
from prefect.context import FlowRunContext
from prefect.task_engine import run_task_async, run_task_sync
task_run_id = uuid7()
cancel_event = threading.Event()
self._cancel_events[task_run_id] = cancel_event
context = copy_context()
flow_run_ctx = FlowRunContext.get()
if flow_run_ctx:
get_run_logger(flow_run_ctx).debug(
f"Submitting task {task.name} to thread pool executor..."
)
else:
self.logger.debug(f"Submitting task {task.name} to thread pool executor...")
submit_kwargs: dict[str, Any] = dict(
task=task,
task_run_id=task_run_id,
parameters=parameters,
wait_for=wait_for,
return_type="state",
dependencies=dependencies,
context=dict(cancel_event=cancel_event),
)
if task.isasync:
# TODO: Explore possibly using a long-lived thread with an event loop
# for better performance
future = self._executor.submit(
context.run,
asyncio.run,
run_task_async(**submit_kwargs),
)
else:
future = self._executor.submit(
context.run,
run_task_sync,
**submit_kwargs,
)
prefect_future = PrefectConcurrentFuture(
task_run_id=task_run_id, wrapped_future=future
)
return prefect_future
@overload
def map(
self,
task: "Task[P, CoroutineType[Any, Any, R]]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
) -> PrefectFutureList[PrefectConcurrentFuture[R]]: ...
@overload
def map(
self,
task: "Task[Any, R]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
) -> PrefectFutureList[PrefectConcurrentFuture[R]]: ...
def map(
self,
task: "Task[P, R | CoroutineType[Any, Any, R]]",
parameters: dict[str, Any],
wait_for: Iterable[PrefectFuture[Any]] | None = None,
) -> PrefectFutureList[PrefectConcurrentFuture[R]]:
return super().map(task, parameters, wait_for)
def cancel_all(self) -> None:
for event in self._cancel_events.values():
event.set()
self.logger.debug("Set cancel event")
if self._executor is not None:
self._executor.shutdown(cancel_futures=True)
self._executor = None
def __enter__(self) -> Self:
super().__enter__()
self._executor = ThreadPoolExecutor(max_workers=self._max_workers)
return self
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
self.cancel_all()
if self._executor is not None:
self._executor.shutdown(cancel_futures=True)
self._executor = None
super().__exit__(exc_type, exc_value, traceback)
def __eq__(self, value: object) -> bool:
if not isinstance(value, ThreadPoolTaskRunner):
return False
return self._max_workers == value._max_workers
# Here, we alias ConcurrentTaskRunner to ThreadPoolTaskRunner for backwards compatibility
ConcurrentTaskRunner = ThreadPoolTaskRunner
def _run_task_in_subprocess(
*args: Any,
env: dict[str, str] | None = None,
**kwargs: Any,
) -> Any:
"""
Wrapper function to update environment variables and settings before running a task in a subprocess.
"""
from prefect.context import hydrated_context
from prefect.engine import handle_engine_signals
from prefect.task_engine import run_task_async, run_task_sync
# Update environment variables
os.environ.update(env or {})
# Extract context from kwargs
context = kwargs.pop("context", None)
with hydrated_context(context):
with handle_engine_signals(kwargs.get("task_run_id")):
# Determine if this is an async task
task = kwargs.get("task")
if task and task.isasync:
# For async tasks, we need to create a new event loop
import asyncio
maybe_coro = run_task_async(*args, **kwargs)
return asyncio.run(maybe_coro)
else:
return run_task_sync(*args, **kwargs)
| ThreadPoolTaskRunner |
python | walkccc__LeetCode | solutions/1881. Maximum Value after Insertion/1881.py | {
"start": 0,
"end": 251
} | class ____:
def maxValue(self, n: str, x: int) -> str:
isNegative = n[0] == '-'
for i, c in enumerate(n):
if not isNegative and int(c) < x or isNegative and int(c) > x:
return n[:i] + str(x) + n[i:]
return n + str(x)
| Solution |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/direct_dep_foo_bar/package.py | {
"start": 217,
"end": 689
} | class ____(Package):
"""This package has a variant "bar", which is False by default, and
variant "foo" which is True by default.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/direct-dep-foo-bar-1.0.tar.gz"
version("1.0", md5="567890abcdefg12345678900987654321")
variant("foo", default=True, description="")
variant("bar", default=False, description="")
depends_on("second-dependency-foo-bar-fee")
| DirectDepFooBar |
python | ansible__ansible | hacking/create-bulk-issues.py | {
"start": 577,
"end": 1614
} | class ____:
title: str
summary: str
body: str
project: str
labels: list[str] | None = None
assignee: str | None = None
def create(self) -> str:
cmd = ['gh', 'issue', 'create', '--title', self.title, '--body', self.body, '--project', self.project]
if self.labels:
for label in self.labels:
cmd.extend(('--label', label))
if self.assignee:
cmd.extend(('--assignee', self.assignee))
try:
process = subprocess.run(cmd, capture_output=True, check=True, text=True)
except subprocess.CalledProcessError as ex:
print('>>> Note')
print(f"You may need to run 'gh auth refresh -s project' if 'gh' reports it cannot find the project {self.project!r} when it exists.")
print(f'>>> Standard Output\n{ex.stdout.strip()}\n>>> Standard Error\n{ex.stderr.strip()}\n>>> Exception')
raise
url = process.stdout.strip()
return url
@dataclasses.dataclass(frozen=True)
| Issue |
python | openai__openai-python | examples/responses/structured_outputs.py | {
"start": 159,
"end": 1050
} | class ____(BaseModel):
steps: List[Step]
final_answer: str
client = OpenAI()
rsp = client.responses.parse(
input="solve 8x + 31 = 2",
model="gpt-4o-2024-08-06",
text_format=MathResponse,
)
for output in rsp.output:
if output.type != "message":
raise Exception("Unexpected non message")
for item in output.content:
if item.type != "output_text":
raise Exception("unexpected output type")
if not item.parsed:
raise Exception("Could not parse response")
rich.print(item.parsed)
print("answer: ", item.parsed.final_answer)
# or
message = rsp.output[0]
assert message.type == "message"
text = message.content[0]
assert text.type == "output_text"
if not text.parsed:
raise Exception("Could not parse response")
rich.print(text.parsed)
print("answer: ", text.parsed.final_answer)
| MathResponse |
python | huggingface__transformers | src/transformers/integrations/fbgemm_fp8.py | {
"start": 3157,
"end": 12441
} | class ____(nn.Module):
def __init__(self, config, dtype=torch.float32):
super().__init__()
self.num_experts = config.num_local_experts
self.intermediate_size = config.intermediate_size
self.hidden_size = config.hidden_size
self.expert_dim = self.intermediate_size
self.act_fn = ACT2FN[config.hidden_act]
# Register FP8 buffers for gate_up_proj
self.gate_up_proj = torch.nn.Parameter(
torch.zeros((self.num_experts, self.hidden_size, 2 * self.expert_dim), dtype=torch.float8_e4m3fn)
)
self.gate_up_proj_scale = torch.nn.Parameter(
torch.zeros((self.num_experts, 1, self.expert_dim * 2), dtype=torch.float32)
)
# Register FP8 buffers for down_proj
self.down_proj = torch.nn.Parameter(
torch.zeros((self.num_experts, self.expert_dim, self.hidden_size), dtype=torch.float8_e4m3fn)
)
self.down_proj_scale = torch.nn.Parameter(
torch.zeros((self.num_experts, self.hidden_size, 1), dtype=torch.float32)
)
# Register input scale upper bound
self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
def forward(self, hidden_states):
"""
Args:
hidden_states (torch.Tensor): (batch_size * token_num, hidden_size)
Returns:
torch.Tensor: (batch_size * token_num, hidden_size)
"""
# Reshape hidden states for expert computation
hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size)
num_tokens = None
# Pre-allocate tensor for all expert outputs with same shape as hidden_states
next_states = torch.empty_like(hidden_states)
for i in range(self.num_experts):
# Extract expert's hidden states
expert_hidden = hidden_states[i]
expert_hidden_reshaped = expert_hidden.reshape(-1, self.hidden_size)
# Quantize for this expert
expert_quantized, expert_scale = torch.ops.fbgemm.quantize_fp8_per_row(
expert_hidden_reshaped, num_tokens, self.input_scale_ub
)
sharded_expert_dim = self.gate_up_proj.shape[-1] // 2
gate_up_proj_scale_float32 = self.gate_up_proj_scale.to(torch.float32)
gate = torch.ops.fbgemm.f8f8bf16_rowwise(
expert_quantized,
self.gate_up_proj[i].transpose(0, 1)[:sharded_expert_dim].contiguous(),
expert_scale,
gate_up_proj_scale_float32[i][0][:sharded_expert_dim].view(-1, 1).contiguous(),
use_fast_accum=True,
)
up = torch.ops.fbgemm.f8f8bf16_rowwise(
expert_quantized,
self.gate_up_proj[i].transpose(0, 1)[sharded_expert_dim:].contiguous(),
expert_scale,
gate_up_proj_scale_float32[i][0][sharded_expert_dim:].view(-1, 1).contiguous(),
use_fast_accum=True,
)
activated = up * self.act_fn(gate)
activated_quantized, activated_scale = torch.ops.fbgemm.quantize_fp8_per_row(
activated, num_tokens, self.input_scale_ub
)
down_proj_scale_float32 = self.down_proj_scale.to(torch.float32)
expert_output = torch.ops.fbgemm.f8f8bf16_rowwise(
activated_quantized,
self.down_proj[i].transpose(0, 1).contiguous(),
activated_scale,
down_proj_scale_float32[i].view(-1, 1).contiguous(),
use_fast_accum=True,
)
next_states[i] = expert_output
next_states = next_states.to(hidden_states.device)
return next_states.view(-1, self.hidden_size)
def _replace_with_fbgemm_fp8_linear(
model,
modules_to_not_convert=None,
current_key_name=None,
quantization_config=None,
has_been_replaced=False,
pre_quantized=False,
config=None,
tp_plan=None,
):
"""
Private method that wraps the recursion for module replacement.
Returns the converted model and a boolean that indicates if the conversion has been successful or not.
"""
import re
if current_key_name is None:
current_key_name = []
for name, module in model.named_children():
current_key_name.append(name)
if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
current_key_name_str = ".".join(current_key_name)
if not any(
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
):
with init_empty_weights(include_buffers=True):
in_features = module.in_features
out_features = module.out_features
model._modules[name] = FbgemmFp8Linear(
in_features,
out_features,
module.bias is not None,
)
has_been_replaced = True
# Force requires grad to False to avoid unexpected errors
model._modules[name].requires_grad_(False)
# set non persistent buffer outside of init_empty_weights
model._modules[name].input_scale_ub = torch.tensor(
[quantization_config.activation_scale_ub],
dtype=torch.float,
)
if module.__class__.__name__ == "Llama4TextExperts" and name not in modules_to_not_convert:
current_key_name_str = ".".join(current_key_name)
if not any(
(key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
):
with init_empty_weights(include_buffers=True):
tp_plan[re.sub(r"\d+", "*", current_key_name_str + ".down_proj_scale")] = None
model._modules[name] = FbgemmFp8Llama4TextExperts(
config.text_config,
)
model._modules[name].input_scale_ub = torch.tensor(
[quantization_config.activation_scale_ub], dtype=torch.float
)
if len(list(module.children())) > 0:
_, has_been_replaced = _replace_with_fbgemm_fp8_linear(
module,
modules_to_not_convert,
current_key_name,
quantization_config,
has_been_replaced=has_been_replaced,
pre_quantized=pre_quantized,
config=config,
tp_plan=tp_plan,
)
# Remove the last key for recursion
current_key_name.pop(-1)
return model, has_been_replaced
def replace_with_fbgemm_fp8_linear(
model,
modules_to_not_convert=None,
current_key_name=None,
quantization_config=None,
pre_quantized=False,
config=None,
tp_plan=None,
):
"""
A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules.
This will enable running your models using high performance fp8 kernel from FBGEMM library.
The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
Parameters:
model (`torch.nn.Module`):
Input model or `torch.nn.Module` as the function is run recursively.
modules_to_not_convert (`list[`str`]`, *optional*, defaults to `["lm_head"]`):
Names of the modules to not convert in `FP8Linear`. In practice we keep the `lm_head` in full precision
for numerical stability reasons.
current_key_name (`list[`str`]`, *optional*):
An array to track the current key of the recursion. This is used to check whether the current key (part of
it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
`disk`).
"""
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
if quantization_config.modules_to_not_convert is not None:
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
modules_to_not_convert = list(set(modules_to_not_convert))
model, has_been_replaced = _replace_with_fbgemm_fp8_linear(
model,
modules_to_not_convert,
current_key_name,
quantization_config,
pre_quantized=pre_quantized,
config=config,
tp_plan=tp_plan,
)
if not has_been_replaced:
logger.warning(
"You are loading your model using FP8 quantization but no linear modules were found in your model."
" Please double check your model architecture, or submit an issue on github if you think this is"
" a bug."
)
return model
| FbgemmFp8Llama4TextExperts |
python | pytorch__pytorch | torch/fx/experimental/normalize.py | {
"start": 3614,
"end": 5491
} | class ____(AnnotateTypesWithSchema):
"""
Normalize callsites that are different ways of "spelling" the same
invocation into a single, canonical call. Currently supports:
1. Normalize operators (e.g. operator.add) to the `torch` ops they
ultimately invoke (e.g. torch.add) when it is possible to statically
reason that
Example usage:
m = torchvision.models.resnet18()
traced = torch.fx.symbolic_trace(m)
traced = NormalizeOperators(traced).transform()
"""
binary_magic_method_remap: dict[
Callable[[Any, Any], Any], Callable[[Any, Any], Any]
] = {
torch.add: operator.add,
torch.mul: operator.mul,
torch.sub: operator.sub,
torch.div: operator.truediv,
torch.floor_divide: operator.floordiv,
torch.remainder: operator.mod,
torch.eq: operator.eq,
torch.ne: operator.ne,
torch.lt: operator.lt,
torch.le: operator.le,
torch.gt: operator.gt,
torch.ge: operator.ge,
}
def call_function(
self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any]
):
# Normalize operators according to the magic methods implemented on tensors here:
# https://github.com/pytorch/pytorch/blob/28c5d90b679c6b38bf4183ec99f16d933c2f1bcd/tools/autograd/templates/python_variable_methods.cpp#L1137 # noqa: B950
assert callable(target)
if target in self.binary_magic_method_remap:
if len(args) != 2:
return super().call_function(target, args, kwargs)
lhs, rhs = args
return super().call_function(
target=self.binary_magic_method_remap[target],
args=(lhs, rhs),
kwargs={},
)
return super().call_function(target, args, kwargs)
| NormalizeOperators |
python | ray-project__ray | python/ray/dag/dag_node_operation.py | {
"start": 1057,
"end": 2689
} | class ____:
def __init__(
self,
exec_task_idx: int,
operation_type: _DAGNodeOperationType,
method_name: Optional[str] = None,
):
"""
Args:
exec_task_idx: The index of the task that this operation belongs to
in the actor's ExecutableTask list. The index is not the same
as bind_index because there may be more tasks bound to an actor
than tasks that appear in the current compiled DAG.
operation_type: The type of operation to perform.
method_name: The name of the method that this operation originates
from. This is only for visualization and debugging purposes.
"""
self.exec_task_idx = exec_task_idx
self.type = operation_type
self.method_name = method_name
def __repr__(self):
return (
f"_DAGNodeOperation("
f"exec_task_idx: {self.exec_task_idx}, "
f"type: {self.type}, "
f"method_name: {self.method_name})"
)
def viz_str(self):
"""
A string representation of the node to be used in visualization.
"""
return f"[{self.exec_task_idx}] {self.method_name} {self.type.viz_str()}"
def __hash__(self):
return hash((self.exec_task_idx, self.type))
def __eq__(self, other):
# An operation is uniquely identified by its `exec_task_idx` and type.
# `method_name` is only for debugging purposes.
return self.exec_task_idx == other.exec_task_idx and self.type == other.type
@total_ordering
| _DAGNodeOperation |
python | huggingface__transformers | src/transformers/models/flex_olmo/modeling_flex_olmo.py | {
"start": 17071,
"end": 18804
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: FlexOlmoConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = FlexOlmoAttention(config=config, layer_idx=layer_idx)
self.mlp = FlexOlmoSparseMoeBlock(config)
self.post_attention_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_feedforward_layernorm = FlexOlmoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs,
) -> torch.FloatTensor:
residual = hidden_states
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_feedforward_layernorm(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
| FlexOlmoDecoderLayer |
python | google__jax | tests/dynamic_api_test.py | {
"start": 48836,
"end": 62038
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if jax.config.x64_enabled: raise unittest.SkipTest()
@parameterized.parameters((True,), (False,))
def test_internal_jumble(self, disable_jit):
with jax.disable_jit(disable_jit):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
xs = jax.vmap(lambda n: jax.lax.iota('int32', n).sum())(ins)
self.assertAllClose(xs, jnp.array([3, 0, 6]), check_dtypes=False)
def test_jumble_escapes(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
xs = jax.vmap(jax.jit(lambda n: jax.lax.iota('int32', n)),
out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(xs, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5), 1)
self.assertAllClose(xs.data, data, check_dtypes=False)
def test_make_jumble_from_dynamic_shape(self):
# We may not want to support returning jumbles from vmapped functions
# (instead preferring to have a separate API which allows jumbles). But for
# now it makes for a convenient way to construct jumbles for the other
# tests!
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
p = jax.vmap(partial(jnp.arange, dtype='int32'),
out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\[bint\{≤5\}\[3\] with value: \[3 1 4\]\.Var[0-9]+\]')
data = jax.lax.broadcasted_iota('int32', (3, 5), 1)
self.assertAllClose(p.data, data, check_dtypes=False)
def test_jumble_map_eltwise(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
p = jax.vmap(partial(jnp.arange, dtype='int32'),
out_axes=batching.jumble_axis)(ins)
p = jumble_map(jax.jit(lambda x: x * 3))(p)
self.assertIsInstance(p, batching.Jumble)
self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\[bint\{≤5\}\[3\] with value: \[3 1 4\]\.Var[0-9]+\]')
data = jax.lax.broadcasted_iota('int32', (3, 5), 1) * 3
self.assertAllClose(p.data, data, check_dtypes=False)
def test_jumble_map_vector_dot(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
p = jax.vmap(partial(jnp.arange, dtype='int32'),
out_axes=batching.jumble_axis)(ins)
y = jumble_map(jnp.dot)(p, p)
self.assertIsInstance(y, batching.Jumble)
self.assertAllClose(y.data, jnp.array([5, 0, 14], dtype='int32'))
@parameterized.parameters((True,), (False,))
def test_jumble_map_matrix_dot_ragged_contract(self, disable_jit):
with jax.disable_jit(disable_jit):
sizes = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
p1 = jax.vmap(lambda n: jnp.ones((7, n)), out_axes=batching.jumble_axis
)(sizes)
p2 = jax.vmap(lambda n: jnp.ones((n, 7)), out_axes=batching.jumble_axis
)(sizes)
y = jax.vmap(jnp.dot, in_axes=batching.jumble_axis, out_axes=0,
axis_size=3)(p1, p2)
self.assertAllClose(y, np.tile(np.array([3, 1, 4])[:, None, None], (7, 7)),
check_dtypes=False)
@parameterized.parameters((True,), (False,))
def test_jumble_map_matrix_dot_ragged_tensor(self, disable_jit):
with jax.disable_jit(disable_jit):
sizes = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
lhs_one_d = jnp.arange(size, dtype='int32') + 1
lhs_two_d = jax.lax.broadcast_in_dim(lhs_one_d, (size, 2), (0,))
rhs = jax.lax.broadcasted_iota('int32', (2, 4), 0) + 1
return jnp.dot(lhs_two_d, rhs)
p = jax.vmap(func, out_axes=batching.jumble_axis)(sizes)
self.assertIsInstance(p, batching.Jumble)
self.assertEqual(p.data.shape, (3, 5, 4))
def test_broadcast_in_dim_while_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jax.lax.broadcast_in_dim(one_d, (size, 7), (0,))
return two_d
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5, 7), 1)
self.assertAllClose(p.data, data)
def test_broadcast_in_dim_to_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(12, dtype='int32')
two_d = jax.lax.broadcast_in_dim(one_d, (size, 12), (1,))
return two_d
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5, 12), 2)
self.assertAllClose(p.data, data)
def test_broadcast_in_dim_ragged_to_static_error(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
# Broadcast should error even if the target shape is the same as the
# underlying data shape, because the semantic size doesn't match.
two_d = jax.lax.broadcast_in_dim(one_d, (4, 5), (1,))
return two_d
msg = r"got operand of shape \(\[dynamic\],\), target broadcast shape \(4, 5\)"
with self.assertRaisesRegex(TypeError, msg):
jax.vmap(func, out_axes=batching.jumble_axis)(ins)
def test_broadcast_in_dim_to_doubly_ragged(self):
ins1 = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
ins2 = lax.convert_element_type(jnp.array([2, 5, 1]), core.bint(6))
def func(size1, size2):
one_d = jnp.arange(size1, dtype='int32')
two_d = jax.lax.broadcast_in_dim(one_d, (size1, size2), (0,))
return two_d
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins1, ins2)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5, 6), 1)
self.assertAllClose(p.data, data)
def test_squeeze_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jax.lax.broadcast_in_dim(one_d, (size, 1), (0,))
one_again = jax.lax.squeeze(two_d, dimensions=[1])
return one_again
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5), 1)
self.assertAllClose(p.data, data)
def test_broadcast_to_while_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jnp.broadcast_to(one_d, (4, size))
return two_d
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 4, 5), 2)
self.assertAllClose(p.data, data)
def test_broadcast_to_doubly_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jnp.broadcast_to(one_d, (size, size))
return two_d
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5, 5), 2)
self.assertAllClose(p.data, data)
def test_transpose_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jnp.broadcast_to(one_d, (7, size))
return jnp.transpose(two_d, [1, 0])
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
data = jax.lax.broadcasted_iota('int32', (3, 5, 7), 1)
self.assertAllClose(p.data, data)
def test_einsum_with_ragged_tensor_dimension(self):
x_sizes = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def fprop_layer(x_size):
one_d = jnp.arange(x_size, dtype='int32')
x = jax.lax.broadcast_in_dim(one_d, (x_size, 11), [0])
wqkv = jax.lax.broadcasted_iota('int32', (3, 2, 7, 11), 1)
qkv = jnp.einsum('te,ihqe->ithq', x, wqkv)
return qkv
p = jax.vmap(fprop_layer, out_axes=batching.jumble_axis)(x_sizes)
self.assertIsInstance(p, batching.Jumble)
self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\[3,bint\{≤5\}\[3\] with value: \[3 1 4\]\.Var[0-9]+,2,7\]')
self.assertEqual(p.data.shape, (3, 3, 5, 2, 7))
@parameterized.parameters((True,), (False,))
def test_einsum_with_ragged_tensor_and_contract_dimensions(self, disable_jit):
with jax.disable_jit(disable_jit):
ragged_sizes = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def fprop_layer(ragged_size):
one_d = jnp.arange(ragged_size, dtype='int32')
alpha = jax.lax.broadcast_in_dim(one_d, (ragged_size, ragged_size, 2), [1])
v = jax.lax.broadcast_in_dim(one_d, (ragged_size, 2, 7), [0])
inner = jnp.einsum('tsh,shq->thq', alpha, v)
return inner
p = jax.vmap(fprop_layer, out_axes=batching.jumble_axis)(ragged_sizes)
self.assertIsInstance(p, batching.Jumble)
self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\[bint\{≤5\}\[3\] with value: \[3 1 4\]\.Var[0-9]+,2,7\]')
self.assertEqual(p.data.shape, (3, 5, 2, 7))
def test_split_while_ragged(self):
ins = lax.convert_element_type(jnp.array([3, 1, 4]), core.bint(5))
def func(size):
one_d = jnp.arange(size, dtype='int32')
two_d = jnp.broadcast_to(one_d, (2, size))
part_1, part_2 = two_d
return part_1
p = jax.vmap(func, out_axes=batching.jumble_axis)(ins)
self.assertIsInstance(p, batching.Jumble)
self.assertRegex(str(p.aval), r'Var[0-9]+:3 => i32\[bint\{≤5\}\[3\] with value: \[3 1 4\]\.Var[0-9]+\]')
data = jax.lax.broadcasted_iota('int32', (3, 5), 1)
self.assertAllClose(p.data, data)
@parameterized.parameters((True,), (False,))
@unittest.skip("test fails at head")
def test_jumble_map_end_to_end_fprop_layer(self, disable_jit):
def fprop_layer(params, x):
((xnorm_scale, xnorm_bias), (wqkv, wqkv_bias), (wo, wo_bias),
(ynorm_scale, ynorm_bias), (w_i, w_i_bias), (w_o, w_o_bias)) = params
xnorm = jax.nn.standardize(x) * xnorm_scale + xnorm_bias
qkv = jnp.einsum('te,ihqe->ithq', xnorm, wqkv) + wqkv_bias[:, None]
q, k, v = qkv
outer = jnp.einsum('thq,shq->tsh', q, k) / jnp.asarray(
jnp.sqrt(v.shape[-1]), dtype=x.dtype)
alpha = jax.nn.softmax(outer, 2)
inner = jnp.einsum('tsh,shq->thq', alpha, v)
y = jnp.einsum('thq,hqe->te', inner, wo) + wo_bias + x
ynorm = jax.nn.standardize(y) * ynorm_scale + ynorm_bias
act = jax.nn.gelu(jnp.einsum('te,ef->tf', ynorm, w_i) + w_i_bias)
z = jnp.einsum('tf,fe->te', act, w_o) + w_o_bias + y
return z
params = [
(jnp.ones(128), jnp.zeros(128)), # xnorm_scale, xnorm_bias
(jnp.ones((3, 16, 64, 128)), jnp.zeros((3, 16, 64))), # wqkv, wqkv_bias
(jnp.ones((16, 64, 128)), jnp.zeros(128)), # wo, wo_bias
(jnp.ones(128), jnp.zeros(128)), # ynorm_scale, ynorm_bias
(jnp.ones((128, 4096)), jnp.zeros(4096)), # w_i, w_i_bias
(jnp.ones((4096, 128)), jnp.zeros(128)), # w_o, w_o_bias
]
xs = [
jnp.zeros((512, 128)),
jnp.zeros((386, 128)),
jnp.zeros((420, 128)),
]
def jumble_stack(xs: list[jax.Array]) -> batching.Jumble:
max_length = max(len(x) for x in xs)
lengths = jnp.array([len(x) for x in xs])
lengths = jax.lax.convert_element_type(lengths, core.bint(max_length))
xs_padded = jnp.stack([jnp.zeros((max_length, 128), dtype=x.dtype
).at[:x.shape[0]].set(x) for x in xs])
# binder = i
binder = core.Var('', core.ShapedArray((), np.dtype('int32')))
# elt_ty = f32[[3, 1, 4].i, 128]
elt_ty = core.DShapedArray((batching.IndexedAxisSize(binder, lengths), 128),
xs_padded.dtype)
# aval = i:(Fin 3) => f32[[3, 1, 4].i, 128]
aval = batching.JumbleTy(binder, len(xs), elt_ty)
xs_jumble = batching.Jumble(aval, xs_padded)
return xs_jumble
with jax.disable_jit(disable_jit):
xs_jumble = jumble_stack(xs)
fprop_batched = jax.vmap(fprop_layer,
in_axes=(None, batching.jumble_axis),
out_axes=batching.jumble_axis,
axis_size=3)
result_jumble = fprop_batched(params, xs_jumble)
self.assertIsInstance(result_jumble, batching.Jumble)
regex = r'Var[0-9]+:3 => (f32|f64)\[bint\{≤512\}\[3\] with value: \[512 386 420\]\.Var[0-9]+,128\]'
self.assertRegex(str(result_jumble.aval), regex)
self.assertAllClose(result_jumble.data.shape, (3, 512, 128))
def jumble_map(f):
def mapped(*jumbles):
return jax.vmap(f, in_axes=batching.jumble_axis, out_axes=batching.jumble_axis,
axis_size=jumbles[0].aval.length)(*jumbles)
return mapped
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| JumbleTest |
python | getsentry__sentry | tests/sentry/issues/test_occurrence_consumer.py | {
"start": 13222,
"end": 14787
} | class ____(IssueOccurrenceTestBase):
def test_lookup_event_doesnt_exist(self) -> None:
message = get_test_message(self.project.id, include_event=False)
with pytest.raises(EventLookupError):
with self.feature("organizations:profile-file-io-main-thread-ingest"):
_process_message(message)
@django_db_all
def test_transaction_lookup(self) -> None:
from sentry.event_manager import EventManager
event_data = load_data("transaction")
event_data["timestamp"] = before_now(minutes=1).isoformat()
event_data["start_timestamp"] = before_now(minutes=1, seconds=1).isoformat()
event_data["event_id"] = "d" * 32
manager = EventManager(data=event_data)
manager.normalize()
event1 = manager.save(self.project.id)
assert event1.get_event_type() == "transaction"
message = get_test_message(
self.project.id,
include_event=False,
event_id=event1.event_id,
type=PerformanceSlowDBQueryGroupType.type_id,
)
with self.feature("organizations:performance-slow-db-query-ingest"):
processed = _process_message(message)
assert processed is not None
occurrence, _ = processed[0], processed[1]
assert occurrence is not None
fetched_event = self.eventstore.get_event_by_id(self.project.id, occurrence.event_id)
assert fetched_event is not None
assert fetched_event.get_event_type() == "transaction"
| IssueOccurrenceLookupEventIdTest |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 3625,
"end": 4035
} | class ____:
def __init__(self, title, user, collaborators=None, categories=None, id_=None):
self.title = title
self.user = user
self.collaborators = collaborators or [] # List/tuple of users
self.categories = categories
self.id = id_
def __contains__(self, item):
return item.name in [each.name for each in self.collaborators]
###### Schemas #####
| Blog |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 37302,
"end": 37440
} | class ____(Interface):
"""A list object representing all known translation directories
for an application"""
| ITranslationDirectories |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | {
"start": 14436,
"end": 15280
} | class ____(_regconfig_fn):
"""The PostgreSQL ``websearch_to_tsquery`` SQL function.
This function applies automatic casting of the REGCONFIG argument
to use the :class:`_postgresql.REGCONFIG` datatype automatically,
and applies a return type of :class:`_postgresql.TSQUERY`.
Assuming the PostgreSQL dialect has been imported, either by invoking
``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
engine using ``create_engine("postgresql...")``,
:class:`_postgresql.websearch_to_tsquery` will be used automatically when
invoking ``sqlalchemy.func.websearch_to_tsquery()``, ensuring the correct
argument and return type handlers are used at compile and execution time.
.. versionadded:: 2.0.0rc1
"""
inherit_cache = True
type = types.TSQUERY
| websearch_to_tsquery |
python | django__django | tests/generic_inline_admin/admin.py | {
"start": 287,
"end": 370
} | class ____(admin.ModelAdmin):
inlines = [
MediaInline,
]
| EpisodeAdmin |
python | huggingface__transformers | src/transformers/models/idefics2/modeling_idefics2.py | {
"start": 17869,
"end": 21526
} | class ____(Idefics2PreTrainedModel):
config: Idefics2VisionConfig
input_modalities = ("image",)
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_can_record_outputs = {
"hidden_states": Idefics2EncoderLayer,
"attentions": Idefics2VisionAttention,
}
def __init__(self, config: Idefics2VisionConfig):
super().__init__(config)
embed_dim = config.hidden_size
self.config = config
self.embeddings = Idefics2VisionEmbeddings(config)
self.encoder = Idefics2Encoder(config)
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
def get_input_embeddings(self):
return self.embeddings
def set_input_embeddings(self, value):
self.embeddings = value
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values,
patch_attention_mask: Optional[torch.BoolTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BaseModelOutput]:
r"""
patch_attention_mask (`torch.BoolTensor` of shape `(batch_size, num_patches_height, num_patches_width)`, *optional*):
The attention mask for the patches.
"""
batch_size = pixel_values.size(0)
if patch_attention_mask is None:
patch_size = self.config.patch_size
patch_attention_mask = torch.ones(
(
batch_size,
pixel_values.size(2) // patch_size,
pixel_values.size(3) // patch_size,
)
)
patch_attention_mask = patch_attention_mask.to(dtype=torch.bool, device=pixel_values.device)
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
patch_attention_mask = patch_attention_mask.view(batch_size, -1)
# The call to `_upad_input` in `_flash_attention_forward` is expensive
# So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
# avoiding passing the attention_mask, which is equivalent to attending to the full sequence
if not torch.any(~patch_attention_mask):
patch_attention_mask = None
elif self.config._attn_implementation != "flash_attention_2":
patch_attention_mask = _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
encoder_outputs: BaseModelOutput = self.encoder(
inputs_embeds=hidden_states,
attention_mask=patch_attention_mask,
**kwargs,
)
last_hidden_state = encoder_outputs.last_hidden_state
last_hidden_state = self.post_layernorm(last_hidden_state)
return BaseModelOutput(last_hidden_state=last_hidden_state)
# Copied from transformers.models.llama.modeling_llama.repeat_kv
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Idefics2
| Idefics2VisionTransformer |
python | encode__starlette | starlette/testclient.py | {
"start": 2043,
"end": 2166
} | class ____(Exception):
def __init__(self, session: WebSocketTestSession) -> None:
self.session = session
| _Upgrade |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 37268,
"end": 42779
} | class ____(Operation):
def __init__(self, function, *, name=None):
super().__init__(name=name)
self.function = function
def call(self, elements):
return backend.core.vectorized_map(self.function, elements)
def compute_output_spec(self, elements):
x = tree.map_structure(lambda t: t[0], elements)
n = tree.flatten(elements)[0].shape[0]
y = backend.compute_output_spec(self.function, x)
def append_batch_axis(t):
return KerasTensor(
shape=(n,) + t.shape,
dtype=t.dtype,
sparse=t.sparse,
ragged=t.ragged,
)
y = tree.map_structure(append_batch_axis, y)
return y
def get_config(self):
config = super().get_config()
config.update({"function": self.function})
return config
@classmethod
def from_config(cls, config):
config = config.copy()
config["function"] = serialization_lib.deserialize_keras_object(
config["function"]
)
return cls(**config)
@keras_export("keras.ops.vectorized_map")
def vectorized_map(function, elements):
"""Parallel map of `function` on axis 0 of tensor(s) `elements`.
Schematically, `vectorized_map` implements the following,
in the case of a single tensor input `elements`:
```python
def vectorized_map(function, elements):
outputs = []
for e in elements:
outputs.append(function(e))
return np.stack(outputs)
```
In the case of an iterable of tensors `elements`,
it implements the following:
```python
def vectorized_map(function, elements):
batch_size = elements[0].shape[0]
outputs = []
for index in range(batch_size):
outputs.append(function([e[index] for e in elements]))
return np.stack(outputs)
```
In this case, `function` is expected to take as input
a single list of tensor arguments.
"""
if any_symbolic_tensors((elements,)):
return VectorizedMap(function)(elements)
return backend.core.vectorized_map(function, elements)
@keras_export("keras.ops.is_tensor")
def is_tensor(x):
"""Check whether the given object is a tensor.
Note: This checks for backend specific tensors so passing a TensorFlow
tensor would return `False` if your backend is PyTorch or JAX.
Args:
x: A variable.
Returns:
`True` if `x` is a tensor, otherwise `False`.
"""
return backend.core.is_tensor(x)
@keras_export("keras.ops.custom_gradient")
def custom_gradient(f):
"""Decorator to define a function with a custom gradient.
This decorator allows fine grained control over the gradients of a sequence
for operations. This may be useful for multiple reasons, including providing
a more efficient or numerically stable gradient for a sequence of
operations.
Args:
f: Function `f(*args)` that returns a tuple
`(output, grad_fn)`, where:
- `args` is a sequence of (nested structures of) tensor inputs to
the function.
- `output` is a (nested structure of) tensor outputs of applying
operations in `forward_fn` to `args`.
- `grad_fn` is a function with the signature `grad_fn(*args,
upstream)` which returns a tuple of tensors the same size as
(flattened) `args`: the derivatives of tensors in `output` with
respect to the tensors in `args`. `upstream` is a tensor or
sequence of tensors holding the initial value gradients for each
tensor in `output`.
Returns:
A function `h(*args)` which returns the same value as
`f(*args)[0]` and whose gradient is determined by
`f(*args)[1]`.
Examples:
1. Backend-agnostic example.
```python
@ops.custom_gradient
def log1pexp(x):
e = ops.exp(x)
def grad(*args, upstream=None):
if upstream is None:
(upstream,) = args
return ops.multiply(upstream, 1.0 - 1.0 / ops.add(1, e))
return ops.log(1 + e), grad
```
Note that the grad function that returns gradient computation
requires `args` as well as an `upstream` keyword argument, depending
on the backend being set. With the JAX and TensorFlow backends,
it requires only one argument, whereas it might use the `upstream`
argument in the case of the PyTorch backend.
When working with TensorFlow/JAX backend, `grad(upstream)`
is sufficient. With PyTorch, the `grad` function requires
`*args` as well as `upstream`, e.g. `def grad(*args, upstream)`.
Follow the previous example to use `@ops.custom_gradient` in
a way that is compatible with all backends.
2. Here's JAX & TensorFlow-specific example:
```python
@ops.custom_gradient
def log1pexp(x):
e = ops.exp(x)
def grad(upstream):
return ops.multiply(upstream, 1.0 - 1.0 / ops.add(1, e))
return ops.log(1 + e), grad
```
3. Lastly, here's a PyTorch-specific example,
using `*args` & `upstream`:
```python
@ops.custom_gradient
def log1pexp(x):
e = ops.exp(x)
def grad(*args, upstream):
return ops.multiply(upstream, 1.0 - 1.0 / ops.add(1, e))
return ops.log(1 + e), grad
```
"""
return backend.core.custom_gradient(f)
| VectorizedMap |
python | eventlet__eventlet | tests/event_test.py | {
"start": 73,
"end": 3063
} | class ____(LimitedTestCase):
def test_waiting_for_event(self):
evt = eventlet.Event()
value = 'some stuff'
def send_to_event():
evt.send(value)
eventlet.spawn_n(send_to_event)
self.assertEqual(evt.wait(), value)
def test_multiple_waiters(self):
self._test_multiple_waiters(False)
def test_multiple_waiters_with_exception(self):
self._test_multiple_waiters(True)
def _test_multiple_waiters(self, exception):
evt = eventlet.Event()
results = []
def wait_on_event(i_am_done):
evt.wait()
results.append(True)
i_am_done.send()
if exception:
raise Exception()
waiters = []
count = 5
for i in range(count):
waiters.append(eventlet.Event())
eventlet.spawn_n(wait_on_event, waiters[-1])
eventlet.sleep() # allow spawns to start executing
evt.send()
for w in waiters:
w.wait()
self.assertEqual(len(results), count)
def test_reset(self):
evt = eventlet.Event()
# calling reset before send should throw
self.assertRaises(AssertionError, evt.reset)
value = 'some stuff'
def send_to_event():
evt.send(value)
eventlet.spawn_n(send_to_event)
self.assertEqual(evt.wait(), value)
# now try it again, and we should get the same exact value,
# and we shouldn't be allowed to resend without resetting
value2 = 'second stuff'
self.assertRaises(AssertionError, evt.send, value2)
self.assertEqual(evt.wait(), value)
# reset and everything should be happy
evt.reset()
def send_to_event2():
evt.send(value2)
eventlet.spawn_n(send_to_event2)
self.assertEqual(evt.wait(), value2)
def test_double_exception(self):
evt = eventlet.Event()
# send an exception through the event
evt.send(exc=RuntimeError('from test_double_exception'))
self.assertRaises(RuntimeError, evt.wait)
evt.reset()
# shouldn't see the RuntimeError again
eventlet.Timeout(0.001)
self.assertRaises(eventlet.Timeout, evt.wait)
def test_wait_timeout_ok():
evt = eventlet.Event()
delay = 0.1
eventlet.spawn_after(delay, evt.send, True)
t1 = eventlet.hubs.get_hub().clock()
with eventlet.Timeout(delay * 3, False):
result = evt.wait(timeout=delay * 2)
td = eventlet.hubs.get_hub().clock() - t1
assert result
assert td >= delay
def test_wait_timeout_exceed():
evt = eventlet.Event()
delay = 0.1
eventlet.spawn_after(delay * 2, evt.send, True)
t1 = eventlet.hubs.get_hub().clock()
with eventlet.Timeout(delay, False):
result = evt.wait(timeout=delay)
td = eventlet.hubs.get_hub().clock() - t1
assert not result
assert td >= delay
| TestEvent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.