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 | pytorch__pytorch | torch/_dynamo/package.py | {
"start": 4108,
"end": 4360
} | class ____:
module: str
firstlineno: int
lastlineno: int
checksum: str
content: str
@functools.cache
def _get_module_content(module: types.ModuleType) -> str:
return inspect.getsource(module)
@dataclasses.dataclass
| InlinedSource |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 64095,
"end": 65266
} | class ____(DateConverter):
# docstring inherited
def __init__(self, formats=None, zero_formats=None, offset_formats=None,
show_offset=True, *, interval_multiples=True):
self._formats = formats
self._zero_formats = zero_formats
self._offset_formats = offset_formats
self._show_offset = show_offset
self._interval_multiples = interval_multiples
super().__init__()
def axisinfo(self, unit, axis):
# docstring inherited
tz = unit
majloc = AutoDateLocator(tz=tz,
interval_multiples=self._interval_multiples)
majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
zero_formats=self._zero_formats,
offset_formats=self._offset_formats,
show_offset=self._show_offset)
datemin = datetime.date(1970, 1, 1)
datemax = datetime.date(1970, 1, 2)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
default_limits=(datemin, datemax))
| ConciseDateConverter |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modeling_instructblipvideo.py | {
"start": 22234,
"end": 25537
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = InstructBlipVideoQFormerAttention(config)
self.layer_idx = layer_idx
if layer_idx % config.cross_attention_frequency == 0:
self.crossattention = InstructBlipVideoQFormerAttention(config, is_cross_attention=True)
self.has_cross_attention = True
else:
self.has_cross_attention = False
self.intermediate = InstructBlipVideoQFormerIntermediate(config)
self.output = InstructBlipVideoQFormerOutput(config)
self.intermediate_query = InstructBlipVideoQFormerIntermediate(config)
self.output_query = InstructBlipVideoQFormerOutput(config)
def forward(
self,
hidden_states,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
query_length=0,
**kwargs: Unpack[TransformersKwargs],
):
attention_output = self.attention(
hidden_states,
attention_mask=attention_mask,
**kwargs,
)
if query_length > 0:
query_attention_output = attention_output[:, :query_length, :]
if self.has_cross_attention:
if encoder_hidden_states is None:
raise ValueError("encoder_hidden_states must be given for cross-attention layers")
query_attention_output = self.crossattention(
query_attention_output,
attention_mask=attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
**kwargs,
)
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk_query,
self.chunk_size_feed_forward,
self.seq_len_dim,
query_attention_output,
)
if attention_output.shape[1] > query_length:
layer_output_text = apply_chunking_to_forward(
self.feed_forward_chunk,
self.chunk_size_feed_forward,
self.seq_len_dim,
attention_output[:, query_length:, :],
).to(layer_output.device)
layer_output = torch.cat([layer_output, layer_output_text], dim=1)
else:
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk,
self.chunk_size_feed_forward,
self.seq_len_dim,
attention_output,
)
return layer_output
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
def feed_forward_chunk_query(self, attention_output):
intermediate_output = self.intermediate_query(attention_output)
layer_output = self.output_query(intermediate_output, attention_output)
return layer_output
| InstructBlipVideoQFormerLayer |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/client.py | {
"start": 1648,
"end": 1971
} | class ____(QtKernelClientMixin, ThreadedKernelClient):
""" A KernelClient that provides signals and slots.
"""
iopub_channel_class = Type(QtZMQSocketChannel)
shell_channel_class = Type(QtZMQSocketChannel)
stdin_channel_class = Type(QtZMQSocketChannel)
hb_channel_class = Type(QtHBChannel)
| QtKernelClient |
python | readthedocs__readthedocs.org | readthedocs/projects/admin.py | {
"start": 3405,
"end": 6941
} | class ____(admin.SimpleListFilter):
"""Filter for projects that are potentially SPAM."""
title = "Spam Threshold"
parameter_name = "spam_threshold"
NOT_ENOUGH_SCORE = "not_enough_score"
DONT_SHOW_ADS = "dont_show_ads"
DENY_ON_ROBOTS = "deny_on_robots"
DONT_SERVE_DOCS = "dont_serve_docs"
DONT_SHOW_DASHBOARD = "dont_show_dashboard"
DELETE_PROJECT = "delete_project"
def lookups(self, request, model_admin):
return (
(
self.NOT_ENOUGH_SCORE,
_("Not spam (1-{})").format(
settings.RTD_SPAM_THRESHOLD_DONT_SHOW_ADS,
),
),
(
self.DONT_SHOW_ADS,
_("Don't show Ads ({}-{})").format(
settings.RTD_SPAM_THRESHOLD_DONT_SHOW_ADS,
settings.RTD_SPAM_THRESHOLD_DENY_ON_ROBOTS,
),
),
(
self.DENY_ON_ROBOTS,
_("Deny on robots ({}-{})").format(
settings.RTD_SPAM_THRESHOLD_DENY_ON_ROBOTS,
settings.RTD_SPAM_THRESHOLD_DONT_SHOW_DASHBOARD,
),
),
(
self.DONT_SHOW_DASHBOARD,
_("Don't show dashboard ({}-{})").format(
settings.RTD_SPAM_THRESHOLD_DONT_SHOW_DASHBOARD,
settings.RTD_SPAM_THRESHOLD_DONT_SERVE_DOCS,
),
),
(
self.DONT_SERVE_DOCS,
_("Don't serve docs ({}-{})").format(
settings.RTD_SPAM_THRESHOLD_DONT_SERVE_DOCS,
settings.RTD_SPAM_THRESHOLD_DELETE_PROJECT,
),
),
(
self.DELETE_PROJECT,
_("Delete project (>={})").format(
settings.RTD_SPAM_THRESHOLD_DELETE_PROJECT,
),
),
)
def queryset(self, request, queryset):
queryset = queryset.annotate(spam_score=Sum("spam_rules__value"))
if self.value() == self.NOT_ENOUGH_SCORE:
return queryset.filter(
spam_score__gte=1,
spam_score__lt=settings.RTD_SPAM_THRESHOLD_DONT_SHOW_ADS,
)
if self.value() == self.DONT_SHOW_ADS:
return queryset.filter(
spam_score__gte=settings.RTD_SPAM_THRESHOLD_DONT_SHOW_ADS,
spam_score__lt=settings.RTD_SPAM_THRESHOLD_DENY_ON_ROBOTS,
)
if self.value() == self.DENY_ON_ROBOTS:
return queryset.filter(
spam_score__gte=settings.RTD_SPAM_THRESHOLD_DENY_ON_ROBOTS,
spam_score__lt=settings.RTD_SPAM_THRESHOLD_DONT_SHOW_DASHBOARD,
)
if self.value() == self.DONT_SHOW_DASHBOARD:
return queryset.filter(
spam_score__gte=settings.RTD_SPAM_THRESHOLD_DONT_SHOW_DASHBOARD,
spam_score__lt=settings.RTD_SPAM_THRESHOLD_DONT_SERVE_DOCS,
)
if self.value() == self.DONT_SERVE_DOCS:
return queryset.filter(
spam_score__gte=settings.RTD_SPAM_THRESHOLD_DONT_SERVE_DOCS,
spam_score__lt=settings.RTD_SPAM_THRESHOLD_DELETE_PROJECT,
)
if self.value() == self.DELETE_PROJECT:
return queryset.filter(
spam_score__gte=settings.RTD_SPAM_THRESHOLD_DELETE_PROJECT,
)
return queryset
@admin.register(Project)
| ProjectSpamThreshold |
python | pytorch__pytorch | test/inductor/test_cpu_select_algorithm.py | {
"start": 4778,
"end": 115149
} | class ____(BaseTestSelectAlgorithm):
common = check_model
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (1, 2, 1000))
@parametrize("in_features", (1, 1000))
@parametrize("out_features", (1, 1024))
@parametrize("bias", (True, False))
@parametrize("input_3d", (True, False))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_static_shapes(
self, batch_size, in_features, out_features, bias, input_3d, dtype
):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x)
counters.clear()
mod = M(bias=bias).to(dtype=dtype).eval()
B = (2, batch_size) if input_3d else (batch_size,)
v = torch.randn(*B, in_features).to(dtype=dtype)
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
if (
counters["inductor"]["decompose_mm"] > 0
or counters["inductor"]["decompose_addmm"] > 0
):
# This is a special case where we go directly with vectorized codegen
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 0)
else:
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("in_features", (1000,))
@parametrize("out_features", (1024,))
@parametrize("bias", (True,))
@dtypes(
torch.float,
)
def test_linear_wgt_multi_users(self, in_features, out_features, bias, dtype):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.embeddings = torch.nn.Embedding(out_features, in_features)
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.linear.weight = self.embeddings.weight
def forward(self, x):
x = self.embeddings(x)
return self.linear(x)
counters.clear()
mod = M(bias=bias).to(dtype=dtype).eval()
v = torch.LongTensor([[1, 2, 4, 5], [4, 3, 2, 9]])
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bias", (True, False))
@dtypes(torch.float)
def test_linear_input_transpose(self, bias, dtype):
batch_size = 384
in_features = 196
out_features = 384
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
@torch.compile
def forward(self, x):
return self.linear(x)
counters.clear()
mod = M(bias=bias).to(dtype=dtype).eval()
v = torch.randn(in_features, batch_size).to(dtype=dtype)
self.common(mod, (v.transpose(0, 1),))
# TODO(jgong5): support transposed input
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 0)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (384,))
@parametrize("in_features", (196,))
@parametrize("out_features", (384, 385))
@parametrize("bias", (True, False))
@parametrize(
"epilogue",
(
"relu",
"gelu",
"silu",
"sigmoid",
"tanh",
"hardswish",
"hardsigmoid",
"leaky_relu",
"hardtanh",
"add",
"sub",
"mul",
"div",
),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
@torch.fx.experimental._config.patch(use_duck_shape=False)
@torch._dynamo.config.patch(specialize_float=True)
def test_linear_with_pointwise(
self, batch_size, in_features, out_features, bias, epilogue, dtype
):
class M(torch.nn.Module):
def __init__(self, bias, epilogue, other):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.epilogue = _get_epilogue(epilogue, other)
def forward(self, x):
return self.epilogue(self.linear(x))
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
u = torch.randn(batch_size, out_features).to(dtype=dtype)
mod = M(bias=bias, epilogue=epilogue, other=u).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
if (
(
(
dtype == torch.bfloat16
and torch.ops.mkldnn._is_mkldnn_bf16_supported()
)
or (
dtype == torch.float16
and torch.ops.mkldnn._is_mkldnn_fp16_supported()
)
or (
dtype == torch.float32
and not dynamo_config.assume_static_by_default
)
)
and epilogue != "mul"
and epilogue != "div"
or (
dtype in (torch.float16, torch.bfloat16)
and epilogue == "add"
and not bias
)
):
# Several scenarios where epilogue fusion is not counted in:
# 1. For bfloat16, the epilogue fusion is part of the template,
# not fused via scheduler. This will also be true for float16 when
# hardware has the float16 instruction. And this will also be true
# for float32 dynamic mode. The exception is mul or div fusion
# which is not supported for oneDNN linear.
# 2. For bfloat16/float16, when oneDNN linear is not applied, linear w/o bias
# plus epilogue add is treated as linear w/ bias.
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 0)
else:
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (384,))
@parametrize("in_features", (196,))
@parametrize("out_features", (128, 129))
@parametrize("bias", (True, False))
@parametrize(
"epilogue",
(
"none",
"relu",
"add",
"sub",
"mul",
),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_with_transpose(
self, batch_size, in_features, out_features, bias, epilogue, dtype
):
class M(torch.nn.Module):
def __init__(self, bias, epilogue, other):
super().__init__()
self.epilogue = _get_epilogue(epilogue, other)
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x, y):
return self.epilogue(self.linear(x)).transpose(0, 1) + y
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
u = torch.randn(out_features, batch_size).to(dtype=dtype)
other = torch.randn(batch_size, out_features).to(dtype=dtype)
mod = M(bias=bias, epilogue=epilogue, other=other).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v, u), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (1,))
@parametrize("in_features", (16,))
@parametrize("image_size", (18,))
@parametrize("out_features", (32,))
@parametrize(
"bias",
(
False,
True,
),
)
@parametrize(
"has_non_epilogue_users",
(
True,
False,
),
)
@dtypes(torch.bfloat16)
def test_linear_with_permute(
self,
batch_size,
in_features,
image_size,
out_features,
bias,
has_non_epilogue_users,
dtype,
):
# Reproducer from the convnext model in timm
class M(torch.nn.Module):
def __init__(self, bias, has_non_epilogue_users):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self._frozen_param398 = torch.randn(batch_size, out_features, 1, 1)
self.conv = torch.nn.Conv2d(
out_features,
out_features,
kernel_size=7,
padding=3,
groups=out_features,
)
self.linear2 = torch.nn.Linear(out_features, out_features, bias)
self._frozen_param400 = torch.randn(batch_size, out_features, 1, 1)
self.has_non_epilogue_users = has_non_epilogue_users
def forward(self, mul_272, _convolution_pointwise_default_31):
out1 = torch.ops.prims.convert_element_type.default(
mul_272, torch.bfloat16
)
mul_272 = None
_linear_pointwise_default_131 = self.linear(out1)
permute_188 = torch.ops.aten.permute.default(
_linear_pointwise_default_131, [0, 3, 1, 2]
)
mul_273 = torch.ops.aten.mul.Tensor(permute_188, self._frozen_param398)
add_187 = torch.ops.aten.add.Tensor(
mul_273, _convolution_pointwise_default_31
)
convert_element_type_847 = torch.ops.prims.convert_element_type.default(
add_187, torch.bfloat16
)
_convolution_pointwise_default_29 = self.conv(convert_element_type_847)
permute_189 = torch.ops.aten.permute.default(
_convolution_pointwise_default_29, [0, 2, 3, 1]
)
permute_189 = self.linear2(permute_189)
permute_189 = torch.ops.aten.permute.default(permute_189, [0, 3, 1, 2])
permute_189 = torch.ops.aten.mul.Tensor(
permute_189, self._frozen_param400
)
# If template_buffer will be used by nodes other than the epilogue nodes,
# we can't alias the template_buffer with the Y buffer.
if self.has_non_epilogue_users:
add_191 = torch.ops.aten.add.Tensor(permute_189, add_187)
return add_191
return permute_189
view_12 = torch.randn(batch_size, image_size, image_size, in_features)
_convolution_pointwise_default_31 = torch.randn(
batch_size, out_features, image_size, image_size
).to(memory_format=torch.channels_last)
mod = M(bias=bias, has_non_epilogue_users=has_non_epilogue_users).eval()
with verify(dtype) as (atol, rtol), torch.cpu.amp.autocast():
self.common(
mod,
(
view_12,
_convolution_pointwise_default_31,
),
atol=atol,
rtol=rtol,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 2)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (8,))
@parametrize("in_features", (3,))
@parametrize("linear_in_features", (384,))
@parametrize("out_features", (196,))
@parametrize("bias", (True,))
@dtypes(torch.float)
def test_linear_with_input_of_flexible_layout(
self, batch_size, in_features, linear_in_features, out_features, bias, dtype
):
# Reproducer from the resmlp_12_224 model in timm
flatten_BS = int(batch_size * linear_in_features)
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.conv = torch.nn.Conv2d(
in_features,
linear_in_features,
kernel_size=16,
padding=0,
stride=16,
dilation=1,
groups=1,
)
self._frozen_param151 = torch.randn(1, 1, linear_in_features)
self._frozen_param3 = torch.randn(1, 1, linear_in_features)
self._frozen_param2 = torch.randn(linear_in_features)
self.linear = torch.nn.Linear(out_features, out_features, bias)
def forward(self, arg150_1):
_convolution_pointwise_default = self.conv(arg150_1)
view_73 = torch.ops.aten.reshape.default(
_convolution_pointwise_default,
[batch_size, linear_in_features, out_features],
)
_convolution_pointwise_default = None
permute_62 = torch.ops.aten.permute.default(view_73, [0, 2, 1])
view_73 = None
mul_111 = torch.ops.aten.mul.Tensor(self._frozen_param151, permute_62)
add_73 = torch.ops.aten.add.Tensor(self._frozen_param3, mul_111)
permute_63 = torch.ops.aten.permute.default(add_73, [0, 2, 1])
add_73 = None
view_74 = torch.ops.aten.reshape.default(
permute_63, [flatten_BS, out_features]
)
permute_63 = None
_mkl_linear_36 = self.linear(view_74)
view_75 = torch.ops.aten.reshape.default(
_mkl_linear_36, [batch_size, linear_in_features, out_features]
)
_mkl_linear_36 = None
permute_65 = torch.ops.aten.permute.default(view_75, [0, 2, 1])
view_75 = None
mul_112 = torch.ops.aten.mul.Tensor(self._frozen_param2, permute_65)
_frozen_param2 = permute_65 = None
add_74 = torch.ops.aten.add.Tensor(permute_62, mul_112)
permute_62 = mul_112 = None
return add_74
v = torch.randn(batch_size, in_features, 224, 224).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (8,))
@parametrize("in_features", (128,))
@parametrize("size_0", (4,))
@parametrize("size_1", (14,))
@parametrize("out_features", (512,))
@parametrize("out_features_conv", (256,))
@parametrize(
"bias",
(
False,
True,
),
)
@parametrize(
"epilogue",
(
False,
True,
),
)
@dtypes(torch.float32)
def test_linear_unsupported_epilogue_fusion(
self,
batch_size,
in_features,
size_0,
size_1,
out_features,
out_features_conv,
bias,
epilogue,
dtype,
):
img_size_0 = int(size_0 * size_0)
img_size_1 = int(size_1 * size_1)
conv_shape = int(size_0 * size_1)
flatten_BS = int(batch_size * size_0 * size_0 * size_1 * size_1)
# Reproducer from the jx_nest_base model in timm
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear1 = torch.nn.Linear(in_features, in_features, bias=bias)
self.linear2 = torch.nn.Linear(out_features, in_features, bias=bias)
self.conv = torch.nn.Conv2d(
in_features,
out_features_conv,
kernel_size=3,
padding=1,
stride=1,
dilation=1,
groups=1,
)
self.epilogue = epilogue
def forward(self, mul_239, view_425, add_184):
_mkl_linear_91 = self.linear1(view_425)
view_426 = torch.ops.aten.reshape.default(
_mkl_linear_91, [batch_size, img_size_0, img_size_1, in_features]
)
_mkl_linear_91 = None
add_187 = torch.ops.aten.add.Tensor(add_184, view_426)
add_184 = view_426 = None
view_429 = torch.ops.aten.reshape.default(
mul_239, [flatten_BS, out_features]
)
mul_239 = None
_mkl_linear_89 = self.linear2(view_429)
if self.epilogue:
_mkl_linear_89 = torch.pow(_mkl_linear_89, 2)
_mkl_linear_89 = test_operators.realize(_mkl_linear_89)
view_430 = torch.ops.aten.reshape.default(
_mkl_linear_89, [batch_size, img_size_0, img_size_1, in_features]
)
_mkl_linear_89 = None
add_191 = torch.ops.aten.add.Tensor(add_187, view_430)
add_187 = view_430 = None
view_431 = torch.ops.aten.reshape.default(
add_191, [batch_size, size_0, size_0, size_1, size_1, in_features]
)
add_191 = None
permute_203 = torch.ops.aten.permute.default(
view_431, [0, 1, 3, 2, 4, 5]
)
view_431 = None
clone_188 = torch.ops.aten.clone.default(
permute_203, memory_format=torch.contiguous_format
)
permute_203 = None
view_432 = torch.ops.aten.reshape.default(
clone_188, [batch_size, conv_shape, conv_shape, in_features]
)
clone_188 = None
permute_204 = torch.ops.aten.permute.default(view_432, [0, 3, 1, 2])
view_432 = None
_convolution_pointwise_default_1 = self.conv(permute_204)
return _convolution_pointwise_default_1
mul_239 = torch.randn(batch_size, img_size_0, img_size_1, out_features)
view_425 = torch.randn(flatten_BS, in_features)
add_184 = torch.randn(batch_size, img_size_0, img_size_1, in_features)
mod = M(bias=bias).eval()
with (
verify(dtype) as (atol, rtol),
torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16),
):
self.common(
mod,
(
mul_239,
view_425,
add_184,
),
atol=atol,
rtol=rtol,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
# TODO: change cpp_epilogue_fusion_counter to 1 once supported
self.assertEqual(
counters["inductor"]["cpp_epilogue_fusion_counter"], 1 if epilogue else 0
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (384,))
@parametrize("in_features", (196,))
@parametrize("out_features", (384, 385))
@parametrize("bias", (True, False))
@parametrize(
"unary",
("relu",),
)
@parametrize(
"binary",
(
"add",
"sub",
"mul",
"div",
),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_with_unary_binary(
self, batch_size, in_features, out_features, bias, unary, binary, dtype
):
class M(torch.nn.Module):
def __init__(self, bias, unary, binary, other):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.unary = _get_epilogue(unary)
self.binary = _get_epilogue(binary, other)
def forward(self, x):
return self.binary(self.unary(self.linear(x)))
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
u = torch.randn(batch_size, out_features).to(dtype=dtype)
mod = M(bias=bias, unary=unary, binary=binary, other=u).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (384,))
@parametrize("in_features", (196,))
@parametrize("out_features", (384,))
@parametrize("bias", (True, False))
@parametrize(
"binary",
("add",),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_with_binary_input_3d(
self, batch_size, in_features, out_features, bias, binary, dtype
):
class M(torch.nn.Module):
def __init__(self, bias, binary, other):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.binary = _get_epilogue(binary, other)
def forward(self, x):
return self.binary(self.linear(x))
counters.clear()
B = (2, batch_size)
v = torch.randn(*B, in_features).to(dtype=dtype)
u = torch.randn(*B, out_features).to(dtype=dtype)
mod = M(bias=bias, binary=binary, other=u).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@set_num_threads(1)
@dynamo_config.patch({"dynamic_shapes": True, "assume_static_by_default": False})
@parametrize("batch_size", (256,))
@parametrize("in_features", (3,))
@parametrize("out_features", (1024,))
@parametrize("out_features2", (2,))
@parametrize("bias", (True, False))
@dtypes(torch.float)
def test_linear_local_and_global_buffer_dynamic_shapes(
self, batch_size, in_features, out_features, out_features2, bias, dtype
):
# Reproducer from soft_actor_critic
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.linear1 = torch.nn.Linear(out_features, out_features, bias)
self.linear2 = torch.nn.Linear(out_features, out_features2, bias)
def forward(self, arg7_1):
addmm_3 = self.linear(arg7_1)
relu_2 = torch.ops.aten.relu.default(addmm_3)
addmm_4 = self.linear1(relu_2)
relu_3 = torch.ops.aten.relu.default(addmm_4)
addmm_5 = self.linear2(relu_3)
split_1 = torch.ops.aten.split.Tensor(addmm_5, 1, 1)
getitem_2 = split_1[0]
getitem_3 = split_1[1]
tanh_1 = torch.ops.aten.tanh.default(getitem_3)
add_62 = torch.ops.aten.add.Tensor(tanh_1, 1)
mul_36 = torch.ops.aten.mul.Tensor(add_62, 6.0)
add_69 = torch.ops.aten.add.Tensor(mul_36, -10.0)
exp_1 = torch.ops.aten.exp.default(add_69)
return (getitem_2, exp_1)
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 3)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 0)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (1024,))
@parametrize("in_features", (1024,))
@parametrize("out_features", (1024, 1025))
@parametrize("bias", (True, False))
@dtypes(torch.bfloat16, torch.half)
def test_linear_amx(self, batch_size, in_features, out_features, bias, dtype):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x)
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
vec_amx = VecAMX()
# Currently brgemm config is only added for half
if dtype == torch.half and not vec_amx.is_amx_fp16_supported():
self._check_brgemm_counter(vec_amx)
else:
self._check_amx_counter(vec_amx)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (8,))
@parametrize("in_features", (128,))
@parametrize("in_features_2", (196,))
@parametrize("out_features", (256,))
@parametrize(
"bias",
(True,),
)
@dtypes(torch.float32)
def test_linear_with_multiple_reindexers(
self,
batch_size,
in_features,
in_features_2,
out_features,
bias,
dtype,
):
flatten_BS = int(batch_size * in_features_2)
# Reproducer from the levit_128 model in timm
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.conv = torch.nn.Conv2d(
64,
128,
kernel_size=3,
padding=1,
stride=2,
dilation=1,
groups=1,
)
self.linear = torch.nn.Linear(in_features, out_features, bias=False)
self._frozen_param221 = torch.randn(out_features)
self._frozen_param389 = torch.randn(out_features)
self._frozen_param20 = torch.randn(out_features)
self._frozen_param21 = torch.randn(out_features)
def forward(self, view_368):
_mkl_linear_57 = self.linear(view_368)
view_369 = torch.ops.aten.reshape.default(
_mkl_linear_57, [batch_size, in_features_2, out_features]
)
_mkl_linear_57 = None
view_370 = torch.ops.aten.reshape.default(
view_369, [flatten_BS, out_features]
)
view_369 = None
sub_85 = torch.ops.aten.sub.Tensor(view_370, self._frozen_param221)
view_370 = _frozen_param221 = None
mul_261 = torch.ops.aten.mul.Tensor(sub_85, self._frozen_param389)
sub_85 = _frozen_param389 = None
mul_262 = torch.ops.aten.mul.Tensor(mul_261, self._frozen_param20)
mul_261 = _frozen_param20 = None
add_219 = torch.ops.aten.add.Tensor(mul_262, self._frozen_param21)
mul_262 = _frozen_param21 = None
view_371 = torch.ops.aten.reshape.default(
add_219, [batch_size, in_features_2, out_features]
)
add_219 = None
add_220 = torch.ops.aten.add.Tensor(view_371, 3)
clamp_min_35 = torch.ops.aten.clamp_min.default(add_220, 0)
add_220 = None
clamp_max_35 = torch.ops.aten.clamp_max.default(clamp_min_35, 6)
clamp_min_35 = None
mul_263 = torch.ops.aten.mul.Tensor(view_371, clamp_max_35)
view_371 = clamp_max_35 = None
div_51 = torch.ops.aten.div.Tensor(mul_263, 6)
mul_263 = None
return div_51
view_368 = torch.randn(flatten_BS, in_features)
mod = M(bias=bias).eval()
with verify(dtype) as (atol, rtol):
self.common(
mod,
(view_368,),
atol=atol,
rtol=rtol,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 2)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (384,))
@parametrize("in_features", (196,))
@parametrize("out_features", (384,))
@parametrize("bias", (True, False))
@dtypes(torch.bfloat16)
def test_linear_with_embedding(
self, batch_size, in_features, out_features, bias, dtype
):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias).to(
dtype=dtype
)
self.emb = torch.nn.Embedding(64, out_features)
def forward(self, idx, x):
return self.emb(idx) + self.linear(x)
idx = torch.randint(0, 64, (batch_size,))
x = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (idx, x), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (2,))
@parametrize("in_features", (16,))
@parametrize("seq_lens", (128,))
@parametrize("out_features", (32,))
@parametrize("bias", (True,))
@dtypes(torch.bfloat16)
def test_linear_with_indirect_indexing(
self, batch_size, in_features, seq_lens, out_features, bias, dtype
):
# Reproducer from the GPT2ForSequenceClassification model in HuggingFace
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.wte = torch.nn.Embedding(128, seq_lens)
self.wpe = torch.nn.Embedding(in_features, seq_lens)
self.linear = torch.nn.Linear(out_features, seq_lens, bias)
def forward(self, view_12, input_ids, view_9):
inputs_embeds = self.wte(input_ids)
position_ids = torch.arange(0, in_features, dtype=torch.long)
position_ids = position_ids.unsqueeze(0)
position_embeds = self.wpe(position_ids)
add = inputs_embeds + position_embeds
add_4 = view_9 + add
_linear_pointwise_default_45 = self.linear(view_12)
view_13 = torch.ops.aten.reshape.default(
_linear_pointwise_default_45, [batch_size, in_features, seq_lens]
)
out = torch.ops.aten.add.Tensor(add_4, view_13)
return out
view_12 = torch.randn(batch_size * in_features, out_features)
input_ids = torch.randint(0, 128, (batch_size, in_features))
view_9 = torch.randn(batch_size, in_features, seq_lens)
mod = M(bias=bias).eval()
with verify(dtype) as (atol, rtol), torch.cpu.amp.autocast():
self.common(
mod,
(
view_12,
input_ids,
view_9,
),
atol=atol,
rtol=rtol,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (8,))
@parametrize("in_features", (3,))
@parametrize("in_features2", (192,))
@parametrize("image_size", (224,))
@parametrize("out_features", (64,))
@parametrize(
"bias",
(True,),
)
@dtypes(torch.float32)
def test_linear_with_in_out_buffer(
self,
batch_size,
in_features,
in_features2,
image_size,
out_features,
bias,
dtype,
):
# Reproducer from the coat_lite_mini model in timm
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self._frozen_param398 = torch.randn(batch_size, out_features, 1, 1)
self.conv = torch.nn.Conv2d(
in_features,
out_features,
kernel_size=4,
padding=0,
stride=4,
dilation=1,
groups=1,
)
self.conv2 = torch.nn.Conv2d(
out_features,
out_features,
kernel_size=3,
padding=1,
stride=1,
dilation=1,
groups=out_features,
)
self.conv3 = torch.nn.Conv2d(
16,
16,
kernel_size=3,
padding=1,
stride=1,
dilation=1,
groups=16,
)
self.conv4 = torch.nn.Conv2d(
24,
24,
kernel_size=5,
padding=2,
stride=1,
dilation=1,
groups=24,
)
self.conv5 = torch.nn.Conv2d(
24,
24,
kernel_size=7,
padding=3,
stride=1,
dilation=1,
groups=24,
)
self.linear = torch.nn.Linear(out_features, in_features2, bias)
self.linear2 = torch.nn.Linear(out_features, out_features, bias)
self._frozen_param2 = torch.randn(out_features)
self._frozen_param3 = torch.randn(out_features)
self._frozen_param7 = torch.randn(out_features)
self._frozen_param8 = torch.randn(out_features)
self._frozen_param153 = torch.randn(batch_size, 1, out_features)
def forward(self, arg152_1):
_convolution_pointwise_default_35 = self.conv(arg152_1)
arg152_1 = None
view_168 = torch.ops.aten.reshape.default(
_convolution_pointwise_default_35, [8, 64, 3136]
)
_convolution_pointwise_default_35 = None
permute_97 = torch.ops.aten.permute.default(view_168, [0, 2, 1])
view_168 = None
clone_65 = torch.ops.aten.clone.default(
permute_97, memory_format=torch.contiguous_format
)
permute_97 = None
var_mean_21 = torch.ops.aten.var_mean.correction(
clone_65, [2], correction=0, keepdim=True
)
getitem_90 = var_mean_21[0]
getitem_91 = var_mean_21[1]
var_mean_21 = None
add_82 = torch.ops.aten.add.Tensor(getitem_90, 1e-05)
getitem_90 = None
rsqrt_21 = torch.ops.aten.rsqrt.default(add_82)
add_82 = None
sub_29 = torch.ops.aten.sub.Tensor(clone_65, getitem_91)
clone_65 = getitem_91 = None
mul_82 = torch.ops.aten.mul.Tensor(sub_29, rsqrt_21)
sub_29 = rsqrt_21 = None
mul_83 = torch.ops.aten.mul.Tensor(mul_82, self._frozen_param2)
mul_82 = None
add_83 = torch.ops.aten.add.Tensor(mul_83, self._frozen_param3)
mul_83 = None
_frozen_param153 = self._frozen_param153
cat_20 = torch.ops.aten.cat.default([_frozen_param153, add_83], 1)
_frozen_param153 = add_83 = None
slice_111 = torch.ops.aten.slice.Tensor(cat_20, 1, 0, 1)
slice_113 = torch.ops.aten.slice.Tensor(
cat_20, 1, 1, 9223372036854775807
)
cat_20 = None
permute_98 = torch.ops.aten.permute.default(slice_113, [0, 2, 1])
slice_113 = None
view_169 = torch.ops.aten.reshape.default(permute_98, [8, 64, 56, 56])
permute_98 = None
_convolution_pointwise_default_34 = self.conv2(view_169)
add_84 = torch.ops.aten.add.Tensor(
_convolution_pointwise_default_34, view_169
)
_convolution_pointwise_default_34 = view_169 = None
view_170 = torch.ops.aten.reshape.default(add_84, [8, 64, 3136])
add_84 = None
permute_99 = torch.ops.aten.permute.default(view_170, [0, 2, 1])
view_170 = None
cat_21 = torch.ops.aten.cat.default([slice_111, permute_99], 1)
slice_111 = permute_99 = None
var_mean_22 = torch.ops.aten.var_mean.correction(
cat_21, [2], correction=0, keepdim=True
)
getitem_92 = var_mean_22[0]
getitem_93 = var_mean_22[1]
var_mean_22 = None
add_85 = torch.ops.aten.add.Tensor(getitem_92, 1e-06)
getitem_92 = None
rsqrt_22 = torch.ops.aten.rsqrt.default(add_85)
add_85 = None
sub_30 = torch.ops.aten.sub.Tensor(cat_21, getitem_93)
getitem_93 = None
mul_84 = torch.ops.aten.mul.Tensor(sub_30, rsqrt_22)
sub_30 = rsqrt_22 = None
mul_85 = torch.ops.aten.mul.Tensor(mul_84, self._frozen_param7)
mul_84 = None
add_86 = torch.ops.aten.add.Tensor(mul_85, self._frozen_param8)
mul_85 = None
view_171 = torch.ops.aten.reshape.default(add_86, [25096, 64])
add_86 = None
_mkl_linear_32 = self.linear(view_171)
view_171 = None
view_172 = torch.ops.aten.reshape.default(
_mkl_linear_32, [8, 3137, 192]
)
_mkl_linear_32 = None
view_173 = torch.ops.aten.reshape.default(view_172, [8, 3137, 3, 8, 8])
view_172 = None
permute_101 = torch.ops.aten.permute.default(view_173, [2, 0, 3, 1, 4])
view_173 = None
unbind_8 = torch.ops.aten.unbind.int(permute_101)
permute_101 = None
getitem_94 = unbind_8[0]
getitem_95 = unbind_8[1]
getitem_96 = unbind_8[2]
unbind_8 = None
clone_66 = torch.ops.aten.clone.default(
getitem_95, memory_format=torch.contiguous_format
)
getitem_95 = None
amax_8 = torch.ops.aten.amax.default(clone_66, [2], True)
sub_31 = torch.ops.aten.sub.Tensor(clone_66, amax_8)
clone_66 = amax_8 = None
exp_8 = torch.ops.aten.exp.default(sub_31)
sub_31 = None
sum_9 = torch.ops.aten.sum.dim_IntList(exp_8, [2], True)
div_8 = torch.ops.aten.div.Tensor(exp_8, sum_9)
exp_8 = sum_9 = None
permute_102 = torch.ops.aten.permute.default(div_8, [0, 1, 3, 2])
div_8 = None
expand_37 = torch.ops.aten.expand.default(permute_102, [8, 8, 8, 3137])
permute_102 = None
view_174 = torch.ops.aten.reshape.default(expand_37, [64, 8, 3137])
expand_37 = None
expand_38 = torch.ops.aten.expand.default(getitem_96, [8, 8, 3137, 8])
clone_67 = torch.ops.aten.clone.default(
expand_38, memory_format=torch.contiguous_format
)
expand_38 = None
view_175 = torch.ops.aten.reshape.default(clone_67, [64, 3137, 8])
clone_67 = None
bmm_16 = torch.ops.aten.bmm.default(view_174, view_175)
view_174 = view_175 = None
view_176 = torch.ops.aten.reshape.default(bmm_16, [8, 8, 8, 8])
bmm_16 = None
expand_39 = torch.ops.aten.expand.default(getitem_94, [8, 8, 3137, 8])
clone_68 = torch.ops.aten.clone.default(
expand_39, memory_format=torch.contiguous_format
)
expand_39 = None
view_177 = torch.ops.aten.reshape.default(clone_68, [64, 3137, 8])
clone_68 = None
expand_40 = torch.ops.aten.expand.default(view_176, [8, 8, 8, 8])
view_176 = None
view_178 = torch.ops.aten.reshape.default(expand_40, [64, 8, 8])
expand_40 = None
bmm_17 = torch.ops.aten.bmm.default(view_177, view_178)
view_177 = view_178 = None
view_179 = torch.ops.aten.reshape.default(bmm_17, [8, 8, 3137, 8])
bmm_17 = None
slice_116 = torch.ops.aten.slice.Tensor(
getitem_94, 2, 1, 9223372036854775807
)
getitem_94 = None
slice_120 = torch.ops.aten.slice.Tensor(
getitem_96, 2, 1, 9223372036854775807
)
getitem_96 = None
permute_103 = torch.ops.aten.permute.default(slice_120, [0, 1, 3, 2])
slice_120 = None
view_180 = torch.ops.aten.reshape.default(permute_103, [8, 64, 56, 56])
permute_103 = None
split_with_sizes_8 = torch.ops.aten.split_with_sizes.default(
view_180, [16, 24, 24], 1
)
view_180 = None
getitem_97 = split_with_sizes_8[0]
getitem_98 = split_with_sizes_8[1]
getitem_99 = split_with_sizes_8[2]
split_with_sizes_8 = None
_convolution_pointwise_default_33 = self.conv3(getitem_97)
_convolution_pointwise_default_32 = self.conv4(getitem_98)
_convolution_pointwise_default_31 = self.conv5(getitem_99)
cat_22 = torch.ops.aten.cat.default(
[
_convolution_pointwise_default_33,
_convolution_pointwise_default_32,
_convolution_pointwise_default_31,
],
1,
)
_convolution_pointwise_default_33 = (
_convolution_pointwise_default_32
) = _convolution_pointwise_default_31 = None
view_181 = torch.ops.aten.reshape.default(cat_22, [8, 8, 8, 3136])
cat_22 = None
permute_104 = torch.ops.aten.permute.default(view_181, [0, 1, 3, 2])
view_181 = None
mul_86 = torch.ops.aten.mul.Tensor(slice_116, permute_104)
slice_116 = permute_104 = None
constant_pad_nd_8 = torch.ops.aten.constant_pad_nd.default(
mul_86, [0, 0, 1, 0, 0, 0], 0.0
)
mul_86 = None
mul_87 = torch.ops.aten.mul.Tensor(view_179, 0.3535533905932738)
view_179 = None
add_87 = torch.ops.aten.add.Tensor(mul_87, constant_pad_nd_8)
mul_87 = constant_pad_nd_8 = None
return add_87
view_12 = torch.randn(batch_size, in_features, image_size, image_size)
mod = M(bias=bias).eval()
with verify(dtype) as (atol, rtol):
self.common(
mod,
(view_12,),
atol=atol,
rtol=rtol,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
self.assertEqual(
counters["inductor"]["cpp_epilogue_fusion_counter"], 2 if TEST_MKL else 1
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (32,))
@parametrize("in_features", (128,))
@parametrize("out_features", (64, 65))
@parametrize("bias", (False, True))
@parametrize("input_3d", (False, True))
@dtypes(torch.float32, torch.bfloat16)
@parametrize(
"epilogue",
(
"none",
"relu",
"gelu",
),
)
@skipIfWindows(msg="Windows don't support quantize.")
def test_quantized_linear_with_pointwise(
self, batch_size, in_features, out_features, bias, input_3d, dtype, epilogue
):
B = (2, batch_size) if input_3d else (batch_size,)
input = torch.randn(*B, in_features).to(dtype=torch.float32)
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.epilogue = _get_epilogue(epilogue)
self.linear2 = torch.nn.Linear(out_features, out_features, bias)
self.epilogue2 = _get_epilogue(epilogue)
def forward(self, x):
res = self.epilogue(self.linear(x))
res = self.epilogue2(self.linear2(res))
return res
counters.clear()
ref_quantized_mod = _generate_qdq_quantized_model(
M(bias=bias).eval(),
(input,),
)
atol, rtol = 1e-3, 1e-3
if dtype == torch.bfloat16:
atol, rtol = 5e-2, 5e-2
with (
patch.object(select_algorithm, "VERIFY", dict(atol=atol, rtol=rtol)),
torch.no_grad(),
torch.autocast("cpu", enabled=(dtype == torch.bfloat16), dtype=dtype),
):
ref_res = ref_quantized_mod(input)
cfn = torch.compile(ref_quantized_mod)
res = cfn(input)
self.assertEqual(
res,
ref_res,
atol=atol,
rtol=rtol,
equal_nan=True,
exact_dtype=True,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 0)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize(
"batch_size",
(
1,
17,
32,
),
)
@parametrize(
"mid_dim",
(
1,
8,
),
)
@parametrize("in_features", (128, 144, 1024))
@parametrize("out_features", (64, 65, 1024))
def test_int8_woq_mm(self, dtype, batch_size, mid_dim, in_features, out_features):
def _convert_weight_to_int8pack(w):
scale, zp = _calculate_dynamic_per_channel_qparams(
w.to(torch.float), torch.int8
)
scale = torch.from_numpy(scale)
zp = torch.from_numpy(zp)
w_int8 = torch.ao.quantization.fx._decomposed.quantize_per_channel(
input=w,
scales=scale,
zero_points=zp,
axis=0,
quant_min=-128,
quant_max=127,
dtype=torch.int8,
)
return w_int8, scale.to(torch.bfloat16)
class M(torch.nn.Module):
def __init__(self, w):
super().__init__()
self.linear_weight = torch.nn.Parameter(w, requires_grad=False)
def forward(self, x, scale):
return (
torch.nn.functional.linear(x, self.linear_weight.to(x.dtype))
* scale
)
counters.clear()
# Currently, the corresponding torch.fx pattern only supports 3D x
# Add 2D X case once the corresponding pattern-matcher pattern is added
x = torch.rand((batch_size, mid_dim, in_features), dtype=dtype)
w = torch.rand((out_features, in_features), dtype=dtype)
w_int8pack, w_scales = _convert_weight_to_int8pack(w)
mod = M(w_int8pack).eval()
self.common(mod, (x, w_scales))
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
if batch_size * mid_dim >= 16:
vec_amx = VecAMX()
self._check_amx_counter(vec_amx)
@inductor_config.patch({"freezing": True, "cpp.enable_concat_linear": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize(
"batch_size",
(
1,
32,
),
)
@parametrize(
"mid_dim",
(
1,
8,
),
)
@parametrize("in_features", (128,))
@parametrize("out_features", (64,))
def test_int8_woq_mm_concat(
self, dtype, batch_size, mid_dim, in_features, out_features
):
def _convert_weight_to_int8pack(w):
scale, zp = _calculate_dynamic_per_channel_qparams(
w.to(torch.float), torch.int8
)
scale = torch.from_numpy(scale)
zp = torch.from_numpy(zp)
w_int8 = torch.ao.quantization.fx._decomposed.quantize_per_channel(
input=w,
scales=scale,
zero_points=zp,
axis=0,
quant_min=-128,
quant_max=127,
dtype=torch.int8,
)
return w_int8, scale.to(torch.bfloat16)
class M(torch.nn.Module):
def __init__(self, w1, w2, w3):
super().__init__()
self.w1 = torch.nn.Parameter(w1, requires_grad=False)
self.w2 = torch.nn.Parameter(w2, requires_grad=False)
self.w3 = torch.nn.Parameter(w3, requires_grad=False)
def forward(self, x, scale1, scale2, scale3):
# Ref: _linear_fp_act_int8_weight_impl in torchao/dtypes/uintx/plain_layout.py
y1 = (
torch.mm(x.reshape(-1, x.shape[-1]), self.w1.t().to(x.dtype))
* scale1
)
y2 = (
torch.mm(x.reshape(-1, x.shape[-1]), self.w2.t().to(x.dtype))
* scale2
)
y3 = (
torch.mm(x.reshape(-1, x.shape[-1]), self.w3.t().to(x.dtype))
* scale3
)
return (
y1.reshape(*x.shape[:-1], y1.shape[-1]),
y2.reshape(*x.shape[:-1], y2.shape[-1]),
y3.reshape(*x.shape[:-1], y3.shape[-1]),
)
counters.clear()
# Currently, the corresponding torch.fx pattern only supports 3D x
# Add 2D X case once the corresponding pattern-matcher pattern is added
x = torch.rand((batch_size, mid_dim, in_features), dtype=dtype)
w1 = torch.rand((out_features, in_features), dtype=dtype)
w2 = torch.rand((out_features, in_features), dtype=dtype)
w3 = torch.rand((out_features, in_features), dtype=dtype)
w1_int8pack, w1_scales = _convert_weight_to_int8pack(w1)
w2_int8pack, w2_scales = _convert_weight_to_int8pack(w2)
w3_int8pack, w3_scales = _convert_weight_to_int8pack(w3)
mod = M(w1_int8pack, w2_int8pack, w3_int8pack).eval()
self.common(mod, (x, w1_scales, w2_scales, w3_scales))
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
if batch_size * mid_dim >= 16:
vec_amx = VecAMX()
self._check_amx_counter(vec_amx)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
# We set allow_ignore_mark_dynamic to True because Dynamo may end up specializing M dimension
# despite it being marked as dynamic with mark_dynamic.
@dynamo_config.patch({"allow_ignore_mark_dynamic": True})
@parametrize("has_bias", [True, False])
@parametrize("dtype", [torch.float, torch.bfloat16])
@parametrize("per_channel_quant", [True, False])
@parametrize("reshape_a", [True, False])
@parametrize("expand_a_scale", [True, False])
@parametrize("dynamic", [True, False])
@parametrize("M", [1, 32])
def test_da8w8_sym_act_sym_wgt_with_int_mm(
self, has_bias, dtype, per_channel_quant, reshape_a, expand_a_scale, dynamic, M
):
r"""
This testcase check if we can match the int8_dynamic_activation_int8_weight int8 linear pattern from torchao,
when activation is symmetrically quantized dynamically & weights are symmetrically quantized (statically)
The pattern is:
(no bias) _int_mm -> convert_element_type -> ([maybe_expand_a_scale] -> mul) -> mul
or
(with bias) pattern_no_bias -> add
Expansion of the scale of activation is optional.
The pattern depiction doesn't mean that convert_element_type output is fed into expand_a as input,
but simply that activation scale may be applied after an expand operation on it.
"""
if dtype == torch.bfloat16 and not torch.ops.mkldnn._is_mkldnn_bf16_supported():
return
in_feature = 48
out_feature = 64
q_min, q_max = -32, 31
class Mod(torch.nn.Module):
def __init__(self, dtype: torch.dtype, has_bias: bool):
super().__init__()
self.dtype = dtype
self.has_bias = has_bias
self.b = torch.randint(
q_min, q_max, [in_feature, out_feature], dtype=torch.int8
)
self.per_channel_quant = per_channel_quant
a_scale_per_tensor = torch.rand([1], dtype=dtype) * 0.01 + 0.01
a_scale_per_channel = torch.rand([M, 1], dtype=dtype) * 0.01 + 0.01
self.a_scale = (
a_scale_per_channel if per_channel_quant else a_scale_per_tensor
)
self.b_scale = torch.rand([out_feature]) * 0.01 + 0.01
self.b_scale = self.b_scale.to(dtype)
self.bias = torch.rand([out_feature], dtype=dtype) if has_bias else None
def forward(self, a):
if reshape_a:
a_reshaped = a.reshape(-1, a.size(-1))
else:
a_reshaped = a
c = torch._int_mm(a_reshaped, self.b)
c = c.to(self.dtype)
if not expand_a_scale:
a_scale = self.a_scale
else:
a_scale = self.a_scale.expand(c.shape)
c = c * a_scale
c = c * self.b_scale
if self.has_bias:
c = c + self.bias
return c
mod = Mod(dtype, has_bias).eval()
a = torch.randint(q_min, q_max, [M, in_feature], dtype=torch.int8)
if dynamic:
torch._dynamo.mark_dynamic(a, 0)
torch._dynamo.mark_static(a, 1)
self.common(
mod,
(a,),
atol=1e-2 if dtype is torch.bfloat16 else None,
rtol=1e-2 if dtype is torch.bfloat16 else None,
)
vec_amx = VecAMX()
self._check_amx_counter(vec_amx)
if torch._C._cpu._is_amx_tile_supported():
# Only AMX ISA based micro-kernel is currently supported for da8w8
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize("batch_size", (1,))
@parametrize("in_features", (128, 256))
@parametrize("out_features", (64, 128))
@parametrize("group_size", (32, 64))
def test_int4_woq_mm_avx512(
self, dtype, batch_size, in_features, out_features, group_size
):
class M(torch.nn.Module):
def __init__(self, K, N, group_size):
super().__init__()
self.linear_weight = torch.randint(
0, 15, (N, K // 2), dtype=torch.uint8
)
self.qscale_and_zeros = torch.rand(K // group_size, N, 2, dtype=dtype)
self.group_size = group_size
def forward(self, x):
x_shape = x.shape
x = x.reshape(-1, x_shape[-1])
y = torch._weight_int4pack_mm_for_cpu(
x, self.linear_weight, self.group_size, self.qscale_and_zeros
)
return y.reshape(*x_shape[:-1], out_features)
counters.clear()
seq_len = 4
x = torch.rand((batch_size, seq_len, in_features), dtype=dtype)
mod = M(in_features, out_features, group_size).eval()
self.common(mod, (x,), reference_in_float=False)
available_isa = torch._inductor.cpu_vec_isa.pick_vec_isa()
avx512_available = "avx512" in str(available_isa)
autotune_count = 1 if avx512_available else 0
self.assertEqual(
counters["inductor"]["select_algorithm_autotune"], autotune_count
)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize("batch_size", (64,))
@parametrize("in_features", (14336,))
@parametrize("out_features", (96,))
@parametrize("group_size", (128,))
@set_num_threads(1)
def test_int4_woq_mm_amx_Nc_larger_than_one(
self, dtype, batch_size, in_features, out_features, group_size
):
"""
Note:
`torch._weight_int4pack_mm_for_cpu` computes with float32, while the AMX-based GEMM
template computes with bfloat16. So, the difference of computation results may be big.
But we need `_weight_int4pack_mm_for_cpu` for its pattern.
Therefore, we define module M1 for its pattern and parameters and define module M2 for
the reference computation. M2's forward function gets the dequantized and unpacked weight
in bfloat16 then computes GEMM with bfloat16.
Besides, we need to skip the VERIFY patch and cannot use self.common for testing.
"""
class M1(torch.nn.Module):
def __init__(self, K, N, group_size):
super().__init__()
self.linear_weight = torch.randint(
0, 255, (N, K // 2), dtype=torch.uint8
)
self.qscale_and_zeros = torch.rand(K // group_size, N, 2, dtype=dtype)
self.group_size = group_size
def forward(self, x):
x_shape = x.shape
x = x.reshape(-1, x_shape[-1])
y = torch._weight_int4pack_mm_for_cpu(
x, self.linear_weight, self.group_size, self.qscale_and_zeros
)
return y.reshape(*x_shape[:-1], out_features)
class M2(torch.nn.Module):
def __init__(self, mod: M1):
super().__init__()
self.mod = mod
def forward(self, x):
x_eye = torch.eye(x.shape[-1], device=x.device, dtype=x.dtype)
dq_w = self.mod(x_eye).T.contiguous()
return torch.nn.functional.linear(x, dq_w)
counters.clear()
seq_len = 8
x = torch.rand((batch_size, seq_len, in_features), dtype=dtype)
mod = M1(in_features, out_features, group_size).eval()
mod2 = M2(mod)
# Skip VERIFY during torch.compile and don't use self.common. See explanation above.
with patch.object(select_algorithm, "VERIFY", None):
m = torch.compile(mod)
y_ref = mod2(x)
y = m(x)
self.assertEqual(
y,
y_ref,
atol=1e-2,
rtol=1e-2,
)
self.assertEqual(counters["inductor"]["select_algorithm_autotune"], 1)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.use_small_dequant_buffer": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize("batch_size", (16,))
@parametrize("in_features", (14336,))
@parametrize("out_features", (96,))
@parametrize("group_size", (128,))
@set_num_threads(1)
def test_int4_woq_mm_with_small_buffer_config(
self, dtype, batch_size, in_features, out_features, group_size
):
class M1(torch.nn.Module):
def __init__(self, K, N, group_size):
super().__init__()
self.linear_weight = torch.randint(
0, 255, (N, K // 2), dtype=torch.uint8
)
self.qscale_and_zeros = torch.rand(K // group_size, N, 2, dtype=dtype)
self.group_size = group_size
def forward(self, x):
x_shape = x.shape
x = x.reshape(-1, x_shape[-1])
y = torch._weight_int4pack_mm_for_cpu(
x, self.linear_weight, self.group_size, self.qscale_and_zeros
)
return y.reshape(*x_shape[:-1], out_features)
counters.clear()
seq_len = 1
x = torch.rand((batch_size, seq_len, in_features), dtype=dtype)
mod = M1(in_features, out_features, group_size).eval()
with patch.object(select_algorithm, "VERIFY", None):
m = torch.compile(mod)
_, code = run_and_get_cpp_code(m, x)
kr = 32 # only kr=32 supported in woq int4 amx kernel
_target_code_check = f"constexpr int64_t Kc_blocks = {group_size // kr};"
torch._C.FileCheck().check(_target_code_check).run(code)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize("batch_size", (1, 4, 6))
@parametrize("in_features", (128, 1024))
@parametrize("out_features", (128, 1024))
@parametrize("group_size", (32, 64, 128))
def test_int4_woq_mm_amx(
self, dtype, batch_size, in_features, out_features, group_size
):
"""
Note:
`torch._weight_int4pack_mm_for_cpu` computes with float32, while the AMX-based GEMM
template computes with bfloat16. So, the difference of computation results may be big.
But we need `_weight_int4pack_mm_for_cpu` for its pattern.
Therefore, we define module M1 for its pattern and parameters and define module M2 for
the reference computation. M2's forward function gets the dequantized and unpacked weight
in bfloat16 then computes GEMM with bfloat16.
Besides, we need to skip the VERIFY patch and cannot use self.common for testing.
"""
class M1(torch.nn.Module):
def __init__(self, K, N, group_size):
super().__init__()
self.linear_weight = torch.randint(
0, 255, (N, K // 2), dtype=torch.uint8
)
self.qscale_and_zeros = torch.rand(K // group_size, N, 2, dtype=dtype)
self.group_size = group_size
def forward(self, x):
x_shape = x.shape
x = x.reshape(-1, x_shape[-1])
y = torch._weight_int4pack_mm_for_cpu(
x, self.linear_weight, self.group_size, self.qscale_and_zeros
)
return y.reshape(*x_shape[:-1], out_features)
class M2(torch.nn.Module):
def __init__(self, mod: M1):
super().__init__()
self.mod = mod
def forward(self, x):
x_eye = torch.eye(x.shape[-1], device=x.device, dtype=x.dtype)
dq_w = self.mod(x_eye).T.contiguous()
return torch.nn.functional.linear(x, dq_w)
counters.clear()
seq_len = 8
x = torch.rand((batch_size, seq_len, in_features), dtype=dtype)
mod = M1(in_features, out_features, group_size).eval()
mod2 = M2(mod)
# Skip VERIFY during torch.compile and don't use self.common. See explanation above.
with patch.object(select_algorithm, "VERIFY", None):
m = torch.compile(mod)
y_ref = mod2(x)
y = m(x)
self.assertEqual(
y,
y_ref,
atol=1e-2,
rtol=1e-2,
)
self.assertEqual(counters["inductor"]["select_algorithm_autotune"], 1)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.enable_concat_linear": True})
@patches
@torch.no_grad
@dtypes(torch.bfloat16)
@parametrize("batch_size", (4,))
@parametrize("in_features", (256,))
@parametrize("out_features", ((512, 256, 256), (512, 512)))
@parametrize("group_size", (32, 128))
def test_int4_concat_woq_mm(
self, dtype, batch_size, in_features, out_features, group_size
):
class M1(torch.nn.Module):
def __init__(self, K, out_features, group_size):
super().__init__()
self.linear_weight = [
torch.randint(0, 255, (N, K // 2), dtype=torch.uint8)
for N in out_features
]
self.qscale_and_zeros = [
torch.rand(K // group_size, N, 2, dtype=dtype) for N in out_features
]
self.group_size = group_size
self.out_features = out_features
def forward(self, x):
x_shape = x.shape
x = x.reshape(-1, x_shape[-1])
y = [
torch._weight_int4pack_mm_for_cpu(
x,
self.linear_weight[idx],
self.group_size,
self.qscale_and_zeros[idx],
)
for idx in range(len(self.out_features))
]
return [
y[idx].reshape(*x_shape[:-1], self.out_features[idx])
for idx in range(len(self.out_features))
]
class M2(torch.nn.Module):
def __init__(self, mod: M1):
super().__init__()
self.mod = mod
def forward(self, x):
x_eye = torch.eye(x.shape[-1], device=x.device, dtype=x.dtype)
dq_w_list = []
for idx in range(len(self.mod.out_features)):
x_shape = x_eye.shape
dq_w = torch._weight_int4pack_mm_for_cpu(
x_eye,
self.mod.linear_weight[idx],
self.mod.group_size,
self.mod.qscale_and_zeros[idx],
)
dq_w_list.append(
dq_w.reshape(
*x_shape[:-1], self.mod.out_features[idx]
).T.contiguous()
)
return [torch.nn.functional.linear(x, dq_w) for dq_w in dq_w_list]
counters.clear()
seq_len = 8
x = torch.rand((batch_size, seq_len, in_features), dtype=dtype)
mod = M1(in_features, out_features, group_size).eval()
mod2 = M2(mod)
# Skip VERIFY during torch.compile and don't use self.common. See explanation above.
with patch.object(select_algorithm, "VERIFY", None):
y_ref = mod2(x)
m = torch.compile(mod)
y = m(x)
self.assertEqual(
y,
y_ref,
atol=1e-2,
rtol=1e-2,
)
# Only do once tuning, since the wgt has been concat
self.assertEqual(counters["inductor"]["select_algorithm_autotune"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (32,))
@parametrize("in_features", (128,))
@parametrize("out_features", (64, 65))
@parametrize("bias", (False, True))
@parametrize("input_3d", (False, True))
@parametrize("int8_mixed_bf16", (False, True))
@dtypes(torch.float32, torch.bfloat16)
@parametrize(
"epilogue",
(
"none",
"relu",
),
)
@skipIfWindows(msg="Windows don't support quantize.")
def test_quantized_linear_with_pointwise_binary(
self,
batch_size,
in_features,
out_features,
bias,
input_3d,
int8_mixed_bf16,
dtype,
epilogue,
):
if not int8_mixed_bf16 and dtype == torch.bfloat16:
return
B = (2, batch_size) if input_3d else (batch_size,)
input = torch.randn(*B, in_features).to(dtype=torch.float32)
other = torch.randn(*B, out_features).to(dtype=dtype)
# Avoid hitting qlinear inplace sum fusion
if input_3d:
other2 = torch.randn(B[0] * B[1], out_features).to(dtype=dtype)
else:
other2 = torch.randn(1, *B, out_features).to(dtype=dtype)
class M(torch.nn.Module):
def __init__(self, bias, input_3d):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.epilogue = _get_epilogue(epilogue)
self.linear2 = torch.nn.Linear(out_features, out_features, bias)
self.epilogue2 = _get_epilogue(epilogue)
self.input_3d = input_3d
def forward(self, x, other, other2):
res = self.epilogue(self.linear(x) + other)
# Avoid hitting qlinear inplace sum fusion
if self.input_3d:
other2 = other2.view(2, other2.size(0) // 2, other2.size(1))
else:
other2 = other2.view(other2.size(1), other2.size(2))
res = self.epilogue2(self.linear2(res) + other2)
return res
counters.clear()
ref_quantized_mod = _generate_qdq_quantized_model(
M(bias=bias, input_3d=input_3d).eval(),
(input, other, other2),
)
atol, rtol = 5e-2, 5e-2
with (
patch.object(select_algorithm, "VERIFY", dict(atol=atol, rtol=rtol)),
torch.no_grad(),
torch.autocast("cpu", enabled=int8_mixed_bf16, dtype=torch.bfloat16),
):
ref_res = ref_quantized_mod(input, other, other2)
cfn = torch.compile(ref_quantized_mod)
res = cfn(input, other, other2)
self.assertEqual(
res,
ref_res,
atol=atol,
rtol=rtol,
equal_nan=True,
exact_dtype=True,
)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
self.assertEqual(
counters["inductor"]["cpp_epilogue_fusion_counter"],
0,
)
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (3, 16, 32, 49))
@parametrize("in_features", (4, 68, 128)) # k should be a multiple of 4
@parametrize("out_features", (64, 65))
@parametrize("bias", (True, False))
@skipIfWindows(msg="Windows don't support quantize.")
def test_quantized_linear_amx(self, batch_size, in_features, out_features, bias):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x)
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=torch.float32)
ref_quantized_mod = _generate_qdq_quantized_model(
M(bias=bias).eval(),
(v,),
)
atol, rtol = 1e-2, 1e-2
with patch.object(select_algorithm, "VERIFY", dict(atol=atol, rtol=rtol)):
self.common(ref_quantized_mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
vec_amx = VecAMX()
self._check_amx_counter(vec_amx)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.gemm_max_k_slices": 0})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (2,))
@parametrize("in_features", (1000,))
@parametrize("out_features", (2,))
@parametrize("bias", (True, False))
@parametrize(
"epilogue",
(
"none",
"relu",
),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_k_slicing(
self, batch_size, in_features, out_features, bias, epilogue, dtype
):
class M(torch.nn.Module):
def __init__(self, bias, epilogue, other):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.epilogue = _get_epilogue(epilogue, other)
def forward(self, x):
return self.epilogue(self.linear(x))
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
u = torch.randn(batch_size, out_features).to(dtype=dtype)
mod = M(bias=bias, epilogue=epilogue, other=u).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.gemm_cache_blocking": "2,2,2"})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@set_num_threads(1)
@parametrize("batch_size", (512,))
@parametrize("in_features", (1024,))
@parametrize("out_features", (1024,))
@parametrize("bias", (True, False))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_cache_blocking(
self, batch_size, in_features, out_features, bias, dtype
):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x)
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.gemm_thread_factors": "4,2,7"})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@set_num_threads(56)
@parametrize("batch_size", (1024,))
@parametrize("in_features", (1024,))
@parametrize("out_features", (1024,))
@parametrize("bias", (True, False))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_linear_thread_factors(
self, batch_size, in_features, out_features, bias, dtype
):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x)
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": False})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (16,))
@parametrize("in_features", (128,))
@parametrize("out_features", (64,))
@parametrize("bias", (True,))
@dtypes(
torch.float,
)
def test_aoti_linear(self, batch_size, in_features, out_features, bias, dtype):
try:
try:
from . import test_aot_inductor_utils
except ImportError:
import test_aot_inductor_utils
except Exception:
# skip this UT if import failed
return
class M(torch.nn.Module):
def __init__(self, bias=bias) -> None:
super().__init__()
self.mlp = torch.nn.Sequential(
torch.nn.Linear(in_features, out_features, bias=bias),
torch.nn.ReLU(),
)
def forward(self, x):
return self.mlp(x)
assert torch._inductor.config.freezing is False
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M(bias=bias).to(dtype=dtype).eval()
torch._dynamo.reset()
torch._inductor.metrics.reset()
torch.manual_seed(0)
with verify(dtype) as (atol, rtol), torch.no_grad():
expected = mod(v)
actual = test_aot_inductor_utils.AOTIRunnerUtil.run(
mod,
(v,),
)
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.enable_grouped_gemm_template": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (16,))
@parametrize("in_features", (52,))
@parametrize("out_features", (32,))
@parametrize("gemm_num", (2, 3))
def test_grouped_linear_invalid(
self,
batch_size,
in_features,
out_features,
gemm_num,
):
class M(torch.nn.Module):
def __init__(self, in_feature, out_feature, gemm_num):
super().__init__()
self.linears = [
torch.nn.Linear(in_feature, out_feature + gemm_idx, bias=False)
for gemm_idx in range(gemm_num)
]
def forward(self, x):
return [linear(x) for linear in self.linears]
# each linear has different num of out features, thus invalid grouped gemm
dtypes = []
if torch.ops.mkldnn._is_mkldnn_bf16_supported():
dtypes.append(torch.bfloat16)
if torch.ops.mkldnn._is_mkldnn_fp16_supported():
dtypes.append(torch.float16)
for dtype in dtypes:
torch._dynamo.reset()
torch._inductor.metrics.reset()
counters.clear()
mod = M(in_features, out_features, gemm_num).eval()
v = torch.randn(batch_size, in_features).to(dtype)
with (
verify(dtype) as (atol, rtol),
torch.autocast(device_type="cpu", dtype=dtype),
torch.no_grad(),
):
self.common(mod, (v,), atol=atol, rtol=rtol)
# gemm_num independent template instead of grouped gemm template
self.assertEqual(
counters["inductor"]["cpp_templated_kernel_counter"], gemm_num
)
self.assertEqual(counters["inductor"]["cpp_grouped_gemm_template"], 0)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.enable_grouped_gemm_template": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (16,))
@parametrize("in_features", (52,))
@parametrize("out_features", (32,))
@parametrize("input_3d", (False, True))
@parametrize("gemm_num", (2, 3))
def test_grouped_linear(
self,
batch_size,
in_features,
out_features,
input_3d,
gemm_num,
):
class M(torch.nn.Module):
def __init__(self, in_feature, out_feature, gemm_num):
super().__init__()
self.linears = [
torch.nn.Linear(in_feature, out_feature, bias=False)
for _ in range(gemm_num)
]
def forward(self, x):
return [linear(x) for linear in self.linears]
dtypes = []
if torch.ops.mkldnn._is_mkldnn_bf16_supported():
dtypes.append(torch.bfloat16)
if torch.ops.mkldnn._is_mkldnn_fp16_supported():
dtypes.append(torch.float16)
for dtype in dtypes:
if dtype == torch.float16 and input_3d:
# reduce the number of tests
continue
torch._dynamo.reset()
torch._inductor.metrics.reset()
counters.clear()
mod = M(in_features, out_features, gemm_num).eval()
B = (2, batch_size) if input_3d else (batch_size,)
v = torch.randn(*B, in_features).to(dtype)
with (
verify(dtype) as (atol, rtol),
torch.autocast(device_type="cpu", dtype=dtype),
torch.no_grad(),
):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_grouped_gemm_template"], 1)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"cpp.enable_grouped_gemm_template": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (16,))
@parametrize("in_features", (52,))
@parametrize("out_features", (32,))
@parametrize("input_3d", (True, False))
@parametrize(
"bias",
(
[True, True],
[True, False],
[False, True],
[False, False],
),
)
@parametrize(
"epilogue",
(
["none", "none"],
["relu", "none"],
["none", "relu"],
["relu", "relu"],
["silu", "mul"],
),
)
def test_grouped_linear_epilogue(
self,
batch_size,
in_features,
out_features,
input_3d,
bias,
epilogue,
):
class M(torch.nn.Module):
def __init__(self, in_feature, out_feature, bias, epilogue):
super().__init__()
self.linear0 = torch.nn.Linear(in_feature, out_feature, bias=bias[0])
self.linear1 = torch.nn.Linear(in_feature, out_feature, bias=bias[1])
self.epilogue0 = epilogue[0]
self.epilogue1 = epilogue[1]
def forward(self, x):
res0 = self.linear0(x)
res1 = self.linear1(x)
if self.epilogue0 == "silu" and self.epilogue1 == "mul":
return torch.nn.functional.silu(res0) * res1
else:
if self.epilogue0 == "relu":
res0 = torch.nn.functional.relu(res0)
if self.epilogue1 == "relu":
res1 = torch.nn.functional.relu(res1)
return res0, res1
dtypes = []
if torch.ops.mkldnn._is_mkldnn_bf16_supported():
dtypes.append(torch.bfloat16)
if torch.ops.mkldnn._is_mkldnn_fp16_supported():
dtypes.append(torch.float16)
for dtype in dtypes:
if input_3d and dtype == torch.float16:
# Reduce the number of test cases
continue
torch._dynamo.reset()
torch._inductor.metrics.reset()
counters.clear()
mod = M(in_features, out_features, bias, epilogue).eval()
B = (2, batch_size) if input_3d else (batch_size,)
v = torch.randn(*B, in_features).to(dtype)
with (
verify(dtype) as (atol, rtol),
torch.autocast(device_type="cpu", dtype=dtype),
torch.no_grad(),
):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_grouped_gemm_template"], 1)
if any(e != "none" for e in epilogue):
self.assertGreater(
counters["inductor"]["cpp_epilogue_fusion_counter"], 0
)
@inductor_config.patch({"freezing": False})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (16,))
@parametrize("in_features", (128,))
@parametrize("out_features", (64,))
@dtypes(
torch.float,
)
def test_aoti_linear_multi_view_operations(
self, batch_size, in_features, out_features, dtype
):
try:
try:
from . import test_aot_inductor_utils
except ImportError:
import test_aot_inductor_utils
except Exception:
# skip this UT if import failed
return
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.bias = torch.randn(out_features)
self.weight = torch.randn(out_features // 2, 2, in_features)
self.relu = torch.nn.ReLU()
def forward(self, x):
tmp = torch.addmm(
self.bias,
x,
self.weight.permute(2, 0, 1).view(in_features, out_features),
)
return self.relu(tmp)
assert torch._inductor.config.freezing is False
counters.clear()
v = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
torch._dynamo.reset()
torch._inductor.metrics.reset()
torch.manual_seed(0)
with verify(dtype) as (atol, rtol), torch.no_grad():
expected = mod(v)
actual = test_aot_inductor_utils.AOTIRunnerUtil.run(
mod,
(v,),
)
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@inductor_config.patch({"coordinate_descent_tuning": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
def test_cpp_coordinate_descent_tuning(self):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(512, 1024, bias=False)
def forward(self, x):
return self.linear(x)
v = torch.randn(1, 512)
mod = M().eval()
torch._dynamo.reset()
torch._inductor.metrics.reset()
counters.clear()
with verify(torch.bfloat16) as (atol, rtol), torch.autocast(device_type="cpu"):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("batch_size", (2,))
@parametrize("in_features", (128,))
@parametrize("out_features", (64,))
@parametrize("bias", (True, False))
def test_linear_to_lowp_fp(self, batch_size, in_features, out_features, bias):
class M(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
def forward(self, x):
return self.linear(x).to(torch.float16)
counters.clear()
dtype = torch.float32
mod = M(bias=bias).to(dtype=dtype).eval()
B = (batch_size,)
v = torch.randn(*B, in_features).to(dtype=dtype)
with verify(dtype) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
def test_cpp_weight_prune(self):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(32, 128, bias=False)
def forward(self, x):
return self.linear(x)
v = torch.randn(2, 32).to(torch.bfloat16)
mod = M().eval().to(torch.bfloat16)
torch._dynamo.reset()
torch._inductor.metrics.reset()
counters.clear()
with verify(torch.bfloat16) as (atol, rtol):
self.common(mod, (v,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["select_algorithm_weight_prune"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (1, 50))
@parametrize("Mdim", (192,))
@parametrize("Kdim", (196,))
@parametrize("Ndim", (84, 385))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_bmm(self, dtype, bs, Mdim, Kdim, Ndim):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
return x @ y
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (2,))
@parametrize("Mdim", (16, 32))
@parametrize("Kdim", (32,))
@parametrize("Ndim", (3, 16, 32, 48, 128, 1024, 1025))
@dtypes(torch.bfloat16, torch.half)
def test_bmm_amx(self, dtype, bs, Mdim, Kdim, Ndim):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
return x @ y
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
vec_amx = VecAMX()
# Currently brgemm config is only added for half
if dtype == torch.half:
self._check_brgemm_counter(vec_amx)
else:
self._check_amx_counter(vec_amx)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (1,))
@parametrize("Mdim", (192,))
@parametrize("Kdim", (196,))
@parametrize("Ndim", (84,))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_bmm_amp(self, dtype, bs, Mdim, Kdim, Ndim):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
return x @ y
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol), torch.amp.autocast("cpu"):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (1,))
@parametrize("Mdim", (192,))
@parametrize("Kdim", (196,))
@parametrize("Ndim", (64, 65))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_bmm_freezing(self, dtype, bs, Mdim, Kdim, Ndim):
class M(torch.nn.Module):
def __init__(self, w):
super().__init__()
self.w = torch.nn.Parameter(w, requires_grad=False)
def forward(self, x):
return x @ self.w
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M(v).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("Ndim", (64, 61))
@parametrize(
"order",
(
((0, 1, 2), (0, 2, 1)), # First BMM in hf_Reformer
((0, 1, 2), (1, 2, 0)), # First BMM in hf_DistilBert
((0, 1, 2), (1, 0, 2)), # Second BMM in hf_DistilBert, hf_T5
((1, 0, 2), (0, 1, 2)), # Third BMM in hf_Reformer
((1, 0, 2), (1, 2, 0)), # First in hf_T5
),
)
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_bmm_2d_permute(self, Ndim, order, dtype):
# TODO: Support bmm with transposed X
bs = 12
Mdim = 10
Kdim = 62
x_args = (bs, Mdim, Kdim)
w_args = (bs, Kdim, Ndim)
inverse_order = [torch.argsort(torch.tensor(o)).tolist() for o in order]
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, w):
if order[0] != (0, 1, 2):
x_order = [x_args[i] for i in inverse_order[0]]
x = x.reshape(x_order[0], x_order[1] * x_order[2]).clone()
x = x.reshape(*x_order).permute(*order[0])
if order[1] != (0, 1, 2):
w_order = [w_args[i] for i in inverse_order[1]]
w = w.reshape(w_order[0], w_order[1] * w_order[2]).clone()
w = w.reshape(*w_order).permute(*order[1])
y = x @ w
return y
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(
counters["inductor"]["cpp_templated_kernel_counter"],
1 if order[0] == (0, 1, 2) else 0,
)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (5,))
@parametrize("Mdim", (64,))
@parametrize("Kdim", (96,))
@dtypes(torch.float, torch.float16, torch.bfloat16)
def test_bmm_self_permute(self, bs, Mdim, Kdim, dtype):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x @ x.permute(0, 2, 1)
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (5,))
@parametrize("Mdim", (3, 64)) # Test small Mdim which uses reshaped weights
@dtypes(torch.float)
def test_bmm_self_square(self, bs, Mdim, dtype):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x @ x
counters.clear()
u = torch.randn(bs, Mdim, Mdim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u,), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (5,))
@parametrize("Mdim", (16,))
@parametrize("Kdim", (32,))
@parametrize("Ndim", (64,))
@dtypes(torch.float)
def test_bmm_with_broadcasted_mat1(self, bs, Mdim, Kdim, Ndim, dtype):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, w):
assert x.dim() == 2, f"Expected x to be 2D, got {x.dim()}D"
x_expanded = x.unsqueeze(0).expand(bs, -1, -1)
return x_expanded @ w
counters.clear()
u = torch.randn(Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@parametrize("bs", (5,))
@parametrize("Mdim", (384,))
@parametrize("Kdim", (96,))
@parametrize("Ndim", (64, 65))
@parametrize(
"epilogue",
(
"relu",
"add",
"sub",
"mul",
"div",
),
)
@dtypes(torch.float32, torch.bfloat16, torch.half)
def test_bmm_with_pointwise(self, bs, Mdim, Kdim, Ndim, epilogue, dtype):
class M(torch.nn.Module):
def __init__(self, epilogue, other):
super().__init__()
self.epilogue = _get_epilogue(epilogue, other)
def forward(self, x, w):
return self.epilogue(x @ w)
counters.clear()
x = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
w = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
other = torch.randn(bs, Mdim, Ndim).to(dtype=dtype)
mod = M(epilogue, other).to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (x, w), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@dtypes(torch.float32, torch.bfloat16, torch.half)
def test_bmm_with_fused_epilogues(self, dtype):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.mul = torch.randn(8, 8, 3136, 8).as_strided(
(8, 8, 3136, 8), (200704, 8, 64, 1)
)
def forward(self, x, w):
x = torch.ops.aten.reshape.default(x, [64, 3137, 8])
w = torch.ops.aten.reshape.default(w, [64, 8, 8])
bmm = torch.ops.aten.bmm.default(x, w)
bmm = torch.ops.aten.reshape.default(bmm, [8, 8, 3137, 8])
constant_pad_nd = torch.ops.aten.constant_pad_nd.default(
self.mul, [0, 0, 1, 0, 0, 0], 0.0
)
mul_2 = torch.ops.aten.mul.Tensor(bmm, 0.3535533905932738)
add = torch.ops.aten.add.Tensor(mul_2, constant_pad_nd)
return add
counters.clear()
x = torch.randn(8, 8, 3137, 8).to(dtype=dtype)
w = torch.randn(8, 8, 8, 8).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (x, w), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
self.assertEqual(counters["inductor"]["cpp_epilogue_fusion_counter"], 1)
@patches
@torch.no_grad
@parametrize("bs", (1, 50))
@parametrize("Mdim", (192,))
@parametrize("Kdim", (196,))
@parametrize("Ndim", (84, 385))
@dtypes(torch.float, torch.bfloat16, torch.half)
def test_bmm_with_y_storage_offset(self, dtype, bs, Mdim, Kdim, Ndim):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
# y_with_offset: contiguous, but has non-zero storage offset
y_with_offset = torch.empty(
(3, *y.shape), dtype=y.dtype, device=y.device
)[2].copy_(y)
return x @ y_with_offset
counters.clear()
u = torch.randn(bs, Mdim, Kdim).to(dtype=dtype)
v = torch.randn(bs, Kdim, Ndim).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
self.common(mod, (u, v), atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 1)
@patches
@torch.no_grad
@dtypes(torch.float)
def test_aoti_bmm_unique_identifiers(self, dtype):
try:
try:
from . import test_aot_inductor_utils
except ImportError:
import test_aot_inductor_utils
except Exception:
# skip this UT if import failed
return
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, w):
y = x @ w
return y @ w
counters.clear()
x = torch.randn(3, 64, 64).to(dtype=dtype)
w = torch.randn(3, 64, 64).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol), torch.no_grad():
expected = mod(x, w)
actual = test_aot_inductor_utils.AOTIRunnerUtil.run(
mod,
(x, w),
)
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
@patches
@torch.no_grad
@unittest.skipIf(not TEST_MKL, "Test requires MKL")
@set_num_threads(1) # avoid k_slicing to make the test deterministic
@parametrize(
"out_features1",
(
8,
16,
24,
32,
48,
),
)
@dtypes(torch.float)
def test_local_and_global_accumulator(self, out_features1, dtype):
batch_size = 256
in_features = 64
out_features = 129
in_features1 = 128
bias = True
try:
try:
from . import test_aot_inductor_utils
except ImportError:
import test_aot_inductor_utils
except Exception:
# skip this UT if import failed
return
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias)
self.linear1 = torch.nn.Linear(in_features1, out_features1, bias)
def forward(self, x):
y = self.linear(x)
view = torch.ops.aten.view.default(y, [-1, in_features1])
return self.linear1(view)
counters.clear()
x = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol), torch.no_grad():
expected = mod(
x,
)
actual = test_aot_inductor_utils.AOTIRunnerUtil.run(
mod,
(x,),
)
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
self.assertEqual(counters["inductor"]["cpp_templated_kernel_counter"], 2)
@patches
@inductor_config.patch(freezing=True)
@unittest.skipIf(not torch._C._has_mkldnn, "MKLDNN is not enabled")
def test_bmm_flexible_layout(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, u, v):
view_3 = torch.ops.aten.reshape.default(u, [-1, 512, 64])
clone_1 = torch.ops.aten.clone.default(
v, memory_format=torch.contiguous_format
)
view_7 = torch.ops.aten.reshape.default(clone_1, [-1, 512, 64])
permute_6 = torch.ops.aten.permute.default(view_7, [0, 2, 1])
div = torch.ops.aten.div.Tensor(permute_6, 8.0)
# view_3 is a ReinterpretView and div is a FlexibleLayout which will become FixedLayout
bmm = torch.ops.aten.bmm.default(view_3, div)
return bmm
mod = M().eval()
u = torch.randn(2, 24, 512, 64)
v = torch.randn(48, 512, 64)
with verify(u.dtype) as (atol, rtol):
self.common(mod, (u, v))
@unittest.skipIf(
not torch._C._cpu._is_amx_tile_supported(), "AMX ISA support is required"
)
@inductor_config.patch({"freezing": True})
@patches
@torch.no_grad
@parametrize("batch_size", (1024,))
@parametrize("in_features", (1024,))
@parametrize("out_features", (2048,))
@dtypes(torch.bfloat16)
def test_linear_reuse_kernels(self, batch_size, in_features, out_features, dtype):
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear_x = torch.nn.Linear(in_features, out_features)
self.linear_y = torch.nn.Linear(out_features, in_features)
self.linear_z = torch.nn.Linear(in_features, out_features)
def forward(self, x):
out = self.linear_x(x)
out = self.linear_y(out)
out = self.linear_z(out)
return out
x = torch.randn(batch_size, in_features).to(dtype=dtype)
mod = M().to(dtype=dtype).eval()
with verify(dtype) as (atol, rtol):
ref_res = mod(x)
m = torch.compile(mod)
res, code = run_and_get_cpp_code(m, x)
self.assertEqual(
res,
ref_res,
atol=atol,
rtol=rtol,
equal_nan=True,
exact_dtype=True,
)
# Check that only 2 kernels are in the generated code
assert code.count("AMXState amx_state") == 2
@dynamo_config.patch({"dynamic_shapes": True, "assume_static_by_default": False})
| TestSelectAlgorithm |
python | apache__airflow | airflow-core/src/airflow/models/backfill.py | {
"start": 3138,
"end": 3345
} | class ____(str, Enum):
"""
Internal enum for setting reprocess behavior in a backfill.
:meta private:
"""
FAILED = "failed"
COMPLETED = "completed"
NONE = "none"
| ReprocessBehavior |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/functions.py | {
"start": 4058,
"end": 10321
} | class ____(GoogleCloudBaseOperator):
"""
Create or update a function in Google Cloud Functions.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudFunctionDeployFunctionOperator`
:param location: Google Cloud region where the function should be created.
:param body: Body of the Cloud Functions definition. The body must be a
Cloud Functions dictionary as described in:
https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions
. Different API versions require different variants of the Cloud Functions
dictionary.
:param project_id: (Optional) Google Cloud project ID where the function
should be created.
:param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud.
Default 'google_cloud_default'.
:param api_version: (Optional) API version used (for example v1 - default - or
v1beta1).
:param zip_path: Path to zip file containing source code of the function. If the path
is set, the sourceUploadUrl should not be specified in the body or it should
be empty. Then the zip file will be uploaded using the upload URL generated
via generateUploadUrl from the Cloud Functions API.
:param validate_body: If set to False, body validation is not performed.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
# [START gcf_function_deploy_template_fields]
template_fields: Sequence[str] = (
"body",
"project_id",
"location",
"gcp_conn_id",
"api_version",
"impersonation_chain",
)
# [END gcf_function_deploy_template_fields]
operator_extra_links = (CloudFunctionsDetailsLink(),)
def __init__(
self,
*,
location: str,
body: dict,
project_id: str = PROVIDE_PROJECT_ID,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
zip_path: str | None = None,
validate_body: bool = True,
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
self.project_id = project_id
self.location = location
self.body = body
self.gcp_conn_id = gcp_conn_id
self.api_version = api_version
self.zip_path = zip_path
self.zip_path_preprocessor = ZipPathPreprocessor(body, zip_path)
self._field_validator: GcpBodyFieldValidator | None = None
self.impersonation_chain = impersonation_chain
if validate_body:
self._field_validator = GcpBodyFieldValidator(CLOUD_FUNCTION_VALIDATION, api_version=api_version)
self._validate_inputs()
super().__init__(**kwargs)
def _validate_inputs(self) -> None:
if not self.location:
raise AirflowException("The required parameter 'location' is missing")
if not self.body:
raise AirflowException("The required parameter 'body' is missing")
self.zip_path_preprocessor.preprocess_body()
def _validate_all_body_fields(self) -> None:
if self._field_validator:
self._field_validator.validate(self.body)
def _create_new_function(self, hook) -> None:
hook.create_new_function(project_id=self.project_id, location=self.location, body=self.body)
def _update_function(self, hook) -> None:
hook.update_function(self.body["name"], self.body, self.body.keys())
def _check_if_function_exists(self, hook) -> bool:
name = self.body.get("name")
if not name:
raise GcpFieldValidationException(f"The 'name' field should be present in body: '{self.body}'.")
try:
hook.get_function(name)
except HttpError as e:
status = e.resp.status
if status == 404:
return False
raise e
return True
def _upload_source_code(self, hook):
return hook.upload_function_zip(
project_id=self.project_id, location=self.location, zip_path=self.zip_path
)
def _set_airflow_version_label(self) -> None:
if "labels" not in self.body.keys():
self.body["labels"] = {}
self.body["labels"].update({"airflow-version": "v" + version.replace(".", "-").replace("+", "-")})
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"location": self.location,
"function_name": self.body["name"].split("/")[-1],
}
def execute(self, context: Context):
hook = CloudFunctionsHook(
gcp_conn_id=self.gcp_conn_id,
api_version=self.api_version,
impersonation_chain=self.impersonation_chain,
)
if self.zip_path_preprocessor.should_upload_function():
self.body[GCF_SOURCE_UPLOAD_URL] = self._upload_source_code(hook)
self._validate_all_body_fields()
self._set_airflow_version_label()
if not self._check_if_function_exists(hook):
self._create_new_function(hook)
else:
self._update_function(hook)
project_id = self.project_id or hook.project_id
if project_id:
CloudFunctionsDetailsLink.persist(
context=context,
location=self.location,
project_id=project_id,
function_name=self.body["name"].split("/")[-1],
)
GCF_SOURCE_ARCHIVE_URL = "sourceArchiveUrl"
GCF_SOURCE_UPLOAD_URL = "sourceUploadUrl"
SOURCE_REPOSITORY = "sourceRepository"
GCF_ZIP_PATH = "zip_path"
| CloudFunctionDeployFunctionOperator |
python | getsentry__sentry | tests/sentry/api/serializers/test_organization.py | {
"start": 5612,
"end": 6340
} | class ____(TestCase):
def test_detailed(self) -> None:
user = self.create_user()
organization = self.create_organization(owner=user)
acc = access.from_user(user, organization)
serializer = DetailedOrganizationSerializer()
result = serialize(organization, user, serializer, access=acc)
assert result["id"] == str(organization.id)
assert result["role"] == "owner"
assert result["access"] == default_owner_scopes
assert result["relayPiiConfig"] is None
assert isinstance(result["orgRoleList"], list)
assert isinstance(result["teamRoleList"], list)
assert result["requiresSso"] == acc.requires_sso
| DetailedOrganizationSerializerTest |
python | ray-project__ray | doc/source/serve/doc_code/key_concepts.py | {
"start": 2300,
"end": 2596
} | class ____:
@fastapi_app.get("/{name}")
async def say_hi(self, name: str) -> str:
return PlainTextResponse(f"Hello {name}!")
app = FastAPIIngress.bind()
serve.run(app)
assert requests.get("http://127.0.0.1:8000/Corey").text == "Hello Corey!"
# __end_fastapi_ingress__
| FastAPIIngress |
python | doocs__leetcode | solution/0200-0299/0261.Graph Valid Tree/Solution.py | {
"start": 0,
"end": 409
} | class ____:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
for a, b in edges:
pa, pb = find(a), find(b)
if pa == pb:
return False
p[pa] = pb
n -= 1
return n == 1
| Solution |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/base_env.py | {
"start": 17470,
"end": 18069
} | class ____(IntFlag):
"""
The dimension property of a dimension of an observation.
"""
UNSPECIFIED = 0
"""
No properties specified.
"""
NONE = 1
"""
No Property of the observation in that dimension. Observation can be processed with
Fully connected networks.
"""
TRANSLATIONAL_EQUIVARIANCE = 2
"""
Means it is suitable to do a convolution in this dimension.
"""
VARIABLE_SIZE = 4
"""
Means that there can be a variable number of observations in this dimension.
The observations are unordered.
"""
| DimensionProperty |
python | huggingface__transformers | src/transformers/models/wav2vec2/modeling_wav2vec2.py | {
"start": 80889,
"end": 85156
} | class ____(Wav2Vec2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Audio frame classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)"
)
self.wav2vec2 = Wav2Vec2Model(config)
num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
if config.use_weighted_layer_sum:
self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
self.num_labels = config.num_labels
self.post_init()
def freeze_feature_encoder(self):
"""
Calling this function will disable the gradient computation for the feature encoder so that its parameter will
not be updated during training.
"""
self.wav2vec2.feature_extractor._freeze_parameters()
def freeze_base_model(self):
"""
Calling this function will disable the gradient computation for the base model so that its parameters will not
be updated during training. Only the classification head will be updated.
"""
for param in self.wav2vec2.parameters():
param.requires_grad = False
@auto_docstring
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, TokenClassifierOutput]:
r"""
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
outputs = self.wav2vec2(
input_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if self.config.use_weighted_layer_sum:
hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
hidden_states = torch.stack(hidden_states, dim=1)
norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
else:
hidden_states = outputs[0]
logits = self.classifier(hidden_states)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
if not return_dict:
output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
return output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| Wav2Vec2ForAudioFrameClassification |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 29439,
"end": 34641
} | class ____(ParakeetPreTrainedModel):
config: ParakeetCTCConfig
def __init__(self, config: ParakeetCTCConfig):
super().__init__(config)
self.encoder = ParakeetEncoder(config.encoder_config)
# Conv rather than linear to be consistent with NeMO decoding layer
self.ctc_head = nn.Conv1d(config.encoder_config.hidden_size, config.vocab_size, kernel_size=1)
self.post_init()
@auto_docstring
@can_return_tuple
def forward(
self,
input_features: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutput:
r"""
Example:
```python
>>> from transformers import AutoProcessor, ParakeetForCTC
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForCTC.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> outputs = model(**inputs)
>>> print(outputs.loss)
```"""
encoder_outputs = self.encoder(
input_features=input_features,
attention_mask=attention_mask,
**kwargs,
)
hidden_states = encoder_outputs.last_hidden_state
logits = self.ctc_head(hidden_states.transpose(1, 2)).transpose(1, 2)
loss = None
if labels is not None:
# retrieve loss input_lengths from attention_mask
attention_mask = (
attention_mask if attention_mask is not None else torch.ones_like(input_features, dtype=torch.long)
)
input_lengths = self._get_subsampling_output_length(attention_mask.sum(-1))
# assuming that padded tokens are filled with -100
# when not being attended to
labels_mask = labels != self.config.pad_token_id
target_lengths = labels_mask.sum(-1)
flattened_targets = labels.masked_select(labels_mask)
# ctc_loss doesn't support fp16
log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
with torch.backends.cudnn.flags(enabled=False):
loss = nn.functional.ctc_loss(
log_probs,
flattened_targets,
input_lengths,
target_lengths,
blank=self.config.pad_token_id,
reduction=self.config.ctc_loss_reduction,
zero_infinity=self.config.ctc_zero_infinity,
)
return CausalLMOutput(
loss=loss,
logits=logits,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@torch.no_grad()
def generate(
self,
input_features: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
return_dict_in_generate: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> Union[ParakeetGenerateOutput, torch.LongTensor]:
r"""
Example:
```python
>>> from transformers import AutoProcessor, ParakeetForCTC
>>> from datasets import load_dataset, Audio
>>> model_id = "nvidia/parakeet-ctc-1.1b"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = ParakeetForCTC.from_pretrained(model_id)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))
>>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
>>> predicted_ids = model.generate(**inputs)
>>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
>>> print(transcription)
```
"""
kwargs["return_dict"] = True
outputs: CausalLMOutput = self.forward(
input_features=input_features,
attention_mask=attention_mask,
**kwargs,
)
# greedy decoding
sequences = outputs.logits.argmax(dim=-1)
# mask out padded tokens
if attention_mask is not None:
attention_mask = self._get_output_attention_mask(attention_mask, target_length=sequences.shape[1])
sequences[~attention_mask] = self.config.pad_token_id
if return_dict_in_generate:
return ParakeetGenerateOutput(
sequences=sequences,
logits=outputs.logits,
attentions=outputs.attentions,
hidden_states=outputs.hidden_states,
)
return sequences
__all__ = ["ParakeetForCTC", "ParakeetEncoder", "ParakeetPreTrainedModel"]
| ParakeetForCTC |
python | google__jax | jax/_src/config.py | {
"start": 56922,
"end": 57713
} | class ____(enum.IntEnum):
WARN = enum.auto()
ERROR = enum.auto()
ALLOW = enum.auto()
@classmethod
def _missing_(cls, value: object) -> ExplicitX64Mode | None:
if value == "warn":
return cls.WARN
if value == "error":
return cls.ERROR
if value == "allow":
return cls.ALLOW
return None
explicit_x64_dtypes = enum_class_state(
name='jax_explicit_x64_dtypes',
enum_class=ExplicitX64Mode,
default=ExplicitX64Mode.WARN,
help=(
'If set to ALLOW, explicit specification of 64-bit types will be '
'respected even if enable_x64 is false. If set to WARN, a warning will '
'be issued, and if set to ERROR, an error will be raised.'
),
include_in_jit_key=True,
include_in_trace_context=True,
)
| ExplicitX64Mode |
python | walkccc__LeetCode | solutions/965. Univalued Binary Tree/965.py | {
"start": 0,
"end": 318
} | class ____:
def isUnivalTree(self, root: TreeNode | None) -> bool:
if not root:
return True
if root.left and root.left.val != root.val:
return False
if root.right and root.right.val != root.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
| Solution |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 22819,
"end": 25997
} | class ____:
def test_email_verification_email(
self, pyramid_request, pyramid_config, token_service, monkeypatch
):
stub_user = pretend.stub(
id="id", username=None, name=None, email="foo@example.com"
)
stub_email = pretend.stub(id="id", email="email@example.com", verified=False)
pyramid_request.method = "POST"
token_service.dumps = pretend.call_recorder(lambda a: "TOKEN")
subject_renderer = pyramid_config.testing_add_renderer(
"email/verify-email/subject.txt"
)
subject_renderer.string_response = "Email Subject"
body_renderer = pyramid_config.testing_add_renderer(
"email/verify-email/body.txt"
)
body_renderer.string_response = "Email Body"
html_renderer = pyramid_config.testing_add_renderer(
"email/verify-email/body.html"
)
html_renderer.string_response = "Email HTML Body"
send_email = pretend.stub(
delay=pretend.call_recorder(lambda *args, **kwargs: None)
)
pyramid_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email)
monkeypatch.setattr(email, "send_email", send_email)
pyramid_request.db = pretend.stub(
query=lambda a: pretend.stub(
filter=lambda *a: pretend.stub(
one=lambda: pretend.stub(user_id=stub_user.id)
)
),
)
pyramid_request.user = stub_user
pyramid_request.registry.settings = {"mail.sender": "noreply@example.com"}
result = email.send_email_verification_email(
pyramid_request, (stub_user, stub_email)
)
assert result == {
"token": "TOKEN",
"email_address": stub_email.email,
"n_hours": token_service.max_age // 60 // 60,
}
subject_renderer.assert_()
body_renderer.assert_(token="TOKEN", email_address=stub_email.email)
html_renderer.assert_(token="TOKEN", email_address=stub_email.email)
assert token_service.dumps.calls == [
pretend.call({"action": "email-verify", "email.id": str(stub_email.id)})
]
assert pyramid_request.task.calls == [pretend.call(send_email)]
assert send_email.delay.calls == [
pretend.call(
stub_email.email,
{
"sender": None,
"subject": "Email Subject",
"body_text": "Email Body",
"body_html": (
"<html>\n<head></head>\n"
"<body><p>Email HTML Body</p></body>\n</html>\n"
),
},
{
"tag": "account:email:sent",
"user_id": stub_user.id,
"additional": {
"from_": "noreply@example.com",
"to": stub_email.email,
"subject": "Email Subject",
"redact_ip": False,
},
},
)
]
| TestEmailVerificationEmail |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 79452,
"end": 79637
} | class ____:
xlPageBreakAutomatic = -4105 # from enum XlPageBreak
xlPageBreakManual = -4135 # from enum XlPageBreak
xlPageBreakNone = -4142 # from enum XlPageBreak
| PageBreak |
python | jazzband__django-waffle | waffle/tests/test_decorators.py | {
"start": 107,
"end": 5286
} | class ____(TestCase):
def test_flag_must_be_active(self):
resp = self.client.get('/flag-on')
self.assertEqual(404, resp.status_code)
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flag-on')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive(self):
resp = self.client.get('/flag-off')
self.assertEqual(200, resp.status_code)
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flag-off')
self.assertEqual(404, resp.status_code)
def test_switch_must_be_active(self):
resp = self.client.get('/switch-on')
self.assertEqual(404, resp.status_code)
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switch-on')
self.assertEqual(200, resp.status_code)
def test_switch_must_be_inactive(self):
resp = self.client.get('/switch-off')
self.assertEqual(200, resp.status_code)
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switch-off')
self.assertEqual(404, resp.status_code)
def test_switch_must_be_inactive_and_redirect_to_view(self):
resp = self.client.get('/switched_view_with_valid_redirect')
self.assertEqual(302, resp.status_code)
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switched_view_with_valid_redirect')
self.assertEqual(200, resp.status_code)
def test_switch_must_be_inactive_and_redirect_to_named_view(self):
resp = self.client.get('/switched_view_with_valid_url_name')
self.assertEqual(302, resp.status_code)
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switched_view_with_valid_url_name')
self.assertEqual(200, resp.status_code)
def test_switch_must_be_inactive_and_redirect_to_view_with_args(self):
resp = self.client.get('/switched_view_with_args_with_valid_redirect/1/')
self.assertRedirects(resp, '/foo_view_with_args/1/')
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switched_view_with_args_with_valid_redirect/1/')
self.assertEqual(200, resp.status_code)
def test_switch_must_be_inactive_and_redirect_to_named_view_with_args(self):
resp = self.client.get('/switched_view_with_args_with_valid_url_name/1/')
self.assertRedirects(resp, '/foo_view_with_args/1/')
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switched_view_with_args_with_valid_url_name/1/')
self.assertEqual(200, resp.status_code)
def test_switch_must_be_inactive_and_not_redirect(self):
resp = self.client.get('/switched_view_with_invalid_redirect')
self.assertEqual(404, resp.status_code)
get_waffle_switch_model().objects.create(name='foo', active=True)
resp = self.client.get('/switched_view_with_invalid_redirect')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive_and_redirect_to_view(self):
resp = self.client.get('/flagged_view_with_valid_redirect')
self.assertEqual(302, resp.status_code)
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flagged_view_with_valid_redirect')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive_and_redirect_to_named_view(self):
resp = self.client.get('/flagged_view_with_valid_url_name')
self.assertEqual(302, resp.status_code)
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flagged_view_with_valid_url_name')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive_and_redirect_to_view_with_args(self):
resp = self.client.get('/flagged_view_with_args_with_valid_redirect/1/')
self.assertRedirects(resp, '/foo_view_with_args/1/')
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flagged_view_with_args_with_valid_redirect/1/')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive_and_redirect_to_named_view_with_args(self):
resp = self.client.get('/flagged_view_with_args_with_valid_url_name/1/')
self.assertRedirects(resp, '/foo_view_with_args/1/')
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flagged_view_with_args_with_valid_url_name/1/')
self.assertEqual(200, resp.status_code)
def test_flag_must_be_inactive_and_not_redirect(self):
resp = self.client.get('/flagged_view_with_invalid_redirect')
self.assertEqual(404, resp.status_code)
get_waffle_flag_model().objects.create(name='foo', everyone=True)
resp = self.client.get('/flagged_view_with_invalid_redirect')
self.assertEqual(200, resp.status_code)
| DecoratorTests |
python | pytorch__pytorch | torch/distributions/constraints.py | {
"start": 14616,
"end": 15205
} | class ____(Constraint):
"""
Constrain to a real interval `[lower_bound, upper_bound)`.
"""
def __init__(self, lower_bound, upper_bound):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
super().__init__()
def check(self, value):
return (self.lower_bound <= value) & (value < self.upper_bound)
def __repr__(self):
fmt_string = self.__class__.__name__[1:]
fmt_string += (
f"(lower_bound={self.lower_bound}, upper_bound={self.upper_bound})"
)
return fmt_string
| _HalfOpenInterval |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py | {
"start": 24137,
"end": 24466
} | class ____(MetadataValue[Optional[float]]):
"""Container class for float metadata entry data.
Args:
value (Optional[float]): The float value.
"""
value: PublicAttr[Optional[float]] # type: ignore
@whitelist_for_serdes(storage_name="IntMetadataEntryData")
@record(kw_only=False)
@public
| FloatMetadataValue |
python | pytorch__pytorch | test/distributed/test_c10d_pypg.py | {
"start": 2418,
"end": 3025
} | class ____(dist.ProcessGroup):
def getRank(self):
return 123
def getSize(self):
return 456
def getBackendName(self):
return "dummy-attr"
def setGroupName(self, name) -> None:
self._group_name = "py:" + name
def getGroupName(self) -> str:
return self._group_name
def setGroupDesc(self, group_desc) -> None:
self._group_desc = "py:" + group_desc
def getGroupDesc(self) -> str:
return self._group_desc
# We cannot use parametrize as some tests are defined on the base class and use _get_process_group
| DummyAttrProcessGroup |
python | PyCQA__flake8 | src/flake8/plugins/finder.py | {
"start": 1497,
"end": 2351
} | class ____(NamedTuple):
"""Classified plugins."""
checkers: Checkers
reporters: dict[str, LoadedPlugin]
disabled: list[LoadedPlugin]
def all_plugins(self) -> Generator[LoadedPlugin]:
"""Return an iterator over all :class:`LoadedPlugin`s."""
yield from self.checkers.tree
yield from self.checkers.logical_line
yield from self.checkers.physical_line
yield from self.reporters.values()
def versions_str(self) -> str:
"""Return a user-displayed list of plugin versions."""
return ", ".join(
sorted(
{
f"{loaded.plugin.package}: {loaded.plugin.version}"
for loaded in self.all_plugins()
if loaded.plugin.package not in {"flake8", "local"}
},
),
)
| Plugins |
python | google__flatbuffers | tests/MyGame/Example/NestedStruct.py | {
"start": 199,
"end": 3326
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls) -> int:
return 32
# NestedStruct
def Init(self, buf: bytes, pos: int):
self._tab = flatbuffers.table.Table(buf, pos)
# NestedStruct
def A(self, j = None):
if j is None:
return [self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + i * 4)) for i in range(self.ALength())]
elif j >= 0 and j < self.ALength():
return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + j * 4))
else:
return None
# NestedStruct
def AAsNumpy(self):
return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int32Flags, self._tab.Pos + 0, self.ALength())
# NestedStruct
def ALength(self) -> int:
return 2
# NestedStruct
def AIsNone(self) -> bool:
return False
# NestedStruct
def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8))
# NestedStruct
def C(self, j = None):
if j is None:
return [self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(9 + i * 1)) for i in range(self.CLength())]
elif j >= 0 and j < self.CLength():
return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(9 + j * 1))
else:
return None
# NestedStruct
def CAsNumpy(self):
return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int8Flags, self._tab.Pos + 9, self.CLength())
# NestedStruct
def CLength(self) -> int:
return 2
# NestedStruct
def CIsNone(self) -> bool:
return False
# NestedStruct
def D(self, j = None):
if j is None:
return [self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16 + i * 8)) for i in range(self.DLength())]
elif j >= 0 and j < self.DLength():
return self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16 + j * 8))
else:
return None
# NestedStruct
def DAsNumpy(self):
return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int64Flags, self._tab.Pos + 16, self.DLength())
# NestedStruct
def DLength(self) -> int:
return 2
# NestedStruct
def DIsNone(self) -> bool:
return False
def CreateNestedStruct(builder, a, b, c, d):
builder.Prep(8, 32)
for _idx0 in range(2 , 0, -1):
builder.PrependInt64(d[_idx0-1])
builder.Pad(5)
for _idx0 in range(2 , 0, -1):
builder.PrependInt8(c[_idx0-1])
builder.PrependInt8(b)
for _idx0 in range(2 , 0, -1):
builder.PrependInt32(a[_idx0-1])
return builder.Offset()
try:
from typing import List
except:
pass
| NestedStruct |
python | psf__black | src/black/trans.py | {
"start": 31200,
"end": 38426
} | class ____(StringTransformer):
"""StringTransformer that strips surrounding parentheses from strings.
Requirements:
The line contains a string which is surrounded by parentheses and:
- The target string is NOT the only argument to a function call.
- The target string is NOT a "pointless" string.
- The target string is NOT a dictionary value.
- If the target string contains a PERCENT, the brackets are not
preceded or followed by an operator with higher precedence than
PERCENT.
Transformations:
The parentheses mentioned in the 'Requirements' section are stripped.
Collaborations:
StringParenStripper has its own inherent usefulness, but it is also
relied on to clean up the parentheses created by StringParenWrapper (in
the event that they are no longer needed).
"""
def do_match(self, line: Line) -> TMatchResult:
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
string_indices = []
idx = -1
while True:
idx += 1
if idx >= len(LL):
break
leaf = LL[idx]
# Should be a string...
if leaf.type != token.STRING:
continue
# If this is a "pointless" string...
if (
leaf.parent
and leaf.parent.parent
and leaf.parent.parent.type == syms.simple_stmt
):
continue
# Should be preceded by a non-empty LPAR...
if (
not is_valid_index(idx - 1)
or LL[idx - 1].type != token.LPAR
or is_empty_lpar(LL[idx - 1])
):
continue
# That LPAR should NOT be preceded by a colon (which could be a
# dictionary value), function name, or a closing bracket (which
# could be a function returning a function or a list/dictionary
# containing a function)...
if is_valid_index(idx - 2) and (
LL[idx - 2].type == token.COLON
or LL[idx - 2].type == token.NAME
or LL[idx - 2].type in CLOSING_BRACKETS
):
continue
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
next_idx = string_parser.parse(LL, string_idx)
# if the leaves in the parsed string include a PERCENT, we need to
# make sure the initial LPAR is NOT preceded by an operator with
# higher or equal precedence to PERCENT
if is_valid_index(idx - 2):
# mypy can't quite follow unless we name this
before_lpar = LL[idx - 2]
if token.PERCENT in {leaf.type for leaf in LL[idx - 1 : next_idx]} and (
(
before_lpar.type
in {
token.STAR,
token.AT,
token.SLASH,
token.DOUBLESLASH,
token.PERCENT,
token.TILDE,
token.DOUBLESTAR,
token.AWAIT,
token.LSQB,
token.LPAR,
}
)
or (
# only unary PLUS/MINUS
before_lpar.parent
and before_lpar.parent.type == syms.factor
and (before_lpar.type in {token.PLUS, token.MINUS})
)
):
continue
# Should be followed by a non-empty RPAR...
if (
is_valid_index(next_idx)
and LL[next_idx].type == token.RPAR
and not is_empty_rpar(LL[next_idx])
):
# That RPAR should NOT be followed by anything with higher
# precedence than PERCENT
if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in {
token.DOUBLESTAR,
token.LSQB,
token.LPAR,
token.DOT,
}:
continue
string_indices.append(string_idx)
idx = string_idx
while idx < len(LL) - 1 and LL[idx + 1].type == token.STRING:
idx += 1
if string_indices:
return Ok(string_indices)
return TErr("This line has no strings wrapped in parens.")
def do_transform(
self, line: Line, string_indices: list[int]
) -> Iterator[TResult[Line]]:
LL = line.leaves
string_and_rpar_indices: list[int] = []
for string_idx in string_indices:
string_parser = StringParser()
rpar_idx = string_parser.parse(LL, string_idx)
should_transform = True
for leaf in (LL[string_idx - 1], LL[rpar_idx]):
if line.comments_after(leaf):
# Should not strip parentheses which have comments attached
# to them.
should_transform = False
break
if should_transform:
string_and_rpar_indices.extend((string_idx, rpar_idx))
if string_and_rpar_indices:
yield Ok(self._transform_to_new_line(line, string_and_rpar_indices))
else:
yield Err(
CannotTransform("All string groups have comments attached to them.")
)
def _transform_to_new_line(
self, line: Line, string_and_rpar_indices: list[int]
) -> Line:
LL = line.leaves
new_line = line.clone()
new_line.comments = line.comments.copy()
previous_idx = -1
# We need to sort the indices, since string_idx and its matching
# rpar_idx may not come in order, e.g. in
# `("outer" % ("inner".join(items)))`, the "inner" string's
# string_idx is smaller than "outer" string's rpar_idx.
for idx in sorted(string_and_rpar_indices):
leaf = LL[idx]
lpar_or_rpar_idx = idx - 1 if leaf.type == token.STRING else idx
append_leaves(new_line, line, LL[previous_idx + 1 : lpar_or_rpar_idx])
if leaf.type == token.STRING:
string_leaf = Leaf(token.STRING, LL[idx].value)
LL[lpar_or_rpar_idx].remove() # Remove lpar.
replace_child(LL[idx], string_leaf)
new_line.append(string_leaf)
# replace comments
old_comments = new_line.comments.pop(id(LL[idx]), [])
new_line.comments.setdefault(id(string_leaf), []).extend(old_comments)
else:
LL[lpar_or_rpar_idx].remove() # This is a rpar.
previous_idx = idx
# Append the leaves after the last idx:
append_leaves(new_line, line, LL[idx + 1 :])
return new_line
| StringParenStripper |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datapipeline.py | {
"start": 1971,
"end": 3063
} | class ____:
@pytest.fixture
def create_operator(self):
"""
Creates a mock create datapipeline operator to be used in testing.
"""
return DataflowCreatePipelineOperator(
task_id="test_create_datapipeline",
body=TEST_BODY,
project_id=TEST_PROJECT_ID,
location=TEST_LOCATION,
gcp_conn_id=TEST_GCP_CONN_ID,
)
@mock.patch("airflow.providers.google.cloud.operators.dataflow.DataflowHook")
def test_execute(self, mock_hook, create_operator):
"""
Test that the execute function creates and calls the DataPipeline hook with the correct parameters
"""
create_operator.execute(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id="test_gcp_conn_id",
impersonation_chain=None,
)
mock_hook.return_value.create_data_pipeline.assert_called_once_with(
project_id=TEST_PROJECT_ID,
body=TEST_BODY,
location=TEST_LOCATION,
)
| TestDataflowCreatePipelineOperator |
python | dask__distributed | distributed/tests/test_client.py | {
"start": 175729,
"end": 232097
} | class ____:
x: int
y: int
@gen_cluster(client=True)
async def test_tuple_keys(c, s, a, b):
x = dask.delayed(inc)(1, dask_key_name=("x", 1))
y = dask.delayed(inc)(x, dask_key_name=("y", 1))
future = c.compute(y)
assert (await future) == 3
z = dask.delayed(inc)(y, dask_key_name=("z", MyHashable(1, 2)))
with pytest.raises(TypeError, match="key"):
await c.compute(z)
@gen_cluster(client=True)
async def test_multiple_scatter(c, s, a, b):
futures = await asyncio.gather(*(c.scatter(1, direct=True) for _ in range(5)))
x = await futures[0]
x = await futures[0]
@gen_cluster(client=True)
async def test_map_large_kwargs_in_graph(c, s, a, b):
np = pytest.importorskip("numpy")
x = np.random.random(100000)
futures = c.map(lambda a, b: a + b, range(100), b=x)
while not s.tasks:
await asyncio.sleep(0.01)
assert len(s.tasks) == 101
assert sum(sizeof(ts.run_spec) > sizeof(x) for ts in s.tasks.values()) == 1
@gen_cluster(client=True)
async def test_retry(c, s, a, b):
def f():
assert dask.config.get("foo")
with dask.config.set(foo=False):
future = c.submit(f)
with pytest.raises(AssertionError):
await future
with dask.config.set(foo=True):
await future.retry()
await future
@gen_cluster(client=True)
async def test_retry_dependencies(c, s, a, b):
def f():
return dask.config.get("foo")
x = c.submit(f)
y = c.submit(inc, x)
with pytest.raises(KeyError):
await y
with dask.config.set(foo=100):
await y.retry()
result = await y
assert result == 101
await y.retry()
await x.retry()
result = await y
assert result == 101
@gen_cluster(client=True)
async def test_released_dependencies(c, s, a, b):
def f(x):
return dask.config.get("foo") + 1
x = c.submit(inc, 1, key="x")
y = c.submit(f, x, key="y")
del x
with pytest.raises(KeyError):
await y
with dask.config.set(foo=100):
await y.retry()
result = await y
assert result == 101
@gen_cluster(client=True, clean_kwargs={"threads": False})
async def test_profile_bokeh(c, s, a, b):
pytest.importorskip("bokeh.plotting")
from bokeh.model import Model
await c.gather(c.map(slowinc, range(10), delay=0.2))
state, figure = await c.profile(plot=True)
assert isinstance(figure, Model)
with tmpfile("html") as fn:
try:
await c.profile(filename=fn)
except PermissionError:
if WINDOWS:
pytest.xfail()
assert os.path.exists(fn)
@gen_cluster(client=True)
async def test_get_mix_futures_and_SubgraphCallable_dask_dataframe(c, s, a, b):
pd = pytest.importorskip("pandas")
dd = pytest.importorskip("dask.dataframe")
df = pd.DataFrame({"x": range(1, 11)})
ddf = c.persist(dd.from_pandas(df, npartitions=2))
ddf = ddf.map_partitions(lambda x: x)
ddf["x"] = ddf["x"].astype("f8")
ddf = ddf.map_partitions(lambda x: x)
ddf["x"] = ddf["x"].astype("f8")
result = await c.compute(ddf)
assert result.equals(df.astype("f8"))
def test_direct_to_workers(s, loop):
with Client(s["address"], loop=loop, direct_to_workers=True) as client:
future = client.scatter(1)
future.result()
resp = client.run_on_scheduler(
lambda dask_scheduler: dask_scheduler.get_events()
)
assert "gather" not in str(resp)
@gen_cluster(client=True)
async def test_instances(c, s, a, b):
assert list(Client._instances) == [c]
assert list(Scheduler._instances) == [s]
assert set(Worker._instances) == {a, b}
@gen_cluster(client=True)
async def test_wait_for_workers(c, s, a, b):
future = asyncio.ensure_future(c.wait_for_workers(n_workers=3))
await asyncio.sleep(0.22) # 2 chances
assert not future.done()
async with Worker(s.address):
start = time()
await future
assert time() < start + 1
with pytest.raises(TimeoutError) as info:
await c.wait_for_workers(n_workers=10, timeout="1 ms")
assert "2/10" in str(info.value).replace(" ", "")
assert "1 ms" in str(info.value)
@pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows")
@pytest.mark.skipif(MACOS, reason="dask/distributed#8075")
@pytest.mark.parametrize(
"Worker", [Worker, pytest.param(Nanny, marks=[pytest.mark.slow])]
)
@gen_test()
async def test_file_descriptors_dont_leak(Worker):
pytest.importorskip("pandas")
df = dask.datasets.timeseries(freq="10s", dtypes={"x": int, "y": float})
proc = psutil.Process()
before = proc.num_fds()
async with Scheduler(dashboard_address=":0") as s:
async with (
Worker(s.address),
Worker(s.address),
Client(s.address, asynchronous=True) as c,
):
assert proc.num_fds() > before
await c.persist(df.sum())
start = time()
while proc.num_fds() > before:
await asyncio.sleep(0.01)
assert time() < start + 10, (before, proc.num_fds())
@gen_test()
async def test_dashboard_link_cluster():
class MyCluster(LocalCluster):
@property
def dashboard_link(self):
return "http://foo.com"
async with MyCluster(
processes=False, asynchronous=True, dashboard_address=":0"
) as cluster:
async with Client(cluster, asynchronous=True) as client:
assert "http://foo.com" in client._repr_html_()
@gen_test()
async def test_shutdown():
async with Scheduler(dashboard_address=":0") as s:
async with Worker(s.address) as w:
async with Client(s.address, asynchronous=True) as c:
await c.shutdown()
assert s.status == Status.closed
assert w.status in {Status.closed, Status.closing}
assert c.status == "closed"
@gen_test()
async def test_shutdown_localcluster():
async with LocalCluster(
n_workers=1, asynchronous=True, processes=False, dashboard_address=":0"
) as lc:
async with Client(lc, asynchronous=True) as c:
await c.shutdown()
assert lc.scheduler.status == Status.closed
assert lc.status == Status.closed
assert c.status == "closed"
@gen_test()
async def test_shutdown_stops_callbacks():
async with Scheduler(dashboard_address=":0") as s:
async with Worker(s.address) as w:
async with Client(s.address, asynchronous=True) as c:
await c.shutdown()
assert not any(pc.is_running() for pc in c._periodic_callbacks.values())
@gen_test()
async def test_shutdown_is_quiet_with_cluster():
async with LocalCluster(
n_workers=1, asynchronous=True, processes=False, dashboard_address=":0"
) as cluster:
with captured_logger("distributed.client") as logger:
timeout = 0.1
async with Client(cluster, asynchronous=True, timeout=timeout) as c:
await c.shutdown()
await asyncio.sleep(timeout)
msg = logger.getvalue().strip()
assert msg == "Shutting down scheduler from Client", msg
@gen_test()
async def test_client_is_quiet_cluster_close():
async with LocalCluster(
n_workers=1, asynchronous=True, processes=False, dashboard_address=":0"
) as cluster:
with captured_logger("distributed.client") as logger:
timeout = 0.1
async with Client(cluster, asynchronous=True, timeout=timeout) as c:
await cluster.close()
await asyncio.sleep(timeout)
assert not logger.getvalue().strip()
@gen_test()
async def test_config_inherited_by_subprocess():
with dask.config.set(foo=100):
async with LocalCluster(
n_workers=1,
asynchronous=True,
processes=True,
dashboard_address=":0",
) as lc:
async with Client(lc, asynchronous=True) as c:
assert await c.submit(dask.config.get, "foo") == 100
@gen_cluster(client=True)
async def test_futures_of_sorted(c, s, a, b):
b = c.persist(dask.bag.from_sequence(range(10), npartitions=5))
futures = futures_of(b)
assert [fut.key for fut in futures] == [k for k in b.__dask_keys__()]
@pytest.mark.skipif(sys.version_info.minor == 11, reason="Profiler disabled")
@gen_cluster(
client=True,
config={
"distributed.worker.profile.enabled": True,
"distributed.worker.profile.cycle": "10ms",
},
)
async def test_profile_server(c, s, a, b):
for i in range(5):
try:
x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False)
await wait(x)
await asyncio.gather(
c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5)
)
p = await c.profile(server=True) # All worker servers
assert "slowinc" in str(p)
p = await c.profile(scheduler=True) # Scheduler
assert "slowdec" in str(p)
except AssertionError:
if i == 4:
raise
else:
pass
else:
break
@gen_cluster(
client=True,
config={
"distributed.worker.profile.enabled": False,
"distributed.worker.profile.cycle": "10ms",
},
)
async def test_profile_server_disabled(c, s, a, b):
x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False)
await wait(x)
await asyncio.gather(
c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5)
)
p = await c.profile(server=True) # All worker servers
assert "slowinc" not in str(p)
p = await c.profile(scheduler=True) # Scheduler
assert "slowdec" not in str(p)
@gen_cluster(client=True)
async def test_await_future(c, s, a, b):
future = c.submit(inc, 1)
async def f():
result = await future
assert result == 2
await f()
future = c.submit(div, 1, 0)
async def f():
with pytest.raises(ZeroDivisionError):
await future
await f()
@gen_cluster(client=True)
async def test_as_completed_async_for(c, s, a, b):
futures = c.map(inc, range(10))
ac = as_completed(futures)
results = []
async def f():
async for future in ac:
result = await future
results.append(result)
await f()
assert set(results) == set(range(1, 11))
@gen_cluster(client=True)
async def test_as_completed_async_for_results(c, s, a, b):
futures = c.map(inc, range(10))
ac = as_completed(futures, with_results=True)
results = []
async def f():
async for _, result in ac:
results.append(result)
await f()
assert set(results) == set(range(1, 11))
@gen_cluster(client=True)
async def test_as_completed_async_for_cancel(c, s, a, b):
x = c.submit(inc, 1)
ev = Event()
y = c.submit(lambda ev: ev.wait(), ev)
ac = as_completed([x, y])
await x
await y.cancel()
futs = [future async for future in ac]
assert futs == [x, y]
await ev.set() # Allow for clean teardown
@gen_test()
async def test_async_with():
async with Client(processes=False, dashboard_address=":0", asynchronous=True) as c:
assert await c.submit(lambda x: x + 1, 10) == 11
assert c.status == "closed"
assert c.cluster.status == Status.closed
def test_client_sync_with_async_def(loop):
async def ff():
await asyncio.sleep(0.01)
return 1
with cluster() as (s, [a, b]):
with Client(s["address"], loop=loop) as c:
assert sync(loop, ff) == 1
assert c.sync(ff) == 1
@pytest.mark.skip(reason="known intermittent failure")
@gen_cluster(client=True)
async def test_dont_hold_on_to_large_messages(c, s, a, b):
np = pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = np.random.random(1000000)
xr = weakref.ref(x)
d = da.from_array(x, chunks=(100000,))
d = d.persist()
del x
start = time()
while xr() is not None:
if time() > start + 5:
# Help diagnosing
from types import FrameType
x = xr()
if x is not None:
del x
rc = sys.getrefcount(xr())
refs = gc.get_referrers(xr())
print("refs to x:", rc, refs, gc.isenabled())
frames = [r for r in refs if isinstance(r, FrameType)]
for i, f in enumerate(frames):
print(
"frames #%d:" % i,
f.f_code.co_name,
f.f_code.co_filename,
sorted(f.f_locals),
)
pytest.fail("array should have been destroyed")
await asyncio.sleep(0.200)
@gen_cluster(client=True)
async def test_run_on_scheduler_async_def(c, s, a, b):
async def f(dask_scheduler):
await asyncio.sleep(0.01)
dask_scheduler.foo = "bar"
await c.run_on_scheduler(f)
assert s.foo == "bar"
async def f(dask_worker):
await asyncio.sleep(0.01)
dask_worker.foo = "bar"
await c.run(f)
assert a.foo == "bar"
assert b.foo == "bar"
@gen_cluster(client=True)
async def test_run_on_scheduler_async_def_wait(c, s, a, b):
async def f(dask_scheduler):
await asyncio.sleep(0.01)
dask_scheduler.foo = "bar"
await c.run_on_scheduler(f, wait=False)
while not hasattr(s, "foo"):
await asyncio.sleep(0.01)
assert s.foo == "bar"
async def f(dask_worker):
await asyncio.sleep(0.01)
dask_worker.foo = "bar"
await c.run(f, wait=False)
while not hasattr(a, "foo") or not hasattr(b, "foo"):
await asyncio.sleep(0.01)
assert a.foo == "bar"
assert b.foo == "bar"
@pytest.mark.slow
@pytest.mark.skipif(WINDOWS, reason="frequently kills off the whole test suite")
@pytest.mark.parametrize("local", [True, False])
@gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2)
async def test_performance_report(c, s, a, b, local):
pytest.importorskip("bokeh")
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
async def f(stacklevel, mode=None):
"""
We wrap this in a function so that the assertions aren't in the
performanace report itself
Also, we want this comment to appear
"""
x = da.random.random((1000, 1000), chunks=(100, 100))
with tmpfile(extension="html") as fn:
urlpath = fn
if not local:
pytest.importorskip("fsspec")
# Make it look like an fsspec path
urlpath = f"file://{fn}"
async with performance_report(
filename=urlpath,
stacklevel=stacklevel,
mode=mode,
):
await c.compute((x + x.T).sum())
with open(fn) as f:
data = f.read()
return data
# Ensure default kwarg maintains backward compatibility
data = await f(stacklevel=1)
assert "Also, we want this comment to appear" in data
assert "bokeh" in data
assert "random" in data
assert "Dask Performance Report" in data
assert "x = da.random" in data
assert "Threads: 4" in data
assert "No logs to report" in data
assert dask.__version__ in data
# stacklevel=2 captures code two frames back -- which in this case
# is the testing function
data = await f(stacklevel=2)
assert "async def test_performance_report(c, s, a, b):" in data
assert "Dask Performance Report" in data
# stacklevel=0 or lower is overridden to stacklevel=1 so we don't see
# distributed internals
data = await f(stacklevel=0)
assert "Also, we want this comment to appear" in data
assert "Dask Performance Report" in data
data = await f(stacklevel=1, mode="inline")
assert "cdn.bokeh.org" not in data
data = await f(stacklevel=1, mode="cdn")
assert "cdn.bokeh.org" in data
@gen_cluster(client=True)
async def test_as_completed_condition_loop(c, s, a, b):
seq = c.map(inc, range(5))
ac = as_completed(seq)
# consume the ac so that the ac.condition is bound to the loop on py3.10+
async for _ in ac:
pass
assert ac.condition._loop == c.loop.asyncio_loop
@pytest.mark.slow
@gen_cluster(client=True, nthreads=[], config={"distributed.comm.compression": None})
@pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost")
async def test_mixed_compression(c, s):
pytest.importorskip("lz4")
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
async with (
Nanny(
s.address,
host="127.0.0.2",
nthreads=1,
config={"distributed.comm.compression": "lz4"},
),
Nanny(
s.address,
host="127.0.0.3",
nthreads=1,
config={"distributed.comm.compression": "zlib"},
),
):
await c.wait_for_workers(2)
await c.get_versions()
x = da.ones((10000, 10000))
# get_data between Worker with lz4 and Worker with zlib
y = x + x.T
# get_data from Worker with lz4 and Worker with zlib to Client with None
out = await c.gather(y)
assert out.shape == (10000, 10000)
def test_futures_in_subgraphs(loop_in_thread):
"""Regression test of <https://github.com/dask/distributed/issues/4145>"""
pd = pytest.importorskip("pandas")
dd = pytest.importorskip("dask.dataframe")
with cluster() as (s, [a, b]), Client(s["address"], loop=loop_in_thread) as c:
ddf = dd.from_pandas(
pd.DataFrame(
dict(
uid=range(50),
enter_time=pd.date_range(
start="2020-01-01", end="2020-09-01", periods=50, tz="UTC"
),
)
),
npartitions=5,
)
ddf = ddf[ddf.uid.isin(range(29))].persist()
ddf["local_time"] = ddf.enter_time.dt.tz_convert("US/Central")
ddf["day"] = ddf.enter_time.dt.day_name()
ddf = ddf.categorize(columns=["day"], index=False)
ddf.compute()
@gen_cluster(client=True)
async def test_get_task_metadata(c, s, a, b):
# Populate task metadata
await c.register_plugin(TaskStateMetadataPlugin())
async with get_task_metadata() as tasks:
f = c.submit(slowinc, 1)
await f
metadata = tasks.metadata
assert f.key in metadata
assert metadata[f.key] == s.tasks.get(f.key).metadata
state = tasks.state
assert f.key in state
assert state[f.key] == "memory"
assert not any(isinstance(p, CollectTaskMetaDataPlugin) for p in s.plugins)
@gen_cluster(client=True)
async def test_get_task_metadata_multiple(c, s, a, b):
# Populate task metadata
await c.register_plugin(TaskStateMetadataPlugin())
# Ensure that get_task_metadata only collects metadata for
# tasks which are submitted and completed within its context
async with get_task_metadata() as tasks1:
f1 = c.submit(slowinc, 1)
await f1
async with get_task_metadata() as tasks2:
f2 = c.submit(slowinc, 2)
await f2
metadata1 = tasks1.metadata
metadata2 = tasks2.metadata
assert len(metadata1) == 2
assert sorted(metadata1.keys()) == sorted([f1.key, f2.key])
assert metadata1[f1.key] == s.tasks.get(f1.key).metadata
assert metadata1[f2.key] == s.tasks.get(f2.key).metadata
assert len(metadata2) == 1
assert list(metadata2.keys()) == [f2.key]
assert metadata2[f2.key] == s.tasks.get(f2.key).metadata
@gen_cluster(client=True)
async def test_register_worker_plugin_instance_required(c, s, a, b):
class MyPlugin(WorkerPlugin): ...
with pytest.raises(TypeError, match="instance"):
await c.register_plugin(MyPlugin)
@gen_cluster(client=True)
async def test_register_worker_plugin_exception(c, s, a, b):
class MyPlugin(WorkerPlugin):
def setup(self, worker=None):
raise ValueError("Setup failed")
with pytest.raises(ValueError, match="Setup failed"):
await c.register_plugin(MyPlugin())
@gen_cluster(client=True)
async def test_annotations_task_state(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(qux="bar", priority=100):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert ts.annotations["qux"] == "bar"
assert ts.annotations["priority"] == 100
@pytest.mark.parametrize("fn", ["compute", "persist"])
@gen_cluster(client=True)
async def test_annotations_compute_time(c, s, a, b, fn):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = da.ones(10, chunks=(5,))
with dask.annotate(foo="bar"):
# Turn off optimization to avoid rewriting layers and picking up annotations
# that way. Instead, we want `compute`/`persist` to be able to pick them up.
fut = getattr(c, fn)(x, optimize_graph=False)
await wait(fut)
assert s.tasks
for ts in s.tasks.values():
assert ts.annotations["foo"] == "bar"
@pytest.mark.xfail(reason="https://github.com/dask/dask/issues/7036")
@gen_cluster(client=True)
async def test_annotations_survive_optimization(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(foo="bar"):
x = da.ones(10, chunks=(5,))
ann = x.__dask_graph__().layers[x.name].annotations
assert ann is not None
assert ann.get("foo", None) == "bar"
(xx,) = dask.optimize(x)
ann = xx.__dask_graph__().layers[x.name].annotations
assert ann is not None
assert ann.get("foo", None) == "bar"
@gen_cluster(client=True)
async def test_annotations_priorities(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(priority=15):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert ts.priority[0] == -15
assert ts.annotations["priority"] == 15
@gen_cluster(client=True)
async def test_annotations_workers(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(workers=[a.address]):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert ts.annotations["workers"] == [a.address]
assert ts.worker_restrictions == {a.address}
assert a.data
assert not b.data
@gen_cluster(client=True)
async def test_annotations_retries(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(retries=2):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert ts.retries == 2
assert ts.annotations["retries"] == 2
@gen_cluster(client=True)
async def test_annotations_blockwise_unpack(c, s, a, b):
np = pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
from dask.array.utils import assert_eq
# A flaky doubling function -- need extra args because it is called before
# application to establish dtype/meta.
scale = varying([ZeroDivisionError("one"), ZeroDivisionError("two"), 2, 2])
def flaky_double(x):
return scale() * x
# A reliable double function.
def reliable_double(x):
return 2 * x
x = da.ones(10, chunks=(5,))
# The later annotations should not override the earlier annotations
with dask.annotate(retries=2):
y = x.map_blocks(flaky_double, meta=np.array((), dtype=float))
with dask.annotate(retries=0):
z = y.map_blocks(reliable_double, meta=np.array((), dtype=float))
with dask.config.set(optimization__fuse__active=False):
z = await c.compute(z)
assert_eq(z, np.ones(10) * 4.0)
@gen_cluster(
client=True,
nthreads=[
("127.0.0.1", 1),
("127.0.0.1", 1, {"resources": {"GPU": 1}}),
],
)
async def test_annotations_resources(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.annotate(resources={"GPU": 1}):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert ts.resource_restrictions == {"GPU": 1}
assert ts.annotations["resources"] == {"GPU": 1}
@gen_cluster(
client=True,
nthreads=[
("127.0.0.1", 1),
("127.0.0.1", 1, {"resources": {"GPU": 1}}),
],
)
async def test_annotations_resources_culled(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = da.ones((2, 2, 2), chunks=1)
with dask.annotate(resources={"GPU": 1}):
y = x.map_blocks(lambda x0: x0, meta=x._meta)
z = y[0, 0, 0]
(z,) = c.compute([z], optimize_graph=False)
await z
# it worked!
@gen_cluster(client=True)
async def test_annotations_loose_restrictions(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
# Eventually fails if allow_other_workers=False
with dask.annotate(workers=["fake"], allow_other_workers=True):
x = da.ones(10, chunks=(5,))
with dask.config.set(optimization__fuse__active=False):
x = await c.persist(x)
for ts in s.tasks.values():
assert not ts.worker_restrictions
assert ts.host_restrictions == {"fake"}
assert ts.annotations["workers"] == ["fake"]
assert ts.annotations["allow_other_workers"] is True
@gen_cluster(
client=True,
nthreads=[
("127.0.0.1", 1, {"resources": {"foo": 4}}),
("127.0.0.1", 1),
],
)
async def test_annotations_submit_map(c, s, a, b):
with dask.annotate(resources={"foo": 1}):
f = c.submit(inc, 0)
with dask.annotate(resources={"foo": 1}):
fs = c.map(inc, range(10, 13))
await wait([f, *fs])
for ts in s.tasks.values():
assert ts.resource_restrictions == {"foo": 1}
assert ts.annotations["resources"] == {"foo": 1}
assert not b.state.tasks
@gen_cluster(client=True)
async def test_annotations_global_vs_local(c, s, a, b):
"""Test that local annotations take precedence over global annotations"""
with dask.annotate(foo=1):
x = delayed(inc)(1, dask_key_name="x")
y = delayed(inc)(2, dask_key_name="y")
with dask.annotate(foo=2):
xf, yf = c.compute([x, y])
await c.gather(xf, yf)
assert s.tasks["x"].annotations == {"foo": 1}
assert s.tasks["y"].annotations == {"foo": 2}
@gen_cluster(client=True)
async def test_workers_collection_restriction(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
future = c.compute(da.arange(10), workers=a.address)
await future
assert a.data and not b.data
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)])
async def test_get_client_functions_spawn_clusters(c, s, a):
# see gh4565
scheduler_addr = c.scheduler.address
def f(x):
with LocalCluster(
n_workers=1,
processes=False,
dashboard_address=":0",
worker_dashboard_address=":0",
loop=None,
) as cluster2:
with Client(cluster2) as c1:
c2 = get_client()
c1_scheduler = c1.scheduler.address
c2_scheduler = c2.scheduler.address
assert c1_scheduler != c2_scheduler
assert c2_scheduler == scheduler_addr
await c.gather(c.map(f, range(2)))
await a.close()
c_default = default_client()
assert c is c_default
def test_computation_code_walk_frames():
test_function_code = inspect.getsource(test_computation_code_walk_frames)
code = Client._get_computation_code()
lineno_relative = relative_frame_linenumber(inspect.currentframe()) - 1
lineno_frame = inspect.getframeinfo(inspect.currentframe()).lineno - 2
# Sanity check helper function works, called 7 lines down in this function
assert relative_frame_linenumber(inspect.currentframe()) == 7
assert len(code) == 1
code = code[0]
assert code.code == test_function_code
assert code.lineno_frame == lineno_frame
assert code.lineno_relative == lineno_relative
assert code.filename == __file__
def nested_call():
code = Client._get_computation_code(nframes=2)
nonlocal lineno_relative, lineno_frame
lineno_relative = 1 # called on first line in this function
lineno_frame = inspect.getframeinfo(inspect.currentframe()).lineno - 3
return code
nested = nested_call()
nested_call_lineno_relative = relative_frame_linenumber(inspect.currentframe()) - 1
nested_call_lineno_frame = inspect.getframeinfo(inspect.currentframe()).lineno - 2
assert len(nested) == 2
assert nested[-1].code == inspect.getsource(nested_call)
assert nested[-1].lineno_frame == lineno_frame
assert nested[-1].lineno_relative == lineno_relative
assert nested[-1].filename == __file__
assert nested[-2].code == test_function_code
assert nested[-2].lineno_frame == nested_call_lineno_frame
assert nested[-2].lineno_relative == nested_call_lineno_relative
assert nested[-2].filename == __file__
with pytest.raises(TypeError, match="Ignored modules must be a list"):
with dask.config.set(
{"distributed.diagnostics.computations.ignore-modules": "test_client"}
):
code = Client._get_computation_code()
with dask.config.set(
{
"distributed.diagnostics.computations.ignore-modules": ["test_client"],
"distributed.diagnostics.computations.ignore-files": [],
}
):
import sys
upper_frame_code = inspect.getsource(sys._getframe(1))
lineno_relative = relative_frame_linenumber(sys._getframe(1))
lineno_frame = inspect.getframeinfo(sys._getframe(1)).lineno
code = Client._get_computation_code()
assert len(code) == 1
code = code[0]
assert code.code == upper_frame_code
assert code.lineno_relative == lineno_relative
assert code.lineno_frame == lineno_frame
assert nested_call()[-1].code == upper_frame_code
def run_in_ipython(code):
from IPython.testing.globalipapp import start_ipython
shell = start_ipython()
return shell.run_cell(code)
@pytest.mark.slow
@pytest.mark.parametrize("nframes", (2, 3))
@gen_cluster()
async def test_computation_ignore_ipython_frames(s, a, b, nframes):
pytest.importorskip("IPython")
source_code = f"""
import time
import dask
from distributed import Client
dask.config.set({{"distributed.diagnostics.computations.nframes": {nframes}}})
with Client("{s.address}") as client:
def foo(x): print(x); return x;
def bar(x): return client.map(foo, range(x))
N = client.gather(bar(3))
"""
# When not running IPython in a new process, it does not shutdown
# properly and leaks a thread. There should be a way to fix this.
# Seems to be another (deeper) issue that this shouldn't need
# a subprocess/thread/@gen_cluster/test at all, and ought to be able to run
# directly in InteractiveShell (and does) but requires `--reruns=1`
# due to some underlying lag in the asyncio if ran by itself, but will
# otherwise run fine in the suite of tests.
ctx = multiprocessing.get_context("spawn")
with concurrent.futures.ProcessPoolExecutor(1, mp_context=ctx) as executor:
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(executor, run_in_ipython, source_code)
result.raise_error()
computations = s.computations
assert len(computations) == 1
assert len(computations[0].code) == 1
code = computations[0].code[0]
assert len(code) == 2 # 2 frames when ignoring IPython frames
def normalize(s):
return re.sub(r"\s+", " ", s).strip()
assert normalize(code[0].code) == normalize(source_code)
assert normalize(code[1].code) == "def bar(x): return client.map(foo, range(x))"
@gen_cluster(client=True, nthreads=[("", 1)])
async def test_computation_store_annotations(c, s, a):
# We do not want to store layer annotations
with dask.annotate(layer="foo"):
f = delayed(inc)(1)
with dask.annotate(job="very-important"):
assert await c.compute(f) == 2
assert len(s.computations) == 1
assert s.computations[0].annotations == {"job": "very-important"}
def test_computation_object_code_dask_compute(client):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
with dask.config.set({"distributed.diagnostics.computations.nframes": 2}):
x = da.ones((10, 10), chunks=(3, 3))
x.sum().compute()
test_function_code = inspect.getsource(test_computation_object_code_dask_compute)
def fetch_comp_code(dask_scheduler):
computations = list(dask_scheduler.computations)
assert len(computations) == 1
comp = computations[0]
assert len(comp.code) == 1
return comp.code[0]
code = client.run_on_scheduler(fetch_comp_code)
assert len(code) == 1
assert code[0].code == test_function_code
def test_computation_object_code_dask_compute_no_frames_default(client):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = da.ones((10, 10), chunks=(3, 3))
x.sum().compute()
def fetch_comp_code(dask_scheduler):
computations = list(dask_scheduler.computations)
assert len(computations) == 1
comp = computations[0]
assert not comp.code
client.run_on_scheduler(fetch_comp_code)
def test_computation_object_code_not_available(client):
np = pytest.importorskip("numpy")
if parse_version(np.__version__) >= parse_version("1.25"):
pytest.skip("numpy >=1.25 can capture ufunc code")
pd = pytest.importorskip("pandas")
dd = pytest.importorskip("dask.dataframe")
with dask.config.set({"distributed.diagnostics.computations.nframes": 2}):
df = pd.DataFrame({"a": range(10)})
ddf = dd.from_pandas(df, npartitions=3)
result = np.where(ddf.a > 4)
def fetch_comp_code(dask_scheduler):
computations = list(dask_scheduler.computations)
assert len(computations) == 1
comp = computations[0]
assert not comp.code
client.run_on_scheduler(fetch_comp_code)
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_dask_persist(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = da.ones((10, 10), chunks=(3, 3))
future = c.persist(x.sum())
await future
test_function_code = inspect.getsource(
test_computation_object_code_dask_persist.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_client_submit_simple(c, s, a, b):
def func(x):
return x
fut = c.submit(func, 1)
await fut
test_function_code = inspect.getsource(
test_computation_object_code_client_submit_simple.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_client_submit_list_comp(c, s, a, b):
def func(x):
return x
futs = [c.submit(func, x) for x in range(10)]
await c.gather(futs)
test_function_code = inspect.getsource(
test_computation_object_code_client_submit_list_comp.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
# Code is deduplicated
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_client_submit_dict_comp(c, s, a, b):
def func(x):
return x
futs = {x: c.submit(func, x) for x in range(10)}
await c.gather(futs)
test_function_code = inspect.getsource(
test_computation_object_code_client_submit_dict_comp.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
# Code is deduplicated
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_client_map(c, s, a, b):
def func(x):
return x
futs = c.map(func, list(range(5)))
await c.gather(futs)
test_function_code = inspect.getsource(
test_computation_object_code_client_map.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, config={"distributed.diagnostics.computations.nframes": 2})
async def test_computation_object_code_client_compute(c, s, a, b):
pytest.importorskip("numpy")
da = pytest.importorskip("dask.array")
x = da.ones((10, 10), chunks=(3, 3))
future = c.compute(x.sum(), retries=2)
y = await future
test_function_code = inspect.getsource(
test_computation_object_code_client_compute.__wrapped__
)
computations = list(s.computations)
assert len(computations) == 1
comp = computations[0]
assert len(comp.code) == 1
assert len(comp.code[0]) == 2
assert comp.code[0][-1].code == test_function_code
@gen_cluster(client=True, Worker=Nanny)
async def test_upload_directory(c, s, a, b, tmp_path):
from dask.distributed import UploadDirectory
# Be sure to exclude code coverage reports
files_start = {f for f in os.listdir() if not f.startswith(".coverage")}
with open(tmp_path / "foo.py", "w") as f:
f.write("x = 123")
with open(tmp_path / "bar.py", "w") as f:
f.write("from foo import x")
plugin = UploadDirectory(tmp_path, restart_workers=True, update_path=True)
await c.register_plugin(plugin)
[name] = a.plugins
assert os.path.split(tmp_path)[-1] in name
def f():
import bar
return bar.x
results = await c.run(f)
assert results[a.worker_address] == 123
assert results[b.worker_address] == 123
async with Nanny(s.address, local_directory=tmp_path / "foo", name="foo") as n:
results = await c.run(f)
assert results[n.worker_address] == 123
files_end = {f for f in os.listdir() if not f.startswith(".coverage")}
assert files_start == files_end # no change
def test_upload_directory_invalid_mode():
with pytest.raises(ValueError, match="mode"):
UploadDirectory(".", mode="invalid")
@pytest.mark.skipif(WINDOWS, reason="distributed#7434")
@pytest.mark.parametrize("mode", ["all", "scheduler"])
@gen_test()
async def test_upload_directory_to_scheduler(mode, tmp_path):
from dask.distributed import UploadDirectory
# Be sure to exclude code coverage reports
files_start = {f for f in os.listdir() if not f.startswith(".coverage")}
with open(tmp_path / "foo.py", "w") as f:
f.write("x = 123")
with open(tmp_path / "bar.py", "w") as f:
f.write("from foo import x")
def f():
import bar
return bar.x
async with SubprocessCluster(
asynchronous=True,
dashboard_address=":0",
scheduler_kwargs={"idle_timeout": "5s"},
worker_kwargs={"death_timeout": "5s"},
) as cluster:
async with Client(cluster, asynchronous=True) as client:
with pytest.raises(ModuleNotFoundError, match="'bar'"):
res = await client.run_on_scheduler(f)
plugin = UploadDirectory(
tmp_path, mode=mode, restart_workers=True, update_path=True
)
await client.register_plugin(plugin)
assert await client.run_on_scheduler(f) == 123
@gen_cluster(client=True, nthreads=[("", 1)])
async def test_duck_typed_register_plugin_raises(c, s, a):
class DuckPlugin:
def setup(self, worker):
pass
def teardown(self, worker):
pass
n_existing_plugins = len(a.plugins)
with pytest.raises(TypeError, match="duck-typed.*inherit from.*Plugin"):
await c.register_plugin(DuckPlugin())
assert len(a.plugins) == n_existing_plugins
@gen_cluster(client=True)
async def test_exception_text(c, s, a, b):
def bad(x):
raise Exception(x)
future = c.submit(bad, 123)
await wait(future)
ts = s.tasks[future.key]
assert isinstance(ts.exception_text, str)
assert "123" in ts.exception_text
assert "Exception(x)" in ts.traceback_text
assert "bad" in ts.traceback_text
@gen_cluster(client=True)
async def test_async_task(c, s, a, b):
async def f(x):
return x + 1
future = c.submit(f, 10)
result = await future
assert result == 11
@gen_cluster(client=True)
async def test_async_task_with_partial(c, s, a, b):
async def f(x, y):
return x + y + 1
future = c.submit(functools.partial(f, 1), 10)
result = await future
assert result == 12
@gen_cluster(client=True)
async def test_warn_manual(c, s, a, b):
def foo():
get_worker().log_event(["foo", "warn"], "Hello!")
with pytest.warns(UserWarning, match="Hello!"):
await c.submit(foo)
def no_message():
# missing "message" key should log TypeError
get_worker().log_event("warn", {})
with captured_logger("distributed.client") as log:
await c.submit(no_message)
assert "TypeError" in log.getvalue()
def no_category():
# missing "category" defaults to `UserWarning`
get_worker().log_event("warn", {"message": pickle.dumps("asdf")})
with pytest.warns(UserWarning, match="asdf"):
await c.submit(no_category)
@gen_cluster(client=True)
async def test_warn_remote(c, s, a, b):
from dask.distributed import warn
def warn_simple():
warn("Hello!")
with pytest.warns(UserWarning, match="Hello!"):
await c.submit(warn_simple)
def warn_deprecation_1():
# one way to do it...
warn("You have been deprecated by AI", DeprecationWarning)
with pytest.warns(DeprecationWarning, match="You have been deprecated by AI"):
await c.submit(warn_deprecation_1)
def warn_deprecation_2():
# another way to do it...
warn(DeprecationWarning("Your profession has been deprecated"))
with pytest.warns(DeprecationWarning, match="Your profession has been deprecated"):
await c.submit(warn_deprecation_2)
# user-defined warning subclass
class MyPrescientWarning(UserWarning):
pass
def warn_cassandra():
warn(MyPrescientWarning("Cassandra says..."))
with pytest.warns(MyPrescientWarning, match="Cassandra says..."):
await c.submit(warn_cassandra)
@gen_cluster(client=True, Worker=Nanny)
async def test_print_remote(c, s, a, b, capsys):
from dask.distributed import print
def foo():
print("Hello!", 123)
def bar():
print("Hello!", 123, sep=":")
def baz():
print("Hello!", 123, sep=":", end="")
def frotz():
# like builtin print(), None values for kwargs should be same as
# defaults " ", "\n", sys.stdout, False, respectively.
# (But note we don't really have a good way to test for flushes.)
print("Hello!", 123, sep=None, end=None, file=None, flush=None)
def plugh():
# no positional arguments
print(sep=":", end=".")
def print_stdout():
print("meow", file=sys.stdout)
def print_stderr():
print("meow", file=sys.stderr)
def print_badfile():
print("meow", file="my arbitrary file object")
capsys.readouterr() # drop any output captured so far
await c.submit(foo)
out, err = capsys.readouterr()
assert "Hello! 123\n" == out
await c.submit(bar)
out, err = capsys.readouterr()
assert "Hello!:123\n" == out
await c.submit(baz)
out, err = capsys.readouterr()
assert "Hello!:123" == out
await c.submit(frotz)
out, err = capsys.readouterr()
assert "Hello! 123\n" == out
await c.submit(plugh)
out, err = capsys.readouterr()
assert "." == out
await c.submit(print_stdout)
out, err = capsys.readouterr()
assert "meow\n" == out and "" == err
await c.submit(print_stderr)
out, err = capsys.readouterr()
assert "meow\n" == err and "" == out
with pytest.raises(TypeError):
await c.submit(print_badfile)
@gen_cluster(client=True, Worker=Nanny)
async def test_print_manual(c, s, a, b, capsys):
def foo():
get_worker().log_event("print", "Hello!")
capsys.readouterr() # drop any output captured so far
await c.submit(foo)
out, err = capsys.readouterr()
assert "Hello!\n" == out
def print_otherfile():
# this should log a TypeError in the client
get_worker().log_event("print", {"args": ("hello",), "file": "bad value"})
with captured_logger("distributed.client") as log:
await c.submit(print_otherfile)
assert "TypeError" in log.getvalue()
@gen_cluster(client=True, Worker=Nanny)
async def test_print_manual_bad_args(c, s, a, b, capsys):
def foo():
get_worker().log_event("print", {"args": "not a tuple"})
with captured_logger("distributed.client") as log:
await c.submit(foo)
assert "TypeError" in log.getvalue()
@gen_cluster(client=True, Worker=Nanny)
async def test_print_non_msgpack_serializable(c, s, a, b, capsys):
from dask.distributed import print
def foo():
print(object())
await c.submit(foo)
out, err = capsys.readouterr()
assert "<object object at" in out
def test_print_local(capsys):
from dask.distributed import print
capsys.readouterr() # drop any output captured so far
print("Hello!", 123, sep=":")
out, err = capsys.readouterr()
assert "Hello!:123\n" == out
@gen_cluster(client=True, Worker=Nanny)
async def test_forward_logging(c, s, a, b):
# logger will be created with default config, which handles ERROR and above.
client_side_logger = logging.getLogger("test.logger")
# set up log forwarding on root logger
await c.forward_logging()
# a task that does some error logging. should be forwarded
def do_error():
logging.getLogger("test.logger").error("Hello error")
with captured_logger(client_side_logger) as log:
await c.submit(do_error)
assert "Hello error" in log.getvalue()
# task that does some error logging with exception traceback info
def do_exception():
try:
raise ValueError("wrong value")
except ValueError:
logging.getLogger("test.logger").error("oops", exc_info=True)
with captured_logger(client_side_logger) as log:
await c.submit(do_exception)
log_out = log.getvalue()
assert "oops" in log_out
assert "Traceback" in log_out
assert "ValueError: wrong value" in log_out
# a task that does some info logging. should NOT be forwarded
def do_info():
logging.getLogger("test.logger").info("Hello info")
with captured_logger(client_side_logger) as log:
await c.submit(do_info)
assert "Hello info" not in log.getvalue()
# If we set level appropriately on both client and worker side, then the
# info record SHOULD be forwarded
client_side_logger.setLevel(logging.INFO)
def do_info_2():
logger = logging.getLogger("test.logger")
logger.setLevel(logging.INFO)
logger.info("Hello info")
with captured_logger(client_side_logger) as log:
await c.submit(do_info_2)
assert "Hello info" in log.getvalue()
# stop forwarding logging; the client-side logger should no longer
# receive forwarded records
await c.unforward_logging()
with captured_logger(client_side_logger) as log:
await c.submit(do_error)
assert "Hello error" not in log.getvalue()
# logger-specific forwarding:
# we should get no forwarded records from do_error(), but we should get
# forwarded records from do_error_other().
client_side_other_logger = logging.getLogger("test.other_logger")
await c.forward_logging("test.other_logger")
def do_error_other():
logging.getLogger("test.other_logger").error("Hello error")
with captured_logger(client_side_logger) as log:
await c.submit(do_error)
# no record forwarded to test.logger
assert "Hello error" not in log.getvalue()
with captured_logger(client_side_other_logger) as log:
await c.submit(do_error_other)
# record forwarded to test.other_logger
assert "Hello error" in log.getvalue()
await c.unforward_logging("test.other_logger")
# test the optional `level` argument of forward_logging(). Same semantics as
# `level` of built-in logging.Handlers: restriction applied on top of the
# level of whatever logger the handler is added to
await c.forward_logging("test.yet_another_logger", logging.CRITICAL)
client_side_yet_another_logger = logging.getLogger("test.yet_another_logger")
def do_error_yet_another():
logging.getLogger("test.yet_another_logger").error("Hello error")
def do_critical_yet_another():
logging.getLogger("test.yet_another_logger").critical("Hello criticality")
with captured_logger(client_side_yet_another_logger) as log:
await c.submit(do_error_yet_another)
# no record forwarded to logger, even though the logger by default would
# handle ERRORs, because we are only forwarding CRITICAL and above
assert "Hello error" not in log.getvalue()
with captured_logger(client_side_yet_another_logger) as log:
await c.submit(do_critical_yet_another)
# record forwarded to logger
assert "Hello criticality" in log.getvalue()
def _verify_cluster_dump(
url: str | pathlib.PosixPath, format: str, addresses: set[str]
) -> dict:
fsspec = pytest.importorskip("fsspec") # for load_cluster_dump
url = str(url) + (".msgpack.gz" if format == "msgpack" else ".yaml")
state = load_cluster_dump(url)
assert isinstance(state, dict)
assert "scheduler" in state
assert "workers" in state
assert "versions" in state
assert state["workers"].keys() == addresses
return state
def test_dump_cluster_state_write_from_scheduler(c, s, a, b, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
scheduler_dir = tmp_path / "scheduler"
scheduler_dir.mkdir()
c.run_on_scheduler(os.chdir, str(scheduler_dir))
c.dump_cluster_state("not-url")
assert (tmp_path / "not-url.msgpack.gz").is_file()
c.dump_cluster_state("file://is-url")
assert (scheduler_dir / "is-url.msgpack.gz").is_file()
c.dump_cluster_state("file://local-explicit", write_from_scheduler=False)
assert (tmp_path / "local-explicit.msgpack.gz").is_file()
c.dump_cluster_state("scheduler-explicit", write_from_scheduler=True)
assert (scheduler_dir / "scheduler-explicit.msgpack.gz").is_file()
@pytest.mark.parametrize("local", [True, False])
@pytest.mark.parametrize("_format", ["msgpack", "yaml"])
def test_dump_cluster_state_sync(c, s, a, b, tmp_path, _format, local):
filename = tmp_path / "foo"
if not local:
pytest.importorskip("fsspec")
# Make it look like an fsspec path
filename = f"file://{filename}"
c.dump_cluster_state(filename, format=_format)
_verify_cluster_dump(filename, _format, {a["address"], b["address"]})
@pytest.mark.parametrize("local", [True, False])
@pytest.mark.parametrize("_format", ["msgpack", "yaml"])
@gen_cluster(client=True)
async def test_dump_cluster_state_async(c, s, a, b, tmp_path, _format, local):
filename = tmp_path / "foo"
if not local:
pytest.importorskip("fsspec")
# Make it look like an fsspec path
filename = f"file://{filename}"
await c.dump_cluster_state(filename, format=_format)
_verify_cluster_dump(filename, _format, {a.address, b.address})
@pytest.mark.parametrize("local", [True, False])
@gen_cluster(client=True)
async def test_dump_cluster_state_json(c, s, a, b, tmp_path, local):
filename = tmp_path / "foo"
if not local:
pytest.importorskip("fsspec")
# Make it look like an fsspec path
filename = f"file://{filename}"
with pytest.raises(ValueError, match="Unsupported format"):
await c.dump_cluster_state(filename, format="json")
@gen_cluster(client=True)
async def test_dump_cluster_state_exclude_default(c, s, a, b, tmp_path):
futs = c.map(inc, range(10))
while len(s.tasks) != len(futs):
await asyncio.sleep(0.01)
# GraphNode / callables are never included
always_excluded = ["run_spec"]
exclude = ["state"]
filename = tmp_path / "foo"
await c.dump_cluster_state(
filename=filename,
format="yaml",
)
with open(f"{filename}.yaml") as fd:
state = yaml.safe_load(fd)
assert "workers" in state
assert len(state["workers"]) == len(s.workers)
for worker_dump in state["workers"].values():
for k, task_dump in worker_dump["tasks"].items():
assert not any(blocked in task_dump for blocked in always_excluded)
assert any(blocked in task_dump for blocked in exclude)
assert k in s.tasks
assert "scheduler" in state
assert "tasks" in state["scheduler"]
tasks = state["scheduler"]["tasks"]
assert len(tasks) == len(futs)
for k, task_dump in tasks.items():
assert not any(blocked in task_dump for blocked in always_excluded)
assert any(blocked in task_dump for blocked in exclude)
assert k in s.tasks
await c.dump_cluster_state(
filename=filename,
format="yaml",
exclude=exclude,
)
with open(f"{filename}.yaml") as fd:
state = yaml.safe_load(fd)
assert "workers" in state
assert len(state["workers"]) == len(s.workers)
for worker_dump in state["workers"].values():
for k, task_dump in worker_dump["tasks"].items():
assert not any(blocked in task_dump for blocked in always_excluded)
assert not any(blocked in task_dump for blocked in exclude)
assert k in s.tasks
assert "scheduler" in state
assert "tasks" in state["scheduler"]
tasks = state["scheduler"]["tasks"]
assert len(tasks) == len(futs)
for k, task_dump in tasks.items():
assert not any(blocked in task_dump for blocked in always_excluded)
assert not any(blocked in task_dump for blocked in exclude)
assert k in s.tasks
| MyHashable |
python | networkx__networkx | networkx/algorithms/tests/test_link_prediction.py | {
"start": 6663,
"end": 7945
} | class ____:
@classmethod
def setup_class(cls):
cls.func = staticmethod(nx.preferential_attachment)
cls.test = staticmethod(partial(_test_func, predict_func=cls.func))
def test_K5(self):
G = nx.complete_graph(5)
self.test(G, [(0, 1)], [(0, 1, 16)])
def test_P3(self):
G = nx.path_graph(3)
self.test(G, [(0, 1)], [(0, 1, 2)])
def test_S4(self):
G = nx.star_graph(4)
self.test(G, [(0, 2)], [(0, 2, 4)])
@pytest.mark.parametrize("graph_type", (nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph))
def test_notimplemented(self, graph_type):
G = graph_type([(0, 1), (1, 2)])
with pytest.raises(nx.NetworkXNotImplemented):
self.func(G, [(0, 2)])
def test_node_not_found(self):
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
with pytest.raises(nx.NodeNotFound):
self.func(G, [(0, 4)])
def test_zero_degrees(self):
G = nx.Graph()
G.add_nodes_from([0, 1])
self.test(G, [(0, 1)], [(0, 1, 0)])
def test_all_nonexistent_edges(self):
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (2, 3)])
self.test(G, None, [(0, 3, 2), (1, 2, 2), (1, 3, 1)])
| TestPreferentialAttachment |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_engine.py | {
"start": 7277,
"end": 8195
} | class ____(AsyncFixture, fixtures.TablesTest):
__requires__ = ("async_dialect",)
@testing.fixture
def async_engine(self):
return engines.testing_engine(
asyncio=True, options={"sqlite_share_pool": True}
)
@testing.fixture
def async_connection(self, async_engine):
with async_engine.sync_engine.connect() as conn:
yield AsyncConnection(async_engine, conn)
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("user_id", Integer, primary_key=True, autoincrement=False),
Column("user_name", String(20)),
)
@classmethod
def insert_data(cls, connection):
users = cls.tables.users
connection.execute(
users.insert(),
[{"user_id": i, "user_name": "name%d" % i} for i in range(1, 20)],
)
| EngineFixture |
python | docker__docker-py | tests/integration/api_network_test.py | {
"start": 185,
"end": 18867
} | class ____(BaseAPIIntegrationTest):
def tearDown(self):
self.client.leave_swarm(force=True)
super().tearDown()
def create_network(self, *args, **kwargs):
net_name = random_name()
net_id = self.client.create_network(net_name, *args, **kwargs)['Id']
self.tmp_networks.append(net_id)
return (net_name, net_id)
def test_list_networks(self):
networks = self.client.networks()
net_name, net_id = self.create_network()
networks = self.client.networks()
assert net_id in [n['Id'] for n in networks]
networks_by_name = self.client.networks(names=[net_name])
assert [n['Id'] for n in networks_by_name] == [net_id]
networks_by_partial_id = self.client.networks(ids=[net_id[:8]])
assert [n['Id'] for n in networks_by_partial_id] == [net_id]
def test_inspect_network(self):
net_name, net_id = self.create_network()
net = self.client.inspect_network(net_id)
assert net['Id'] == net_id
assert net['Name'] == net_name
assert net['Driver'] == 'bridge'
assert net['Scope'] == 'local'
assert net['IPAM']['Driver'] == 'default'
def test_create_network_with_ipam_config(self):
_, net_id = self.create_network(
ipam=IPAMConfig(
driver='default',
pool_configs=[
IPAMPool(
subnet="172.28.0.0/16",
iprange="172.28.5.0/24",
gateway="172.28.5.254",
aux_addresses={
"a": "172.28.1.5",
"b": "172.28.1.6",
"c": "172.28.1.7",
},
),
],
),
)
net = self.client.inspect_network(net_id)
ipam = net['IPAM']
assert ipam.pop('Options', None) is None
assert ipam['Driver'] == 'default'
assert ipam['Config'] == [{
'Subnet': "172.28.0.0/16",
'IPRange': "172.28.5.0/24",
'Gateway': "172.28.5.254",
'AuxiliaryAddresses': {
"a": "172.28.1.5",
"b": "172.28.1.6",
"c": "172.28.1.7",
},
}]
def test_create_network_with_host_driver_fails(self):
with pytest.raises(docker.errors.APIError):
self.client.create_network(random_name(), driver='host')
def test_remove_network(self):
net_name, net_id = self.create_network()
assert net_name in [n['Name'] for n in self.client.networks()]
self.client.remove_network(net_id)
assert net_name not in [n['Name'] for n in self.client.networks()]
def test_connect_and_disconnect_container(self):
net_name, net_id = self.create_network()
container = self.client.create_container(TEST_IMG, 'top')
self.tmp_containers.append(container)
self.client.start(container)
network_data = self.client.inspect_network(net_id)
assert not network_data.get('Containers')
self.client.connect_container_to_network(container, net_id)
network_data = self.client.inspect_network(net_id)
assert list(network_data['Containers'].keys()) == [
container['Id']
]
with pytest.raises(docker.errors.APIError):
self.client.connect_container_to_network(container, net_id)
self.client.disconnect_container_from_network(container, net_id)
network_data = self.client.inspect_network(net_id)
assert not network_data.get('Containers')
with pytest.raises(docker.errors.APIError):
self.client.disconnect_container_from_network(container, net_id)
@requires_api_version('1.22')
def test_connect_and_force_disconnect_container(self):
net_name, net_id = self.create_network()
container = self.client.create_container(TEST_IMG, 'top')
self.tmp_containers.append(container)
self.client.start(container)
network_data = self.client.inspect_network(net_id)
assert not network_data.get('Containers')
self.client.connect_container_to_network(container, net_id)
network_data = self.client.inspect_network(net_id)
assert list(network_data['Containers'].keys()) == \
[container['Id']]
self.client.disconnect_container_from_network(container, net_id, True)
network_data = self.client.inspect_network(net_id)
assert not network_data.get('Containers')
with pytest.raises(docker.errors.APIError):
self.client.disconnect_container_from_network(
container, net_id, force=True
)
@requires_api_version('1.22')
def test_connect_with_aliases(self):
net_name, net_id = self.create_network()
container = self.client.create_container(TEST_IMG, 'top')
self.tmp_containers.append(container)
self.client.start(container)
self.client.connect_container_to_network(
container, net_id, aliases=['foo', 'bar'])
container_data = self.client.inspect_container(container)
aliases = (
container_data['NetworkSettings']['Networks'][net_name]['Aliases']
)
assert 'foo' in aliases
assert 'bar' in aliases
def test_connect_on_container_create(self):
net_name, net_id = self.create_network()
container = self.client.create_container(
image=TEST_IMG,
command='top',
host_config=self.client.create_host_config(network_mode=net_name),
)
self.tmp_containers.append(container)
self.client.start(container)
network_data = self.client.inspect_network(net_id)
assert list(network_data['Containers'].keys()) == \
[container['Id']]
self.client.disconnect_container_from_network(container, net_id)
network_data = self.client.inspect_network(net_id)
assert not network_data.get('Containers')
@requires_api_version('1.22')
def test_create_with_aliases(self):
net_name, net_id = self.create_network()
container = self.client.create_container(
image=TEST_IMG,
command='top',
host_config=self.client.create_host_config(
network_mode=net_name,
),
networking_config=self.client.create_networking_config({
net_name: self.client.create_endpoint_config(
aliases=['foo', 'bar'],
),
}),
)
self.tmp_containers.append(container)
self.client.start(container)
container_data = self.client.inspect_container(container)
aliases = (
container_data['NetworkSettings']['Networks'][net_name]['Aliases']
)
assert 'foo' in aliases
assert 'bar' in aliases
@requires_api_version('1.22')
def test_create_with_ipv4_address(self):
net_name, net_id = self.create_network(
ipam=IPAMConfig(
driver='default',
pool_configs=[IPAMPool(subnet="132.124.0.0/16")],
),
)
container = self.client.create_container(
image=TEST_IMG, command='top',
host_config=self.client.create_host_config(network_mode=net_name),
networking_config=self.client.create_networking_config({
net_name: self.client.create_endpoint_config(
ipv4_address='132.124.0.23'
)
})
)
self.tmp_containers.append(container)
self.client.start(container)
net_settings = self.client.inspect_container(container)[
'NetworkSettings'
]
assert net_settings['Networks'][net_name]['IPAMConfig']['IPv4Address']\
== '132.124.0.23'
@requires_api_version('1.22')
def test_create_with_ipv6_address(self):
net_name, net_id = self.create_network(
enable_ipv6=True,
ipam=IPAMConfig(
driver='default',
pool_configs=[IPAMPool(subnet="2001:389::/64")],
),
)
container = self.client.create_container(
image=TEST_IMG, command='top',
host_config=self.client.create_host_config(network_mode=net_name),
networking_config=self.client.create_networking_config({
net_name: self.client.create_endpoint_config(
ipv6_address='2001:389::f00d'
)
})
)
self.tmp_containers.append(container)
self.client.start(container)
net_settings = self.client.inspect_container(container)[
'NetworkSettings'
]
assert net_settings['Networks'][net_name]['IPAMConfig']['IPv6Address']\
== '2001:389::f00d'
@requires_api_version('1.24')
def test_create_with_linklocal_ips(self):
container = self.client.create_container(
TEST_IMG, 'top',
networking_config=self.client.create_networking_config(
{
'bridge': self.client.create_endpoint_config(
link_local_ips=['169.254.8.8']
)
}
),
host_config=self.client.create_host_config(network_mode='bridge')
)
self.tmp_containers.append(container)
self.client.start(container)
container_data = self.client.inspect_container(container)
net_cfg = container_data['NetworkSettings']['Networks']['bridge']
assert 'IPAMConfig' in net_cfg
assert 'LinkLocalIPs' in net_cfg['IPAMConfig']
assert net_cfg['IPAMConfig']['LinkLocalIPs'] == ['169.254.8.8']
@requires_api_version('1.32')
def test_create_with_driveropt(self):
container = self.client.create_container(
TEST_IMG, 'top',
networking_config=self.client.create_networking_config(
{
'bridge': self.client.create_endpoint_config(
driver_opt={'com.docker-py.setting': 'on'}
)
}
),
host_config=self.client.create_host_config(network_mode='bridge')
)
self.tmp_containers.append(container)
self.client.start(container)
container_data = self.client.inspect_container(container)
net_cfg = container_data['NetworkSettings']['Networks']['bridge']
assert 'DriverOpts' in net_cfg
assert 'com.docker-py.setting' in net_cfg['DriverOpts']
assert net_cfg['DriverOpts']['com.docker-py.setting'] == 'on'
@requires_api_version('1.22')
def test_create_with_links(self):
net_name, net_id = self.create_network()
container = self.create_and_start(
host_config=self.client.create_host_config(network_mode=net_name),
networking_config=self.client.create_networking_config({
net_name: self.client.create_endpoint_config(
links=[('docker-py-test-upstream', 'bar')],
),
}),
)
net_settings = self.client.inspect_container(container)[
'NetworkSettings'
]
assert net_settings['Networks'][net_name]['Links'] == [
'docker-py-test-upstream:bar'
]
self.create_and_start(
name='docker-py-test-upstream',
host_config=self.client.create_host_config(network_mode=net_name),
)
self.execute(container, ['nslookup', 'bar'])
def test_create_check_duplicate(self):
net_name, net_id = self.create_network()
with pytest.raises(docker.errors.APIError):
self.client.create_network(net_name, check_duplicate=True)
@requires_api_version('1.22')
def test_connect_with_links(self):
net_name, net_id = self.create_network()
container = self.create_and_start(
host_config=self.client.create_host_config(network_mode=net_name))
self.client.disconnect_container_from_network(container, net_name)
self.client.connect_container_to_network(
container, net_name,
links=[('docker-py-test-upstream', 'bar')])
net_settings = self.client.inspect_container(container)[
'NetworkSettings'
]
assert net_settings['Networks'][net_name]['Links'] == [
'docker-py-test-upstream:bar'
]
self.create_and_start(
name='docker-py-test-upstream',
host_config=self.client.create_host_config(network_mode=net_name),
)
self.execute(container, ['nslookup', 'bar'])
@requires_api_version('1.22')
def test_connect_with_ipv4_address(self):
net_name, net_id = self.create_network(
ipam=IPAMConfig(
driver='default',
pool_configs=[
IPAMPool(
subnet="172.28.0.0/16", iprange="172.28.5.0/24",
gateway="172.28.5.254"
)
]
)
)
container = self.create_and_start(
host_config=self.client.create_host_config(network_mode=net_name))
self.client.disconnect_container_from_network(container, net_name)
self.client.connect_container_to_network(
container, net_name, ipv4_address='172.28.5.24'
)
container_data = self.client.inspect_container(container)
net_data = container_data['NetworkSettings']['Networks'][net_name]
assert net_data['IPAMConfig']['IPv4Address'] == '172.28.5.24'
@requires_api_version('1.22')
def test_connect_with_ipv6_address(self):
net_name, net_id = self.create_network(
enable_ipv6=True,
ipam=IPAMConfig(
driver='default',
pool_configs=[
IPAMPool(
subnet="2001:389::/64", iprange="2001:389::0/96",
gateway="2001:389::ffff"
)
]
)
)
container = self.create_and_start(
host_config=self.client.create_host_config(network_mode=net_name))
self.client.disconnect_container_from_network(container, net_name)
self.client.connect_container_to_network(
container, net_name, ipv6_address='2001:389::f00d'
)
container_data = self.client.inspect_container(container)
net_data = container_data['NetworkSettings']['Networks'][net_name]
assert net_data['IPAMConfig']['IPv6Address'] == '2001:389::f00d'
@requires_api_version('1.25')
def test_connect_with_mac_address(self):
net_name, net_id = self.create_network()
container = self.client.create_container(TEST_IMG, 'top')
self.tmp_containers.append(container)
self.client.connect_container_to_network(
container, net_name, mac_address='02:42:ac:11:00:02'
)
container_data = self.client.inspect_container(container)
net_data = container_data['NetworkSettings']['Networks'][net_name]
assert net_data['MacAddress'] == '02:42:ac:11:00:02'
@requires_api_version('1.23')
def test_create_internal_networks(self):
_, net_id = self.create_network(internal=True)
net = self.client.inspect_network(net_id)
assert net['Internal'] is True
@requires_api_version('1.23')
def test_create_network_with_labels(self):
_, net_id = self.create_network(labels={
'com.docker.py.test': 'label'
})
net = self.client.inspect_network(net_id)
assert 'Labels' in net
assert len(net['Labels']) == 1
assert net['Labels'] == {
'com.docker.py.test': 'label'
}
@requires_api_version('1.23')
def test_create_network_with_labels_wrong_type(self):
with pytest.raises(TypeError):
self.create_network(labels=['com.docker.py.test=label', ])
@requires_api_version('1.23')
def test_create_network_ipv6_enabled(self):
_, net_id = self.create_network(
enable_ipv6=True, ipam=IPAMConfig(
driver='default',
pool_configs=[
IPAMPool(
subnet="2001:389::/64", iprange="2001:389::0/96",
gateway="2001:389::ffff"
)
]
)
)
net = self.client.inspect_network(net_id)
assert net['EnableIPv6'] is True
@requires_api_version('1.25')
def test_create_network_attachable(self):
assert self.init_swarm()
_, net_id = self.create_network(driver='overlay', attachable=True)
net = self.client.inspect_network(net_id)
assert net['Attachable'] is True
@requires_api_version('1.29')
def test_create_network_ingress(self):
assert self.init_swarm()
self.client.remove_network('ingress')
_, net_id = self.create_network(driver='overlay', ingress=True)
net = self.client.inspect_network(net_id)
assert net['Ingress'] is True
@requires_api_version('1.25')
def test_prune_networks(self):
net_name, _ = self.create_network()
result = self.client.prune_networks()
assert net_name in result['NetworksDeleted']
@requires_api_version('1.31')
def test_create_inspect_network_with_scope(self):
assert self.init_swarm()
net_name_loc, net_id_loc = self.create_network(scope='local')
assert self.client.inspect_network(net_name_loc)
assert self.client.inspect_network(net_name_loc, scope='local')
with pytest.raises(docker.errors.NotFound):
self.client.inspect_network(net_name_loc, scope='global')
net_name_swarm, net_id_swarm = self.create_network(
driver='overlay', scope='swarm'
)
assert self.client.inspect_network(net_name_swarm)
assert self.client.inspect_network(net_name_swarm, scope='swarm')
with pytest.raises(docker.errors.NotFound):
self.client.inspect_network(net_name_swarm, scope='local')
def test_create_remove_network_with_space_in_name(self):
net_id = self.client.create_network('test 01')
self.tmp_networks.append(net_id)
assert self.client.inspect_network('test 01')
assert self.client.remove_network('test 01') is None # does not raise
| TestNetworks |
python | pytorch__pytorch | test/mobile/model_test/builtin_ops.py | {
"start": 96,
"end": 2295
} | class ____(torch.nn.Module):
def forward(self):
x = torch.tensor(1)
y = torch.tensor(0.5)
b = float(1)
l = ["1", "2", "test", "a{}b"]
d = {"key": 1}
d2 = {0: 100}
return len(
# type
bool(x),
bool(x.item()),
int(y),
int(y.item()),
float(x),
float(x.item()),
# math
x & x,
bool(x) & bool(x),
int(x) & int(x),
x | x,
bool(x) | bool(x),
int(x) | int(x),
x << x,
int(x) << int(x),
x >> x,
int(x) >> int(x),
x ^ x,
bool(x) ^ bool(x),
int(x) ^ int(x),
b * float(x),
b * int(x),
b + float(x),
b - float(x),
x.item() + y.item(),
x.item() - y.item(),
x.item() * y.item(),
x.item() / y.item(),
float(x) < float(y),
float(x) <= float(y),
float(x) > float(y),
float(x) > int(y),
float(x) >= float(y),
float(x) >= int(y),
float(x) == float(y),
float(x) == int(y),
float(x) != float(y),
int(x) != float(y),
float(x) / float(y),
int(x) / int(y),
max(x),
max(x.item(), y.item()),
max(int(x), int(y)),
max(float(x), float(y)),
min(x),
min(x.item(), y.item()),
min(int(x), int(y)),
min(float(x), float(y)),
int(l[0]),
float(l[0]),
# string
str(torch.tensor(1)),
l[2].find("t"),
l[2].replace("t", "x"),
l[2].lower(),
l[2].startswith("t"),
l[2].split("t"),
l[2].strip(),
l[2].rstrip(),
l[2].lstrip(),
l[2][slice(2)],
l[3].format("x"),
ord(l[2][0]),
len(torch.randn(3)),
len(l),
len(l[2]),
len(d),
len(d2),
)
| TSBuiltinOpsModule |
python | conda__conda | conda/cli/condarc.py | {
"start": 5765,
"end": 20141
} | class ____:
"""
Represents and manipulates a conda configuration (.condarc) file.
Provides methods to read, write, and modify configuration files while
validating keys and maintaining proper structure.
Can be used as a context manager for atomic edits:
with ConfigurationFile.from_user_condarc() as config:
config.set_key("channels", ["conda-forge"])
config.add("channels", "defaults")
# File is automatically written when exiting the context
"""
def __init__(
self,
path: str | os.PathLike[str] | Path | None = None,
context: Configuration | None = None,
content: dict[str, Any] | None = None,
warning_handler: Callable[[str], None] | None = None,
) -> None:
self._path = path
self._content = content
self._context = context
self._context_params: ParameterTypeGroups | None = None
self.warning_handler = warning_handler or (lambda msg: None)
@classmethod
def from_user_condarc(
cls, context: Configuration | None = None
) -> ConfigurationFile:
"""
Create a ConfigurationFile instance for the default user .condarc file.
:param context: Optional Configuration instance. If None, uses the global context.
:returns: ConfigurationFile instance configured for the user's .condarc file.
"""
from ..base.context import user_rc_path
return cls(path=user_rc_path, context=context)
@classmethod
def from_system_condarc(
cls, context: Configuration | None = None
) -> ConfigurationFile:
"""
Create a ConfigurationFile instance for the system .condarc file.
:param context: Optional Configuration instance. If None, uses the global context.
:returns: ConfigurationFile instance configured for the system .condarc file.
"""
from ..base.context import sys_rc_path
return cls(path=sys_rc_path, context=context)
@classmethod
def from_env_condarc(
cls,
prefix: str | os.PathLike[str] | Path | None = None,
context: Configuration | None = None,
) -> ConfigurationFile:
"""
Create a ConfigurationFile instance for an environment-specific .condarc file.
Environment-specific .condarc files are located at `{prefix}/.condarc` and allow
per-environment configuration overrides.
:param prefix: Path to the conda environment. If None, uses $CONDA_PREFIX or sys.prefix.
:param context: Optional Configuration instance. If None, uses the global context.
:returns: ConfigurationFile instance configured for the environment's .condarc file.
"""
if prefix is None:
prefix = os.environ.get("CONDA_PREFIX", sys.prefix)
return cls(path=Path(prefix) / DEFAULT_CONDARC_FILENAME, context=context)
def __enter__(self) -> ConfigurationFile:
"""Enter the context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""Exit the context manager and write changes if no exception occurred."""
if exc_type is None:
self.write()
@property
def path(self) -> str | os.PathLike[str] | Path:
"""
Get the path to the configuration file.
:returns: Path to the configuration file.
:raises AttributeError: If path has not been set.
"""
if self._path is None:
raise AttributeError("Configuration file path has not been set")
return self._path
@path.setter
def path(self, path: str | os.PathLike[str] | Path) -> None:
"""
Set the path to the configuration file.
:param path: Path to the configuration file.
"""
self._path = path
@property
def context(self) -> Configuration:
"""
Get the context instance.
If no context was provided during initialization, falls back to the global
conda context singleton. This lazy import is necessary to avoid circular
dependencies at module load time.
:returns: Configuration instance.
"""
if self._context is None:
# Import the global context singleton
# This is imported lazily to avoid circular import issues
from ..base.context import context
self._context = context
return self._context
@property
def context_params(self) -> ParameterTypeGroups:
if self._context_params is None:
self._context_params = ParameterTypeGroups(self.context)
return self._context_params
@property
def content(self) -> dict[str, Any]:
"""
Get the configuration content, reading from file if needed.
:returns: Dictionary containing configuration content.
"""
if self._content is None:
self.read()
return self._content
def read(self, path: str | os.PathLike[str] | Path | None = None) -> dict[str, Any]:
"""
Read configuration content from file.
:param path: Optional path to read from. If None, uses the instance path.
:returns: Dictionary containing configuration content.
"""
from ..common.serialize import yaml_round_trip_load
path = Path(path or self._path)
try:
self._content = (
yaml_round_trip_load(Path(path or self._path).read_text()) or {}
)
except FileNotFoundError:
self._content = {}
return self._content
def write(self, path: str | os.PathLike[str] | Path | None = None) -> None:
"""
Write configuration content to file.
:param path: Optional path to write to. If None, uses the instance path.
:raises CondaError: If the file cannot be written.
"""
from .. import CondaError
from ..common.serialize import yaml_round_trip_dump
path: Path = Path(path or self._path)
try:
path.write_text(yaml_round_trip_dump(self.content))
except OSError as e:
raise CondaError(f"Cannot write to condarc file at {path}\nCaused by {e!r}")
def key_exists(self, key: str) -> bool:
"""
Check if a configuration key is valid.
:param key: Configuration key to check.
:returns: True if the key is valid, False otherwise.
"""
first, *rest = key.split(".")
# Handle plugin parameters if the context has a plugins attribute
if (
first == "plugins"
and len(rest) > 0
and hasattr(self.context, "plugins")
and rest[0] in self.context.plugins.list_parameters()
):
return True
if first not in self.context.list_parameters():
exists = bool(self.context.name_for_alias(first))
if not exists:
self.warning_handler(f"Unknown key: {key!r}")
return exists
return True
def add(self, key: str, item: Any, prepend: bool = False) -> None:
"""
Add an item to a sequence configuration parameter.
:param key: Configuration key name (may contain dots for nested keys).
:param item: Item to add to the sequence.
:param prepend: If True, add to the beginning; if False, add to the end.
:raises CondaValueError: If the key is not a known sequence parameter.
:raises CouldntParseError: If the key should be a list but isn't.
"""
from ..exceptions import CondaValueError, CouldntParseError
key, subkey = key.split(".", 1) if "." in key else (key, None)
if key in self.context_params.sequence_parameters:
arglist = self.content.setdefault(key, [])
elif (
key == "plugins"
and subkey in self.context_params.plugin_sequence_parameters
):
arglist = self.content.setdefault("plugins", {}).setdefault(subkey, [])
elif key in self.context_params.map_parameters:
arglist = self.content.setdefault(key, {}).setdefault(subkey, [])
elif key in self.context_params.plugin_map_parameters:
arglist = self.content.setdefault("plugins", {}).setdefault(subkey, {})
else:
raise CondaValueError(f"Key '{key}' is not a known sequence parameter.")
if not (isinstance(arglist, Sequence) and not isinstance(arglist, str)):
bad = self.content[key].__class__.__name__
raise CouldntParseError(f"key {key!r} should be a list, not {bad}.")
if item in arglist:
# Right now, all list keys should not contain duplicates
location = "top" if prepend else "bottom"
message_key = key + "." + subkey if subkey is not None else key
message = f"Warning: '{item}' already in '{message_key}' list, moving to the {location}"
if subkey is None:
arglist = self.content[key] = [p for p in arglist if p != item]
else:
arglist = self.content[key][subkey] = [p for p in arglist if p != item]
self.warning_handler(msg=message)
arglist.insert(0 if prepend else len(arglist), item)
def get_key(
self,
key: str,
) -> tuple[str, Any | _MissingSentinel]:
"""
Get a configuration value by key.
:param key: Configuration key name (may contain dots for nested keys).
:returns: Tuple of (key, value) or (key, MISSING) if key doesn't exist.
"""
key_parts = key.split(".")
if not self.key_exists(key):
return key, MISSING
if alias := self.context.name_for_alias(key):
key = alias
key_parts = alias.split(".")
sub_config = self.content
try:
for part in key_parts:
sub_config = sub_config[part]
except KeyError:
pass
else:
return key, sub_config
return key, MISSING
def set_key(self, key: str, item: Any) -> None:
"""
Set a configuration value for a primitive or map parameter.
:param key: Configuration key name (may contain dots for nested keys).
:param item: Value to set.
:raises CondaKeyError: If the key is unknown or invalid.
"""
from ..exceptions import CondaKeyError
if not self.key_exists(key):
raise CondaKeyError(key, "unknown parameter")
if aliased := self.context.name_for_alias(key):
log.warning(
"Key %s is an alias of %s; setting value with latter", key, aliased
)
key = aliased
first, *rest = key.split(".")
if first == "plugins" and hasattr(self.context, "plugins"):
base_context = self.context.plugins
base_config = self.content.setdefault("plugins", {})
parameter_name, *rest = rest
else:
base_context = self.context
base_config = self.content
parameter_name = first
parameter_type = base_context.describe_parameter(parameter_name)[
"parameter_type"
]
if parameter_type == "primitive" and len(rest) == 0:
base_config[parameter_name] = base_context.typify_parameter(
parameter_name, item, "--set parameter"
)
elif parameter_type == "map" and len(rest) == 1:
base_config.setdefault(parameter_name, {})[rest[0]] = item
else:
raise CondaKeyError(key, "invalid parameter")
def remove_item(self, key: str, item: Any) -> None:
"""
Remove an item from a sequence configuration parameter.
:param key: Configuration key name.
:param item: Item to remove from the sequence.
:raises CondaKeyError: If the key is unknown, undefined, or the item is not present.
"""
from ..exceptions import CondaKeyError
first, *rest = key.split(".")
if first == "plugins" and hasattr(self.context, "plugins"):
base_context = self.context.plugins
base_config = self.content.setdefault("plugins", {})
parameter_name = rest[0]
rest = []
else:
base_context = self.context
base_config = self.content
parameter_name = first
try:
parameter_type = base_context.describe_parameter(parameter_name)[
"parameter_type"
]
except KeyError:
# KeyError: key_parts[0] is an unknown parameter
raise CondaKeyError(key, "unknown parameter")
if parameter_type == "sequence" and len(rest) == 0:
if parameter_name not in base_config:
if parameter_name != "channels":
raise CondaKeyError(key, "undefined in config")
self.content[parameter_name] = ["defaults"]
if item not in base_config[parameter_name]:
raise CondaKeyError(
parameter_name, f"value {item!r} not present in config"
)
base_config[parameter_name] = [
i for i in base_config[parameter_name] if i != item
]
else:
raise CondaKeyError(key, "invalid parameter")
def remove_key(self, key: str) -> None:
"""
Remove a configuration key entirely.
:param key: Configuration key name (may contain dots for nested keys).
:raises CondaKeyError: If the key is undefined in the config.
"""
from ..exceptions import CondaKeyError
key_parts = key.split(".")
sub_config = self.content
try:
for part in key_parts[:-1]:
sub_config = sub_config[part]
del sub_config[key_parts[-1]]
except KeyError:
# KeyError: part not found, nothing to remove, but maybe user passed an alias?
if alias := self.context.name_for_alias(key):
try:
return self.remove_key(alias)
except CondaKeyError:
pass # raise with originally passed key
raise CondaKeyError(key, "undefined in config")
| ConfigurationFile |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 13341,
"end": 13760
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def parent(self):
raise NotImplementedError()
def __call__(self, key):
raise NotImplementedError()
def __len__(self):
raise NotImplementedError()
def __iter__(self):
raise NotImplementedError()
def __contains__(self, key):
raise NotImplementedError()
| Collection |
python | spack__spack | lib/spack/spack/vendor/pyrsistent/_checked_types.py | {
"start": 11685,
"end": 13982
} | class ____(PSet, CheckedType, metaclass=_CheckedTypeMeta):
"""
A CheckedPSet is a PSet which allows specifying type and invariant checks.
>>> class Positives(CheckedPSet):
... __type__ = (int, float)
... __invariant__ = lambda n: (n >= 0, 'Negative')
...
>>> Positives([1, 2, 3])
Positives([1, 2, 3])
"""
__slots__ = ()
def __new__(cls, initial=()):
if type(initial) is PMap:
return super(CheckedPSet, cls).__new__(cls, initial)
evolver = CheckedPSet.Evolver(cls, pset())
for e in initial:
evolver.add(e)
return evolver.persistent()
def __repr__(self):
return self.__class__.__name__ + super(CheckedPSet, self).__repr__()[4:]
def __str__(self):
return self.__repr__()
def serialize(self, format=None):
serializer = self.__serializer__
return set(serializer(format, v) for v in self)
create = classmethod(_checked_type_create)
def __reduce__(self):
# Pickling support
return _restore_pickle, (self.__class__, list(self),)
def evolver(self):
return CheckedPSet.Evolver(self.__class__, self)
class Evolver(PSet._Evolver):
__slots__ = ('_destination_class', '_invariant_errors')
def __init__(self, destination_class, original_set):
super(CheckedPSet.Evolver, self).__init__(original_set)
self._destination_class = destination_class
self._invariant_errors = []
def _check(self, it):
_check_types(it, self._destination_class._checked_types, self._destination_class)
error_data = _invariant_errors_iterable(it, self._destination_class._checked_invariants)
self._invariant_errors.extend(error_data)
def add(self, element):
self._check([element])
self._pmap_evolver[element] = True
return self
def persistent(self):
if self._invariant_errors:
raise InvariantException(error_codes=self._invariant_errors)
if self.is_dirty() or self._destination_class != type(self._original_pset):
return self._destination_class(self._pmap_evolver.persistent())
return self._original_pset
| CheckedPSet |
python | PrefectHQ__prefect | tests/server/schemas/test_states.py | {
"start": 304,
"end": 1716
} | class ____:
def test_state_takes_name_from_type(self):
state = State(type=StateType.RUNNING)
assert state.name == "Running"
def test_state_raises_validation_error_for_invalid_type(self):
with pytest.raises(
pydantic.ValidationError,
match="1 validation error for State\ntype\n Input should be",
):
State(type="Running")
def test_state_custom_name(self):
state = State(type=StateType.RUNNING, name="My Running State")
assert state.name == "My Running State"
def test_state_default_timestamp(self):
dt = datetime.now(timezone.utc)
state = State(type=StateType.RUNNING)
assert state.timestamp >= dt
def test_state_copy_does_not_create_insertable_object(self):
dt = datetime.now(timezone.utc)
state = State(type=StateType.RUNNING, timestamp=dt, id=uuid4())
new_state = state.model_copy()
# Same UUID
assert new_state.id == state.id
def test_state_copy_with_field_reset_creates_insertable_object(self):
dt = datetime.now(timezone.utc)
state = State(type=StateType.RUNNING, timestamp=dt, id=uuid4())
new_state = state.reset_fields()
# New UUID
assert new_state.id != state.id
assert isinstance(new_state.id, UUID)
# New state timestamp
assert new_state.timestamp >= dt
| TestState |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/pickleable.py | {
"start": 1448,
"end": 1804
} | class ____:
def __init__(self, x, y):
self.x = x
self.y = y
__hash__ = object.__hash__
def __eq__(self, other):
return (
other.__class__ is self.__class__
and other.x == self.x
and other.y == self.y
)
def __str__(self):
return "Bar(%d, %d)" % (self.x, self.y)
| Bar |
python | tensorflow__tensorflow | tensorflow/python/training/saver.py | {
"start": 24159,
"end": 25689
} | class ____(BaseSaverBuilder):
"""SaverBuilder with support for bulk restoring multiple saveables."""
def bulk_restore(self, filename_tensor, saveables, preferred_shard,
restore_sequentially):
# Ignored: bulk restore is internally sequential.
del restore_sequentially
restore_specs = []
for saveable in saveables:
for spec in saveable.specs:
restore_specs.append((spec.name, spec.slice_spec, spec.dtype))
names, slices, dtypes = zip(*restore_specs)
# Load all tensors onto CPU 0 for compatibility with existing code.
with ops.device("cpu:0"):
return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
def _get_saver_or_default():
"""Returns the saver from SAVERS collection, or creates a default one.
This method is used by other members of the training module, such as
`Scaffold`, or `CheckpointSaverHook`.
Returns:
`Saver`.
Raises:
RuntimeError: If the SAVERS collection already has more than one items.
"""
collection_key = ops.GraphKeys.SAVERS
savers = ops.get_collection(collection_key)
if savers:
if len(savers) > 1:
raise RuntimeError(
"More than one item in collection {}. "
"Please indicate which one to use by passing it to the constructor."
.format(collection_key))
return savers[0]
saver = Saver(sharded=True, allow_empty=True)
if saver is not None:
ops.add_to_collection(collection_key, saver)
return saver
@tf_export(v1=["train.Saver"])
| BulkSaverBuilder |
python | wandb__wandb | wandb/sdk/launch/errors.py | {
"start": 207,
"end": 275
} | class ____(Error):
"""Generic execution exception."""
| ExecutionError |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/trackable_view.py | {
"start": 1008,
"end": 4436
} | class ____(object):
"""Gathers and serializes a trackable view.
Example usage:
>>> class SimpleModule(tf.Module):
... def __init__(self, name=None):
... super().__init__(name=name)
... self.a_var = tf.Variable(5.0)
... self.b_var = tf.Variable(4.0)
... self.vars = [tf.Variable(1.0), tf.Variable(2.0)]
>>> root = SimpleModule(name="root")
>>> root.leaf = SimpleModule(name="leaf")
>>> trackable_view = tf.train.TrackableView(root)
Pass root to tf.train.TrackableView.children() to get the dictionary of all
children directly linked to root by name.
>>> trackable_view_children = trackable_view.children(root)
>>> for item in trackable_view_children.items():
... print(item)
('a_var', <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>)
('b_var', <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>)
('vars', ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32,
numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]))
('leaf', ...)
"""
def __init__(self, root):
"""Configure the trackable view.
Args:
root: A `Trackable` object whose variables (including the variables of
dependencies, recursively) should be saved. May be a weak reference.
"""
# TrackableView should never contain a strong reference to root, since it
# may result in a cycle:
# root -> deferred dependencies -> CheckpointPosition
# -> CheckpointRestoreCoordinator -> TrackableView -> root
self._root_ref = (root if isinstance(root, weakref.ref)
else weakref.ref(root))
@classmethod
def children(cls, obj, save_type=base.SaveType.CHECKPOINT, **kwargs):
"""Returns all child trackables attached to obj.
Args:
obj: A `Trackable` object.
save_type: A string, can be 'savedmodel' or 'checkpoint'.
**kwargs: kwargs to use when retrieving the object's children.
Returns:
Dictionary of all children attached to the object with name to trackable.
"""
# pylint: disable=protected-access
obj._maybe_initialize_trackable()
children = {}
for name, ref in obj._trackable_children(save_type, **kwargs).items():
ref = converter.convert_to_trackable(ref, parent=obj)
children[name] = ref
return children
@property
def root(self):
if isinstance(self._root_ref, weakref.ref):
derefed = self._root_ref()
assert derefed is not None
return derefed
else:
return self._root_ref
def descendants(self):
"""Returns a list of all nodes from self.root using a breadth first traversal."""
return self._descendants_with_paths()[0]
def _descendants_with_paths(self):
"""Returns a list of all nodes and its paths from self.root using a breadth first traversal."""
bfs_sorted = []
to_visit = collections.deque([self.root])
node_paths = object_identity.ObjectIdentityDictionary()
node_paths[self.root] = ()
while to_visit:
current_trackable = to_visit.popleft()
bfs_sorted.append(current_trackable)
for name, dependency in self.children(current_trackable).items():
if dependency not in node_paths:
node_paths[dependency] = (
node_paths[current_trackable] +
(base.TrackableReference(name, dependency),))
to_visit.append(dependency)
return bfs_sorted, node_paths
| TrackableView |
python | tensorflow__tensorflow | tensorflow/python/feature_column/sequence_feature_column.py | {
"start": 17307,
"end": 20567
} | class ____(
fc.SequenceDenseColumn,
collections.namedtuple(
'SequenceNumericColumn',
('key', 'shape', 'default_value', 'dtype', 'normalizer_fn'))):
"""Represents sequences of numeric data."""
@property
def _is_v2_column(self):
return True
@property
def name(self):
"""See `FeatureColumn` base class."""
return self.key
@property
def parse_example_spec(self):
"""See `FeatureColumn` base class."""
return {self.key: parsing_ops.VarLenFeature(self.dtype)}
def transform_feature(self, transformation_cache, state_manager):
"""See `FeatureColumn` base class.
In this case, we apply the `normalizer_fn` to the input tensor.
Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.
Returns:
Normalized input tensor.
"""
input_tensor = transformation_cache.get(self.key, state_manager)
if self.normalizer_fn is not None:
input_tensor = self.normalizer_fn(input_tensor)
return input_tensor
@property
def variable_shape(self):
"""Returns a `TensorShape` representing the shape of sequence input."""
return tensor_shape.TensorShape(self.shape)
def get_sequence_dense_tensor(self, transformation_cache, state_manager):
"""Returns a `TensorSequenceLengthPair`.
Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.
"""
sp_tensor = transformation_cache.get(self, state_manager)
dense_tensor = sparse_ops.sparse_tensor_to_dense(
sp_tensor, default_value=self.default_value)
# Reshape into [batch_size, T, variable_shape].
dense_shape = array_ops.concat(
[array_ops.shape(dense_tensor)[:1], [-1], self.variable_shape], axis=0)
dense_tensor = array_ops.reshape(dense_tensor, shape=dense_shape)
# Get the number of timesteps per example
# For the 2D case, the raw values are grouped according to num_elements;
# for the 3D case, the grouping happens in the third dimension, and
# sequence length is not affected.
if sp_tensor.shape.ndims == 2:
num_elements = self.variable_shape.num_elements()
else:
num_elements = 1
seq_length = fc_utils.sequence_length_from_sparse_tensor(
sp_tensor, num_elements=num_elements)
return fc.SequenceDenseColumn.TensorSequenceLengthPair(
dense_tensor=dense_tensor, sequence_length=seq_length)
@property
def parents(self):
"""See 'FeatureColumn` base class."""
return [self.key]
def get_config(self):
"""See 'FeatureColumn` base class."""
config = dict(zip(self._fields, self))
config['dtype'] = self.dtype.name
return config
@classmethod
def from_config(cls, config, custom_objects=None, columns_by_name=None):
"""See 'FeatureColumn` base class."""
fc._check_config_keys(config, cls._fields)
kwargs = fc._standardize_and_copy_config(config)
kwargs['dtype'] = dtypes.as_dtype(config['dtype'])
return cls(**kwargs)
# pylint: enable=protected-access
| SequenceNumericColumn |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 20067,
"end": 22136
} | class ____(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
router_probs (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary
loss and the z_loss for Mixture of Experts models.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
router_probs: Optional[tuple[torch.FloatTensor]] = None
router_logits: Optional[tuple[torch.FloatTensor]] = None
@dataclass
| MoEModelOutput |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 437502,
"end": 460912
} | class ____(FieldChannelMixin, core.PositionFieldDefBase):
r"""
Radius schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : bool, dict, Literal['binned'], :class:`BinParams`, None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
scale : dict, :class:`Scale`, None
An object defining properties of the channel's scale, which is the function that
transforms values in the data domain (numbers, dates, strings, etc) to visual values
(pixels, colors, sizes) of the encoding channels.
If ``null``, the scale will be `disabled and the data value will be directly encoded
<https://vega.github.io/vega-lite/docs/scale.html#disable>`__.
**Default value:** If undefined, default `scale properties
<https://vega.github.io/vega-lite/docs/scale.html>`__ are applied.
**See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__
documentation.
sort : dict, :class:`Sort`, Sequence[str], Sequence[bool], Sequence[float], :class:`SortArray`, :class:`SortOrder`, :class:`AllSortString`, :class:`SortByChannel`, :class:`SortByEncoding`, :class:`EncodingSortField`, :class:`SortByChannelDesc`, Sequence[dict, :class:`DateTime`], Literal['-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', '-fillOpacity', '-strokeOpacity', '-opacity', '-text', 'ascending', 'descending', 'x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', 'strokeOpacity', 'opacity', 'text'], None
Sort order for the encoded field.
For continuous fields (quantitative or temporal), ``sort`` can be either
``"ascending"`` or ``"descending"``.
For discrete fields, ``sort`` can be one of the following:
* ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in
JavaScript.
* `A string indicating an encoding channel name to sort by
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__ (e.g.,
``"x"`` or ``"y"``) with an optional minus prefix for descending sort (e.g.,
``"-x"`` to sort by x-field, descending). This channel string is short-form of `a
sort-by-encoding definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__. For
example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order":
"descending"}``.
* `A sort field definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-field>`__ for sorting by
another field.
* `An array specifying the field values in preferred order
<https://vega.github.io/vega-lite/docs/sort.html#sort-array>`__. In this case, the
sort order will obey the values in the array, followed by any unspecified values
in their original order. For discrete time field, values in the sort array can be
`date-time definition objects
<https://vega.github.io/vega-lite/docs/datetime.html>`__. In addition, for time
units ``"month"`` and ``"day"``, the values can be the month or day names (case
insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"``).
* ``null`` indicating no sort.
**Default value:** ``"ascending"``
**Note:** ``null`` and sorting by another channel is not supported for ``row`` and
``column``.
**See also:** `sort <https://vega.github.io/vega-lite/docs/sort.html>`__
documentation.
stack : bool, :class:`StackOffset`, Literal['zero', 'center', 'normalize'], None
Type of stacking offset if the field should be stacked. ``stack`` is only applicable
for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For
example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar
chart.
``stack`` can be one of the following values:
* ``"zero"`` or ``true``: stacking with baseline offset at zero value of the scale
(for creating typical stacked `bar
<https://vega.github.io/vega-lite/docs/stack.html#bar>`__ and `area
<https://vega.github.io/vega-lite/docs/stack.html#area>`__ chart).
* ``"normalize"`` - stacking with normalized domain (for creating `normalized
stacked bar and area charts
<https://vega.github.io/vega-lite/docs/stack.html#normalized>`__ and pie charts
`with percentage tooltip
<https://vega.github.io/vega-lite/docs/arc.html#tooltip>`__).
* ``"center"`` - stacking with center baseline (for `streamgraph
<https://vega.github.io/vega-lite/docs/stack.html#streamgraph>`__).
* ``null`` or ``false`` - No-stacking. This will produce layered `bar
<https://vega.github.io/vega-lite/docs/stack.html#layered-bar-chart>`__ and area
chart.
**Default value:** ``zero`` for plots with all of the following conditions are true:
(1) the mark is ``bar``, ``area``, or ``arc``; (2) the stacked measure channel (x or
y) has a linear scale; (3) At least one of non-position channels mapped to an
unaggregated field that is different from x and y. Otherwise, ``null`` by default.
**See also:** `stack <https://vega.github.io/vega-lite/docs/stack.html>`__
documentation.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "radius"
@overload
def aggregate(self, _: NonArgAggregateOp_T, /) -> Radius: ...
@overload
def aggregate(
self, *, argmax: Optional[str | SchemaBase] = Undefined
) -> Radius: ...
@overload
def aggregate(
self, *, argmin: Optional[str | SchemaBase] = Undefined
) -> Radius: ...
@overload
def bandPosition(self, _: float, /) -> Radius: ...
@overload
def bin(self, _: bool | Bin | Literal["binned"] | None, /) -> Radius: ...
@overload
def bin(
self,
*,
anchor: Optional[float] = Undefined,
base: Optional[float] = Undefined,
binned: Optional[bool] = Undefined,
divide: Optional[Sequence[float]] = Undefined,
extent: Optional[Parameter | SchemaBase | Sequence[float] | Map] = Undefined,
maxbins: Optional[float] = Undefined,
minstep: Optional[float] = Undefined,
nice: Optional[bool] = Undefined,
step: Optional[float] = Undefined,
steps: Optional[Sequence[float]] = Undefined,
) -> Radius: ...
@overload
def field(self, _: str | RepeatRef, /) -> Radius: ...
@overload
def field(
self,
*,
repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined,
) -> Radius: ...
@overload
def scale(self, _: Scale | None, /) -> Radius: ...
@overload
def scale(
self,
*,
align: Optional[float | Parameter | SchemaBase | Map] = Undefined,
base: Optional[float | Parameter | SchemaBase | Map] = Undefined,
bins: Optional[SchemaBase | Sequence[float] | Map] = Undefined,
clamp: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
constant: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domain: Optional[
Parameter
| SchemaBase
| Literal["unaggregated"]
| Sequence[
str | bool | float | Temporal | Parameter | SchemaBase | Map | None
]
| Map
] = Undefined,
domainMax: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainMid: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domainMin: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainRaw: Optional[Parameter | SchemaBase | Map] = Undefined,
exponent: Optional[float | Parameter | SchemaBase | Map] = Undefined,
interpolate: Optional[
Parameter | SchemaBase | Map | ScaleInterpolateEnum_T
] = Undefined,
nice: Optional[
bool | float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingInner: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingOuter: Optional[float | Parameter | SchemaBase | Map] = Undefined,
range: Optional[
SchemaBase
| Sequence[str | float | Parameter | SchemaBase | Sequence[float] | Map]
| Map
| RangeEnum_T
] = Undefined,
rangeMax: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
rangeMin: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
reverse: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
round: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
scheme: Optional[Parameter | SchemaBase | Map | ColorScheme_T] = Undefined,
type: Optional[SchemaBase | ScaleType_T] = Undefined,
zero: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
) -> Radius: ...
@overload
def sort(
self,
_: Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[DateTime | Temporal]
| AllSortString_T
| None,
/,
) -> Radius: ...
@overload
def sort(
self,
*,
field: Optional[str | SchemaBase | Map] = Undefined,
op: Optional[SchemaBase | NonArgAggregateOp_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> Radius: ...
@overload
def sort(
self,
*,
encoding: Optional[SchemaBase | SortByChannel_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> Radius: ...
@overload
def stack(self, _: bool | StackOffset_T | None, /) -> Radius: ...
@overload
def timeUnit(
self,
_: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T,
/,
) -> Radius: ...
@overload
def timeUnit(
self,
*,
binned: Optional[bool] = Undefined,
maxbins: Optional[float] = Undefined,
step: Optional[float] = Undefined,
unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined,
utc: Optional[bool] = Undefined,
) -> Radius: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> Radius: ...
@overload
def type(self, _: StandardType_T, /) -> Radius: ...
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[bool | SchemaBase | Literal["binned"] | Map | None] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
scale: Optional[SchemaBase | Map | None] = Undefined,
sort: Optional[
SchemaBase
| Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[Temporal | SchemaBase | Map]
| Map
| AllSortString_T
| None
] = Undefined,
stack: Optional[bool | SchemaBase | StackOffset_T | None] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | StandardType_T] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
field=field,
scale=scale,
sort=sort,
stack=stack,
timeUnit=timeUnit,
title=title,
type=type,
**kwds,
)
@with_property_setters
| Radius |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 246989,
"end": 248727
} | class ____(SliceNode):
# start:stop:step in subscript list
# This is just a node to hold start,stop and step nodes that can be
# converted to integers. This does not generate a slice python object.
#
# start ExprNode
# stop ExprNode
# step ExprNode
is_temp = 0
def calculate_constant_result(self):
self.constant_result = slice(
self.start.constant_result,
self.stop.constant_result,
self.step.constant_result)
def compile_time_value(self, denv):
start = self.start.compile_time_value(denv)
stop = self.stop.compile_time_value(denv)
step = self.step.compile_time_value(denv)
try:
return slice(start, stop, step)
except Exception as e:
self.compile_time_value_error(e)
def may_be_none(self):
return False
def analyse_types(self, env):
self.start = self.start.analyse_types(env)
self.stop = self.stop.analyse_types(env)
self.step = self.step.analyse_types(env)
if not self.start.is_none:
self.start = self.start.coerce_to_index(env)
if not self.stop.is_none:
self.stop = self.stop.coerce_to_index(env)
if not self.step.is_none:
self.step = self.step.coerce_to_index(env)
if self.start.is_literal and self.stop.is_literal and self.step.is_literal:
self.is_literal = True
self.is_temp = False
return self
def calculate_result_code(self):
pass
def generate_result_code(self, code):
for a in self.start,self.stop,self.step:
if isinstance(a, CloneNode):
a.arg.result()
| SliceIntNode |
python | realpython__materials | python-unittest/test_vehicles.py | {
"start": 35,
"end": 694
} | class ____(unittest.TestCase):
def test_vehicle_is_instance_of_car(self):
car = vehicles.Car("Chevrolet", "Corvette", 194)
self.assertIsInstance(car, vehicles.Car)
def test_vehicle_is_instance_of_truck(self):
truck = vehicles.Truck("Ford", "F-150", 2000)
self.assertIsInstance(truck, vehicles.Truck)
def test_vehicles_factory(self):
car = vehicles.vehicle_factory(
vehicles.Car,
make="Toyota",
model="Corolla",
max_speed=180,
)
self.assertIsInstance(car, vehicles.Vehicle)
if __name__ == "__main__":
unittest.main(verbosity=2)
| TestVehicles |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/layout_propagation_test.py | {
"start": 1671,
"end": 15048
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super(LayoutPropagationV2Test, self).setUp()
global_ids = test_util.create_device_ids_array((1, 2))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = { # pylint: disable=g-complex-comprehension
device: layout.Mesh(
[_MESH_DIM_X, _MESH_DIM_Y],
global_ids,
local_ids,
test_util.create_device_list((1, 2), device),
)
for device in ('CPU', 'GPU', 'TPU')
}
self.mesh = self.configTestMesh(mesh_dict)
# 1D Layouts
self.unsharded_layout = layout.Layout.replicated(self.mesh, rank=1)
self.x_layout = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=1)
self.y_layout = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_Y, rank=1)
# 2D Layouts
self.unsharded_unsharded_layout = layout.Layout.replicated(
self.mesh, rank=2
)
self.x_unsharded_layout = layout.Layout.batch_sharded(
self.mesh, _MESH_DIM_X, rank=2
)
self.unsharded_x_layout = layout.Layout.inner_sharded(
self.mesh, _MESH_DIM_X, rank=2
)
self.unsharded_y_layout = layout.Layout.inner_sharded(
self.mesh, _MESH_DIM_Y, rank=2
)
def test_layout_prop_v2_with_const_tf_function(self):
a = constant_op.constant([[1.0, 2.0], [3.0, 4.0]])
b = constant_op.constant([[10.0, 20.0], [30.0, 40.0]])
golden_result = math_ops.add(a, b)
c = api.copy_to_mesh(a, self.unsharded_unsharded_layout)
@polymorphic_function.function
def add_function():
d = constant_op.constant([[10.0, 20.0], [30.0, 40.0]])
return math_ops.add(c, d)
dtensor_result = add_function()
self.assertDTensorEqual(golden_result, self.unsharded_unsharded_layout,
dtensor_result)
def test_layout_prop_v2_while(self):
a = constant_op.constant([0, 1, 2, 1], dtype=dtypes.float32)
num_iterations = 10
@polymorphic_function.function
def function_with_while(t):
for _ in math_ops.range(num_iterations):
random_number = stateless_random_ops.stateless_random_normal(
shape=[4], seed=[1, 2], dtype=dtypes.float32
)
t = t + random_number
return t
golden_result = function_with_while(a)
a = numpy_util.pack_numpy(a, self.unsharded_layout)
dtensor_result = function_with_while(a)
self.assertDTensorEqual(golden_result, self.unsharded_layout,
dtensor_result)
@parameterized.named_parameters(
dict(testcase_name='unsharded', sharded_layout=0, use_split=False),
dict(testcase_name='x_sharded', sharded_layout=1, use_split=False),
dict(testcase_name='unsharded_split', sharded_layout=0, use_split=True),
dict(testcase_name='x_sharded_split', sharded_layout=1, use_split=True))
def test_while_microbatch(self, sharded_layout, use_split):
layouts = [self.unsharded_unsharded_layout, self.x_unsharded_layout]
sharded_layout = layouts[sharded_layout]
np.random.seed(0)
random_initial_value = np.random.uniform(size=4 * 4).reshape([4, 4])
if use_split:
random_batch = np.random.uniform(size=12 * 4).reshape([12, 4])
else:
random_batch = np.random.uniform(size=4 * 4).reshape([4, 4])
golden_variable = variables.Variable(random_initial_value)
@polymorphic_function.function
def update_weights(batch, variable):
accum_grads = array_ops.zeros_like_v2(variable)
for i in math_ops.range(3):
if use_split:
reshaped = array_ops.reshape(batch, [4, 3, 4])
mini_batch = array_ops.gather_v2(reshaped, i, axis=1)
else:
mini_batch = batch
with backprop.GradientTape() as tape:
logits = variable * variable + mini_batch
loss = math_ops.reduce_sum(logits * logits)
accum_grads += tape.gradient(loss, variable)
new_variable = variable + accum_grads
variable.assign(new_variable)
return accum_grads
golden_accum = update_weights(
constant_op.constant(random_batch), golden_variable
)
random_batch = numpy_util.pack_numpy(random_batch, sharded_layout)
random_initial_value = numpy_util.pack_numpy(random_initial_value,
sharded_layout)
dtensor_variable = d_variable.DVariable(random_initial_value)
dtensor_accum = update_weights(random_batch, dtensor_variable)
self.assertDTensorEqual(golden_accum, sharded_layout, dtensor_accum)
@parameterized.named_parameters(
dict(testcase_name='unsharded_split', sharded_layout=0),
dict(testcase_name='x_sharded_split', sharded_layout=1))
def test_while_microbatch_with_reused_gradient_accumulator(
self, sharded_layout):
layouts = [
self.unsharded_unsharded_layout, self.x_unsharded_layout,
self.unsharded_x_layout
]
sharded_layout_0 = layouts[sharded_layout]
sharded_layout_1 = layouts[2]
np.random.seed(0)
random_initial_value_1 = np.random.uniform(size=4 * 4).reshape(
[4, 4]).astype(np.float32)
random_initial_value_2 = np.random.uniform(size=4 * 4).reshape(
[4, 4]).astype(np.float32)
random_batch = np.random.uniform(size=12 * 4).reshape([12, 4
]).astype(np.float32)
golden_variable_1 = variables.Variable(random_initial_value_1)
golden_variable_2 = variables.Variable(random_initial_value_2)
@polymorphic_function.function
def update_weights(batch, variable1, variable2):
accum_grads = array_ops.zeros_like_v2(variable1)
accum_grads_2 = array_ops.zeros_like_v2(variable2)
for i in math_ops.range(3):
reshaped = array_ops.reshape(batch, [4, 3, 4])
mini_batch = array_ops.gather_v2(reshaped, i, axis=1)
with backprop.GradientTape() as tape:
logits_1 = variable1 * variable1 + mini_batch
logits_2 = variable2 * variable2 + mini_batch
loss_1 = math_ops.reduce_sum(logits_1 * logits_1)
loss_2 = math_ops.reduce_sum(logits_2 * logits_2)
loss = loss_1 + loss_2
grads = tape.gradient(loss, [variable1, variable2])
accum_grads += grads[0]
accum_grads_2 += grads[1]
new_variable = variable1 + accum_grads
new_variable_2 = variable2 + accum_grads_2
variable1.assign(new_variable)
variable2.assign(new_variable_2)
return accum_grads, accum_grads_2
golden_accum, golden_accum_2 = update_weights(
constant_op.constant(random_batch), golden_variable_1, golden_variable_2
)
random_batch = numpy_util.pack_numpy(random_batch, sharded_layout_0)
random_initial_value_1 = numpy_util.pack_numpy(random_initial_value_1,
sharded_layout_0)
dtensor_variable_1 = d_variable.DVariable(random_initial_value_1)
random_initial_value_2 = numpy_util.pack_numpy(random_initial_value_2,
sharded_layout_1)
dtensor_variable_2 = d_variable.DVariable(random_initial_value_2)
dtensor_accum, dtensor_accum_2 = update_weights(random_batch,
dtensor_variable_1,
dtensor_variable_2)
self.assertDTensorEqual(golden_accum, sharded_layout_0, dtensor_accum)
self.assertDTensorEqual(golden_accum_2, sharded_layout_1, dtensor_accum_2)
def test_layout_like(self):
a = constant_op.constant([1, 2, 3, 4], dtype=dtypes.float32)
a = numpy_util.pack_numpy(a, self.unsharded_layout)
b = constant_op.constant([0, 1, 2, 3], dtype=dtypes.int64)
b = numpy_util.pack_numpy(b, self.x_layout)
@polymorphic_function.function
def layout_like_function(i, t):
i = math_ops.sqrt(i)
return api.relayout_like(i, t)
# Triggers relayout_like with different dtype.
dtensor_result = layout_like_function(a, b)
api.check_layout(dtensor_result, self.x_layout)
def test_layout_prop_v2_if(self):
a = constant_op.constant([0, 1, 2, 1], dtype=dtypes.float32)
a = numpy_util.pack_numpy(a, self.unsharded_layout)
@polymorphic_function.function
def function_with_if(t):
if math_ops.equal(math_ops.reduce_sum(t), 0):
t = math_ops.sqrt(t)
return api.relayout(t, self.x_layout)
else:
return array_ops.zeros_like_v2(t)
dtensor_result = function_with_if(a)
api.check_layout(dtensor_result, self.x_layout)
def test_layout_prop_v2_if_with_different_layouts_for_branches(self):
unsharded_unsharded = layout.Layout.replicated(self.mesh, rank=2)
unsharded_y = layout.Layout.inner_sharded(self.mesh, _MESH_DIM_Y, rank=2)
x_unsharded = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=2)
a = np.random.uniform(size=16).reshape([4, 4])
a = numpy_util.pack_numpy(a, unsharded_unsharded)
@polymorphic_function.function
def function_with_if(t):
if math_ops.equal(math_ops.reduce_sum(t), 0):
t = math_ops.sqrt(t)
return api.relayout(t, unsharded_y)
else:
t = array_ops.zeros_like_v2(a)
return api.relayout(t, x_unsharded)
dtensor_result = function_with_if(a)
x_y_sharded = layout.Layout([_MESH_DIM_X, _MESH_DIM_Y], self.mesh)
api.check_layout(dtensor_result, x_y_sharded)
def test_partial_relayout_in_function(self):
sharded_layout = layout.Layout([_MESH_DIM_X, _MESH_DIM_Y], self.mesh)
a = np.random.uniform(size=16).reshape([4, 4])
a = numpy_util.pack_numpy(a, sharded_layout)
replicated_layout = layout.Layout(
[layout.MATCH, layout.UNSHARDED], mesh=self.mesh
)
@polymorphic_function.function
def func_with_relayout(t):
out = math_ops.cast(t, dtypes.float32)
out = math_ops.sqrt(out)
return api.relayout(out, replicated_layout)
out = func_with_relayout(a)
expected_layout = layout.Layout([_MESH_DIM_X, layout.UNSHARDED], self.mesh)
api.check_layout(out, expected_layout)
def test_partial_relayout_in_eager(self):
sharded_layout = layout.Layout([_MESH_DIM_X, _MESH_DIM_Y], self.mesh)
a = np.random.uniform(size=16).reshape([4, 4])
a = numpy_util.pack_numpy(a, sharded_layout)
replicated_layout = layout.Layout(
[layout.MATCH, layout.UNSHARDED], mesh=self.mesh
)
a = math_ops.cast(a, dtypes.float32)
a = math_ops.sqrt(a)
out = api.relayout(a, replicated_layout)
expected_layout = layout.Layout([_MESH_DIM_X, layout.UNSHARDED], self.mesh)
api.check_layout(out, expected_layout)
@parameterized.named_parameters(
dict(testcase_name='unsharded_unsharded', sharded_layout=0),
dict(testcase_name='x_unsharded', sharded_layout=1),
dict(testcase_name='unsharded_y', sharded_layout=2),
)
def test_relayout_equivalent_layouts(self, sharded_layout):
layouts = [
self.unsharded_unsharded_layout, self.x_unsharded_layout,
self.unsharded_y_layout]
expected_layout = layouts[sharded_layout]
inputs = constant_op.constant([[0, 1], [2, 1]], dtype=dtypes.float32)
sharded_layout = layout.Layout([_MESH_DIM_X, _MESH_DIM_Y], self.mesh)
inputs = numpy_util.pack_numpy(inputs, sharded_layout)
output = api.relayout(inputs, expected_layout)
api.check_layout(output, expected_layout)
def test_strided_slice_grad(self):
np.random.seed(0)
random_initial_value = np.random.uniform(size=4).reshape([4])
random_initial_value = numpy_util.pack_numpy(random_initial_value,
self.unsharded_layout)
@polymorphic_function.function
def fn_with_strided_slice(t):
a = array_ops.strided_slice(t, [1], [2], shrink_axis_mask=1)
return math_ops.sqrt(a)
random_variable = d_variable.DVariable(random_initial_value)
with backprop.GradientTape() as tape:
output = fn_with_strided_slice(random_variable)
grads = tape.gradient(output, [random_variable])
self.assertTrue(api.fetch_layout(grads[0]).is_fully_replicated())
def test_layout_prop_v2_infinite_loop(self):
x_unsharded = layout.Layout([_MESH_DIM_X, layout.UNSHARDED], self.mesh)
unsharded_x = layout.Layout([layout.UNSHARDED, _MESH_DIM_X], self.mesh)
@polymorphic_function.function
def func(input_a, input_b):
out = array_ops.identity(
math_ops.matmul(input_a, array_ops.identity(input_b))
)
return api.relayout(out, unsharded_x)
result = func(
api.call_with_layout(
array_ops.ones, shape=(16, 16), layout=x_unsharded
),
api.call_with_layout(
array_ops.ones, shape=(16, 16), layout=unsharded_x
),
)
api.check_layout(result, unsharded_x)
def test_layout_prop_parted_layout(self):
value = np.array([1.0, 2.0, 3.0, 4.0])
expected = nn_ops.softmax_v2(gen_nn_ops.relu(value))
@polymorphic_function.function
def func(value):
return nn_ops.softmax_v2(gen_nn_ops.relu(value))
parted_layout = self.x_layout.to_parted()
result = func(api.relayout(value, parted_layout))
# Verifies the parted layout can be propagated through a chain of ops to the
# final output.
self.assertDTensorEqual(expected, parted_layout, result)
if __name__ == '__main__':
test.main()
| LayoutPropagationV2Test |
python | huggingface__transformers | src/transformers/models/llama4/modeling_llama4.py | {
"start": 49047,
"end": 60149
} | class ____(Llama4PreTrainedModel, GenerationMixin):
_no_split_modules = ["Llama4TextDecoderLayer", "Llama4VisionEncoderLayer"]
_tp_plan = {}
base_model_prefix = "model"
config: Llama4Config
def __init__(self, config: Llama4Config):
super().__init__(config)
self.vision_model = Llama4VisionModel(config.vision_config)
self.multi_modal_projector = Llama4MultiModalProjector(config)
self.language_model = Llama4ForCausalLM(config.text_config)
self.vocab_size = config.text_config.vocab_size
self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
self.post_init()
def get_input_embeddings(self):
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.set_input_embeddings(value)
def get_output_embeddings(self):
return self.language_model.get_output_embeddings()
def set_output_embeddings(self, new_embeddings):
self.language_model.set_output_embeddings(new_embeddings)
def set_decoder(self, decoder):
self.language_model.set_decoder(decoder)
def get_decoder(self):
return self.language_model.get_decoder()
def get_image_features(
self,
pixel_values: torch.FloatTensor,
vision_feature_select_strategy: str,
**kwargs,
):
"""
Obtains image last hidden states from the vision tower and apply al projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
The tensors corresponding to the input images.
vision_feature_select_strategy (`str`):
The feature selection strategy used to select the vision feature from the vision backbone.
Can be one of `"default"` or `"full"`
Returns:
image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
"""
if vision_feature_select_strategy not in ["default", "full"]:
raise ValueError(f"Unexpected select feature strategy: {self.vision_feature_select_strategy}")
kwargs = {k: v for k, v in kwargs.items() if v is not None}
image_outputs = self.vision_model(pixel_values, output_hidden_states=False, **kwargs)
hidden_state = image_outputs.last_hidden_state
return hidden_state
def get_placeholder_mask(
self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
):
"""
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
"""
if input_ids is None:
special_image_mask = inputs_embeds == self.get_input_embeddings()(
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
)
special_image_mask = special_image_mask.all(-1)
else:
special_image_mask = input_ids == self.config.image_token_id
n_image_tokens = special_image_mask.sum()
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
if inputs_embeds[special_image_mask].numel() != image_features.numel():
raise ValueError(
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
)
return special_image_mask
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
vision_feature_select_strategy: Optional[str] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, Llama4CausalLMOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_config.vision_feature_select_strategy
)
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if pixel_values is not None and inputs_embeds is not None:
raise ValueError(
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
)
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
if pixel_values is not None:
image_features = self.get_image_features(
pixel_values=pixel_values,
vision_feature_select_strategy=vision_feature_select_strategy,
)
vision_flat = image_features.view(-1, image_features.size(-1))
projected_vision_flat = self.multi_modal_projector(vision_flat).to(
inputs_embeds.device, inputs_embeds.dtype
)
special_image_mask = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, image_features=projected_vision_flat
)
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, projected_vision_flat)
outputs = self.language_model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
logits_to_keep=logits_to_keep,
**kwargs,
)
logits = outputs[0]
loss = None
if labels is not None:
# Shift so that tokens < n predict n
if attention_mask is not None:
# we use the input attention mask to shift the logits and labels, because it is 2D.
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
else:
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
)
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return Llama4CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
image_hidden_states=image_features if pixel_values is not None else None,
)
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
inputs_embeds=None,
pixel_values=None,
attention_mask=None,
cache_position=None,
logits_to_keep=None,
**kwargs,
):
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
model_inputs = self.language_model.prepare_inputs_for_generation(
input_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
logits_to_keep=logits_to_keep,
**kwargs,
)
if cache_position[0] == 0:
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
# Otherwise we need pixel values to be passed to model
model_inputs["pixel_values"] = pixel_values
return model_inputs
__all__ = [
"Llama4PreTrainedModel",
"Llama4TextModel",
"Llama4VisionModel",
"Llama4ForCausalLM",
"Llama4ForConditionalGeneration",
]
| Llama4ForConditionalGeneration |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 5895,
"end": 7190
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
`MoshiForConditionalGeneration` outputs.
"""
)
| MoshiCausalLMOutputWithPast |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/lookup_ops.py | {
"start": 2674,
"end": 10270
} | class ____(lookup_ops.TableInitializerBase):
"""Creates a table initializer from a `tf.data.Dataset`.
Sample usage:
>>> keys = tf.data.Dataset.range(100)
>>> values = tf.data.Dataset.range(100).map(
... lambda x: tf.strings.as_string(x * 2))
>>> ds = tf.data.Dataset.zip((keys, values))
>>> init = tf.data.experimental.DatasetInitializer(ds)
>>> table = tf.lookup.StaticHashTable(init, "")
>>> table.lookup(tf.constant([0, 1, 2], dtype=tf.int64)).numpy()
array([b'0', b'2', b'4'], dtype=object)
Attributes:
dataset: A `tf.data.Dataset` object that produces tuples of scalars. The
first scalar is treated as a key and the second as value.
Raises: ValueError if `dataset` doesn't conform to specifications.
"""
def __init__(self, dataset):
"""Creates a table initializer from a `tf.data.Dataset`.
Args:
dataset: A `tf.data.Dataset` object that produces tuples of scalars. The
first scalar is treated as a key and the second as value.
Raises: ValueError if `dataset` doesn't conform to specifications.
Returns: A `DatasetInitializer` object
"""
# Assert that the dataset element spec is a tuple of TensorSpecs where
# each tensor is a scalar.
self.dataset = dataset
elem_spec = self.dataset.element_spec
_check_table_initializer_element_spec(elem_spec)
key_type = elem_spec[0].dtype
value_type = elem_spec[1].dtype
super(DatasetInitializer, self).__init__(key_type, value_type)
def initialize(self, table):
lookup_ops.check_table_dtypes(table, self._key_dtype, self._value_dtype)
init_op = ged_ops.initialize_table_from_dataset(
table.resource_handle, self.dataset._variant_tensor) # pylint: disable=protected-access
ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op)
return init_op
@tf_export("data.experimental.table_from_dataset")
def table_from_dataset(dataset=None,
num_oov_buckets=0,
vocab_size=None,
default_value=None,
hasher_spec=lookup_ops.FastHashSpec,
key_dtype=dtypes.string,
name=None):
"""Returns a lookup table based on the given dataset.
This operation constructs a lookup table based on the given dataset of pairs
of (key, value).
Any lookup of an out-of-vocabulary token will return a bucket ID based on its
hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the
`default_value`.
The bucket ID range is
`[vocabulary size, vocabulary size + num_oov_buckets - 1]`.
Sample Usages:
>>> keys = tf.data.Dataset.range(100)
>>> values = tf.data.Dataset.range(100).map(
... lambda x: tf.strings.as_string(x * 2))
>>> ds = tf.data.Dataset.zip((keys, values))
>>> table = tf.data.experimental.table_from_dataset(
... ds, default_value='n/a', key_dtype=tf.int64)
>>> table.lookup(tf.constant([0, 1, 2], dtype=tf.int64)).numpy()
array([b'0', b'2', b'4'], dtype=object)
Args:
dataset: A dataset containing (key, value) pairs.
num_oov_buckets: The number of out-of-vocabulary buckets.
vocab_size: Number of the elements in the vocabulary, if known.
default_value: The value to use for out-of-vocabulary feature values.
Defaults to -1.
hasher_spec: A `HasherSpec` to specify the hash function to use for
assignation of out-of-vocabulary buckets.
key_dtype: The `key` data type.
name: A name for this op (optional).
Returns:
The lookup table based on the given dataset.
Raises:
ValueError: If
* `dataset` does not contain pairs
* The 2nd item in the `dataset` pairs has a dtype which is incompatible
with `default_value`
* `num_oov_buckets` is negative
* `vocab_size` is not greater than zero
* The `key_dtype` is not integer or string
"""
elem_spec = dataset.element_spec
_check_table_initializer_element_spec(elem_spec)
if default_value is None:
default_value = -1
if not (elem_spec[1].dtype.is_integer or elem_spec[1].dtype.is_floating):
raise ValueError("`default_value` must be specified when creating a "
"table from a dataset that produces values of type "
f"{elem_spec[1].dtype}.")
if num_oov_buckets < 0:
raise ValueError("`num_oov_buckets` must be greater than or equal to 0, "
f"got {num_oov_buckets}.")
if (not isinstance(vocab_size, tensor.Tensor) and vocab_size is not None and
vocab_size < 1):
raise ValueError(f"`vocab_size` must be greater than 0, got {vocab_size}.")
if (not key_dtype.is_integer) and (dtypes.string != key_dtype.base_dtype):
raise TypeError("`key_dtype` must be either an integer or string type, "
f"but got {key_dtype}")
if vocab_size is not None:
if isinstance(vocab_size, tensor.Tensor):
vocab_size = math_ops.cast(vocab_size, dtypes.int64)
dataset = dataset.take(vocab_size)
dataset = dataset.apply(assert_cardinality(vocab_size))
with ops.name_scope(name, "string_to_index"):
initializer = DatasetInitializer(dataset)
with ops.name_scope(None, "hash_table"):
table = lookup_ops.StaticHashTableV1(initializer, default_value)
if num_oov_buckets:
table = lookup_ops.IdTableWithHashBuckets(
table,
num_oov_buckets=num_oov_buckets,
hasher_spec=hasher_spec,
key_dtype=key_dtype)
return table
@tf_export("data.experimental.index_table_from_dataset")
def index_table_from_dataset(dataset=None,
num_oov_buckets=0,
vocab_size=None,
default_value=-1,
hasher_spec=lookup_ops.FastHashSpec,
key_dtype=dtypes.string,
name=None):
"""Returns an index lookup table based on the given dataset.
This operation constructs a lookup table based on the given dataset of keys.
Any lookup of an out-of-vocabulary token will return a bucket ID based on its
hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the
`default_value`.
The bucket ID range is
`[vocabulary size, vocabulary size + num_oov_buckets - 1]`.
Sample Usages:
>>> ds = tf.data.Dataset.range(100).map(lambda x: tf.strings.as_string(x * 2))
>>> table = tf.data.experimental.index_table_from_dataset(
... ds, key_dtype=dtypes.int64)
>>> table.lookup(tf.constant(['0', '2', '4'], dtype=tf.string)).numpy()
array([0, 1, 2])
Args:
dataset: A dataset of keys.
num_oov_buckets: The number of out-of-vocabulary buckets.
vocab_size: Number of the elements in the vocabulary, if known.
default_value: The value to use for out-of-vocabulary feature values.
Defaults to -1.
hasher_spec: A `HasherSpec` to specify the hash function to use for
assignation of out-of-vocabulary buckets.
key_dtype: The `key` data type.
name: A name for this op (optional).
Returns:
The lookup table based on the given dataset.
Raises:
ValueError: If
* `num_oov_buckets` is negative
* `vocab_size` is not greater than zero
* The `key_dtype` is not integer or string
"""
return table_from_dataset(dataset.enumerate().map(lambda v, k: (k, v)),
num_oov_buckets, vocab_size, default_value,
hasher_spec, key_dtype, name)
| DatasetInitializer |
python | jazzband__django-simple-history | simple_history/tests/tests/test_utils.py | {
"start": 3629,
"end": 11250
} | class ____(TestCase):
def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Poll(id=4, question="Question 4", pub_date=timezone.now()),
Poll(id=5, question="Question 5", pub_date=timezone.now()),
]
self.data_with_excluded_fields = [
PollWithExcludeFields(id=1, question="Question 1", pub_date=timezone.now()),
PollWithExcludeFields(id=2, question="Question 2", pub_date=timezone.now()),
PollWithExcludeFields(id=3, question="Question 3", pub_date=timezone.now()),
PollWithExcludeFields(id=4, question="Question 4", pub_date=timezone.now()),
PollWithExcludeFields(id=5, question="Question 5", pub_date=timezone.now()),
]
self.data_with_alternative_manager = [
PollWithAlternativeManager(
id=1, question="Question 1", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=2, question="Question 2", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=3, question="Question 3", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=4, question="Question 4", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=5, question="Question 5", pub_date=timezone.now()
),
]
self.data_with_duplicates = [
PollWithUniqueQuestion(
pk=1, question="Question 1", pub_date=timezone.now()
),
PollWithUniqueQuestion(
pk=2, question="Question 2", pub_date=timezone.now()
),
PollWithUniqueQuestion(
pk=3, question="Question 1", pub_date=timezone.now()
),
]
def test_bulk_create_history(self):
bulk_create_with_history(self.data, Poll)
self.assertEqual(Poll.objects.count(), 5)
self.assertEqual(Poll.history.count(), 5)
@override_settings(SIMPLE_HISTORY_ENABLED=False)
def test_bulk_create_history_with_disabled_setting(self):
bulk_create_with_history(self.data, Poll)
self.assertEqual(Poll.objects.count(), 5)
self.assertEqual(Poll.history.count(), 0)
def test_bulk_create_history_alternative_manager(self):
bulk_create_with_history(
self.data,
PollWithAlternativeManager,
)
self.assertEqual(PollWithAlternativeManager.all_objects.count(), 5)
self.assertEqual(PollWithAlternativeManager.history.count(), 5)
def test_bulk_create_history_with_default_user(self):
user = User.objects.create_user("tester", "tester@example.com")
bulk_create_with_history(self.data, Poll, default_user=user)
self.assertTrue(
all([history.history_user == user for history in Poll.history.all()])
)
def test_bulk_create_history_with_default_change_reason(self):
bulk_create_with_history(
self.data, Poll, default_change_reason="my change reason"
)
self.assertTrue(
all(
[
history.history_change_reason == "my change reason"
for history in Poll.history.all()
]
)
)
def test_bulk_create_history_with_default_date(self):
date = datetime(2020, 7, 1)
bulk_create_with_history(self.data, Poll, default_date=date)
self.assertTrue(
all([history.history_date == date for history in Poll.history.all()])
)
def test_bulk_create_history_num_queries_is_two(self):
with self.assertNumQueries(2):
bulk_create_with_history(self.data, Poll)
def test_bulk_create_history_on_model_without_history_raises_error(self):
self.data = [
Place(id=1, name="Place 1"),
Place(id=2, name="Place 2"),
Place(id=3, name="Place 3"),
]
with self.assertRaises(NotHistoricalModelError):
bulk_create_with_history(self.data, Place)
def test_num_queries_when_batch_size_is_less_than_total(self):
with self.assertNumQueries(6):
bulk_create_with_history(self.data, Poll, batch_size=2)
def test_bulk_create_history_with_batch_size(self):
bulk_create_with_history(self.data, Poll, batch_size=2)
self.assertEqual(Poll.objects.count(), 5)
self.assertEqual(Poll.history.count(), 5)
def test_bulk_create_works_with_excluded_fields(self):
bulk_create_with_history(self.data_with_excluded_fields, PollWithExcludeFields)
self.assertEqual(Poll.objects.count(), 0)
self.assertEqual(Poll.history.count(), 0)
self.assertEqual(PollWithExcludeFields.objects.count(), 5)
self.assertEqual(PollWithExcludeFields.history.count(), 5)
def test_bulk_create_history_with_relation_name(self):
self.data = [
Street(name="Street 1"),
Street(name="Street 2"),
Street(name="Street 3"),
Street(name="Street 4"),
]
bulk_create_with_history(self.data, Street)
self.assertEqual(Street.objects.count(), 4)
self.assertEqual(Street.log.count(), 4)
def test_bulk_create_history_with_duplicates(self):
with transaction.atomic(), self.assertRaises(IntegrityError):
bulk_create_with_history(
self.data_with_duplicates,
PollWithUniqueQuestion,
ignore_conflicts=False,
)
self.assertEqual(PollWithUniqueQuestion.objects.count(), 0)
self.assertEqual(PollWithUniqueQuestion.history.count(), 0)
def test_bulk_create_history_with_duplicates_ignore_conflicts(self):
bulk_create_with_history(
self.data_with_duplicates, PollWithUniqueQuestion, ignore_conflicts=True
)
self.assertEqual(PollWithUniqueQuestion.objects.count(), 2)
self.assertEqual(PollWithUniqueQuestion.history.count(), 2)
def test_bulk_create_history_with_no_ids_return(self):
pub_date = timezone.now()
objects = [
Poll(question="Question 1", pub_date=pub_date),
Poll(question="Question 2", pub_date=pub_date),
Poll(question="Question 3", pub_date=pub_date),
Poll(question="Question 4", pub_date=pub_date),
Poll(question="Question 5", pub_date=pub_date),
]
_bulk_create = Poll._default_manager.bulk_create
def mock_bulk_create(*args, **kwargs):
_bulk_create(*args, **kwargs)
return [
Poll(question="Question 1", pub_date=pub_date),
Poll(question="Question 2", pub_date=pub_date),
Poll(question="Question 3", pub_date=pub_date),
Poll(question="Question 4", pub_date=pub_date),
Poll(question="Question 5", pub_date=pub_date),
]
with patch.object(
Poll._default_manager, "bulk_create", side_effect=mock_bulk_create
):
with self.assertNumQueries(3):
result = bulk_create_with_history(objects, Poll)
self.assertEqual(
[poll.question for poll in result], [poll.question for poll in objects]
)
self.assertNotEqual(result[0].id, None)
| BulkCreateWithHistoryTestCase |
python | getsentry__sentry | tests/sentry/notifications/utils/test_participants.py | {
"start": 8512,
"end": 22512
} | class ____(_ParticipantsTest):
def get_send_to_owners(self, event: Event) -> Mapping[ExternalProviders, set[Actor]]:
return get_send_to(
self.project,
target_type=ActionTargetType.ISSUE_OWNERS,
target_identifier=None,
event=event,
)
def store_event_owners(self, filename: str) -> Event:
return super().store_event(data=make_event_data(filename), project_id=self.project.id)
def setUp(self) -> None:
self.user2 = self.create_user(email="baz@example.com", is_active=True)
self.user3 = self.create_user(email="bar@example.com", is_active=True)
self.user_suspect_committer = self.create_user(
email="suspectcommitter@example.com", is_active=True
)
self.team2 = self.create_team(
organization=self.organization, members=[self.user, self.user2]
)
self.team_suspect_committer = self.create_team(
organization=self.organization, members=[self.user_suspect_committer]
)
self.project.add_team(self.team2)
self.project.add_team(self.team_suspect_committer)
self.repo = Repository.objects.create(
organization_id=self.organization.id, name=self.organization.id
)
user_ids = list(self.project.member_set.values_list("user_id", flat=True))
with assume_test_silo_mode(SiloMode.CONTROL):
users = [Owner("user", user.email) for user in User.objects.filter(id__in=user_ids)]
ProjectOwnership.objects.create(
project_id=self.project.id,
schema=dump_schema(
[
grammar.Rule(Matcher("path", "*.py"), [Owner("team", self.team2.slug)]),
grammar.Rule(Matcher("path", "*.jsx"), [Owner("user", self.user.email)]),
grammar.Rule(Matcher("path", "*.jx"), [Owner("user", self.user3.email)]),
grammar.Rule(Matcher("path", "*.java"), [Owner("user", self.user.email)]),
grammar.Rule(
Matcher("path", "*.cbl"),
users,
),
grammar.Rule(Matcher("path", "*.lol"), []),
]
),
fallthrough=True,
)
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration.add_organization(self.project.organization, self.user)
def create_sample_commit(self, user: User) -> Commit:
return self.create_commit(
project=self.project,
repo=self.repo,
author=self.create_commit_author(project=self.project, user=user),
key="a" * 40,
message="fix: Fix bug",
)
def test_empty(self) -> None:
event = self.store_event_owners("empty.lol")
assert self.get_send_to_owners(event) == {}
def test_single_user(self) -> None:
event = self.store_event_owners("user.jsx")
self.assert_recipients_are(
self.get_send_to_owners(event), email=[self.user.id], slack=[self.user.id]
)
with assume_test_silo_mode(SiloMode.CONTROL):
# Make sure that disabling mail alerts works as expected
NotificationSettingProvider.objects.create(
user_id=self.user.id,
scope_type="user",
scope_identifier=self.user.id,
provider="email",
type="alerts",
value="never",
)
self.assert_recipients_are(self.get_send_to_owners(event), slack=[self.user.id])
def test_single_user_no_teams(self) -> None:
event = self.store_event_owners("user.jx")
assert self.get_send_to_owners(event) == {}
def test_team_owners(self) -> None:
event = self.store_event_owners("team.py")
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user.id, self.user2.id],
slack=[self.user.id, self.user2.id],
)
with assume_test_silo_mode(SiloMode.CONTROL):
# disable alerts on the project
NotificationSettingOption.objects.create(
user_id=self.user2.id,
scope_type="project",
scope_identifier=self.project.id,
type="alerts",
value="never",
)
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user.id],
slack=[self.user.id],
)
def test_disable_alerts_multiple_scopes(self) -> None:
event = self.store_event_owners("everyone.cbl")
with assume_test_silo_mode(SiloMode.CONTROL):
# Project-independent setting.
NotificationSettingOption.objects.create(
user_id=self.user2.id,
scope_type="user",
scope_identifier=self.user2.id,
type="alerts",
value="always",
)
# Per-project setting.
NotificationSettingOption.objects.create(
user_id=self.user2.id,
scope_type="project",
scope_identifier=self.project.id,
type="alerts",
value="never",
)
self.assert_recipients_are(
self.get_send_to_owners(event), email=[self.user.id], slack=[self.user.id]
)
def test_no_fallthrough(self) -> None:
event = self.store_event_owners("no_rule.cpp")
self.assert_recipients_are(self.get_send_to_owners(event), email=[], slack=[])
def test_without_fallthrough(self) -> None:
ProjectOwnership.objects.get(project_id=self.project.id).update(fallthrough=False)
event = self.store_event_owners("no_rule.cpp")
assert self.get_send_to_owners(event) == {}
def test_send_to_current_assignee_team(self) -> None:
"""
Test the current issue assignee is notified
"""
event = self.store_event(
data={
"platform": "java",
"stacktrace": STACKTRACE,
},
project_id=self.project.id,
)
team = self.create_team(organization=self.organization, members=[self.user])
assert event.group is not None
GroupAssignee.objects.create(
group=event.group,
project=event.group.project,
team_id=team.id,
date_added=timezone.now(),
)
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user.id],
slack=[self.user.id],
)
def test_send_to_current_assignee_user(self) -> None:
"""
Test the current issue assignee is notified
"""
event = self.store_event(
data={
"platform": "java",
"stacktrace": STACKTRACE,
},
project_id=self.project.id,
)
assert event.group is not None
GroupAssignee.objects.create(
group=event.group,
project=event.group.project,
user_id=self.user.id,
date_added=timezone.now(),
)
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user.id],
slack=[self.user.id],
)
def test_send_to_current_assignee_and_owners(self) -> None:
"""
We currently send to both the current assignee and issue owners.
In the future we might consider only sending to the assignee.
"""
member = self.create_user(email="member@example.com", is_active=True)
event = self.store_event_owners("team.py")
assert event.group is not None
GroupAssignee.objects.create(
group=event.group,
project=event.group.project,
user_id=member.id,
date_added=timezone.now(),
)
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user.id, self.user2.id, member.id],
slack=[self.user.id, self.user2.id, member.id],
)
def test_send_to_suspect_committers(self) -> None:
"""
Test suspect committer is added as suggested assignee
"""
self.commit = self.create_sample_commit(self.user_suspect_committer)
event = self.store_event(
data={"stacktrace": STACKTRACE},
project_id=self.project.id,
)
assert event.group is not None
GroupOwner.objects.create(
group=event.group,
user_id=self.user_suspect_committer.id,
project=self.project,
organization=self.organization,
type=GroupOwnerType.SUSPECT_COMMIT.value,
context={"commitId": self.commit.id},
)
self.assert_recipients_are(
self.get_send_to_owners(event),
email=[self.user_suspect_committer.id, self.user.id],
slack=[self.user_suspect_committer.id, self.user.id],
)
def test_send_to_suspect_committers_no_owners(self) -> None:
"""
Test suspect committer is added as suggested assignee, where no user owns the file
"""
organization = self.create_organization(name="New Organization")
project_suspect_committer = self.create_project(
name="Suspect Committer Team Project",
organization=organization,
teams=[self.team_suspect_committer],
)
team_suspect_committer = self.create_team(
organization=organization, members=[self.user_suspect_committer]
)
project_suspect_committer.add_team(team_suspect_committer)
commit = self.create_sample_commit(self.user_suspect_committer)
event = self.store_event(
data={
"stacktrace": {
"frames": [
{
"function": "handledError",
"abs_path": "Application.lol",
"module": "io.sentry.example.Application",
"in_app": True,
"lineno": 39,
"filename": "Application.lol",
},
]
},
},
project_id=project_suspect_committer.id,
)
assert event.group is not None
GroupOwner.objects.create(
group=event.group,
user_id=self.user_suspect_committer.id,
project=project_suspect_committer,
organization=organization,
type=GroupOwnerType.SUSPECT_COMMIT.value,
context={"commitId": commit.id},
)
self.assert_recipients_are(
get_send_to(
project_suspect_committer,
target_type=ActionTargetType.ISSUE_OWNERS,
target_identifier=None,
event=event,
),
email=[self.user_suspect_committer.id],
slack=[self.user_suspect_committer.id],
)
def test_send_to_suspect_committers_dupe(self) -> None:
"""
Test suspect committer/owner is added as suggested assignee once where the suspect
committer is also the owner.
"""
commit = self.create_sample_commit(self.user)
event = self.store_event(
data={"stacktrace": STACKTRACE},
project_id=self.project.id,
)
assert event.group is not None
GroupOwner.objects.create(
group=event.group,
user_id=self.user.id,
project=self.project,
organization=self.organization,
type=GroupOwnerType.SUSPECT_COMMIT.value,
context={"commitId": commit.id},
)
self.assert_recipients_are(
self.get_send_to_owners(event), email=[self.user.id], slack=[self.user.id]
)
def test_send_to_suspect_committers_exception(self) -> None:
"""
Test determine_eligible_recipients throws an exception when get_suspect_committers throws
an exception and returns the file owner
"""
invalid_commit_id = 10000
event = self.store_event(
data={"stacktrace": STACKTRACE},
project_id=self.project.id,
)
assert event.group is not None
GroupOwner.objects.create(
group=event.group,
user_id=self.user3.id,
project=self.project,
organization=self.organization,
type=GroupOwnerType.SUSPECT_COMMIT.value,
context={"commitId": invalid_commit_id},
)
self.assert_recipients_are(
self.get_send_to_owners(event), email=[self.user.id], slack=[self.user.id]
)
def test_send_to_suspect_committers_not_project_member(self) -> None:
"""
Test suspect committer is not added as suggested assignee where the suspect committer
is not part of the project
"""
user_suspect_committer_no_team = self.create_user(
email="suspectcommitternoteam@example.com", is_active=True
)
commit = self.create_sample_commit(user_suspect_committer_no_team)
event = self.store_event(
data={"stacktrace": STACKTRACE},
project_id=self.project.id,
)
assert event.group is not None
GroupOwner.objects.create(
group=event.group,
user_id=user_suspect_committer_no_team.id,
project=self.project,
organization=self.organization,
type=GroupOwnerType.SUSPECT_COMMIT.value,
context={"commitId": commit.id},
)
self.assert_recipients_are(
self.get_send_to_owners(event), email=[self.user.id], slack=[self.user.id]
)
| GetSendToOwnersTest |
python | huggingface__transformers | src/transformers/models/tapas/modeling_tapas.py | {
"start": 14539,
"end": 17683
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = TapasAttention(config, layer_idx=layer_idx)
self.is_decoder = config.is_decoder
self.add_cross_attention = config.add_cross_attention
if self.add_cross_attention:
if not self.is_decoder:
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
self.crossattention = TapasAttention(config, layer_idx=layer_idx)
self.intermediate = TapasIntermediate(config)
self.output = TapasOutput(config)
# Copied from transformers.models.rembert.modeling_rembert.RemBertLayer.forward
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
cache_position: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor]:
self_attention_outputs = self.attention(
hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
past_key_values=past_key_values,
cache_position=cache_position,
)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
if self.is_decoder and encoder_hidden_states is not None:
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
" by setting `config.add_cross_attention=True`"
)
cross_attention_outputs = self.crossattention(
attention_output,
attention_mask=encoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
past_key_values=past_key_values,
output_attentions=output_attentions,
cache_position=cache_position,
)
attention_output = cross_attention_outputs[0]
outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
)
outputs = (layer_output,) + outputs
return outputs
# Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
| TapasLayer |
python | falconry__falcon | falcon/inspect.py | {
"start": 16294,
"end": 18200
} | class ____(_Traversable):
"""Describes an application.
Args:
routes (list[RouteInfo]): The routes of the application.
middleware (MiddlewareInfo): The middleware information in the application.
static_routes (list[StaticRouteInfo]): The static routes of this application.
sinks (list[SinkInfo]): The sinks of this application.
error_handlers (list[ErrorHandlerInfo]): The error handlers of this application.
asgi (bool): Whether or not this is an ASGI application.
"""
__visit_name__ = 'app'
def __init__(
self,
routes: list[RouteInfo],
middleware: MiddlewareInfo,
static_routes: list[StaticRouteInfo],
sinks: list[SinkInfo],
error_handlers: list[ErrorHandlerInfo],
asgi: bool,
):
self.routes = routes
self.middleware = middleware
self.static_routes = static_routes
self.sinks = sinks
self.error_handlers = error_handlers
self.asgi = asgi
def to_string(
self, verbose: bool = False, internal: bool = False, name: str = ''
) -> str:
"""Return a string representation of this class.
Args:
verbose (bool, optional): Adds more information. Defaults to False.
internal (bool, optional): Also include internal falcon route methods
and error handlers. Defaults to ``False``.
name (str, optional): The name of the application, to be output at the
beginning of the text. Defaults to ``'Falcon App'``.
Returns:
str: A string representation of the application.
"""
return StringVisitor(verbose, internal, name).process(self)
# ------------------------------------------------------------------------
# Visitor classes
# ------------------------------------------------------------------------
| AppInfo |
python | viewflow__viewflow | tests/json/test_json__integer.py | {
"start": 295,
"end": 1165
} | class ____(TestCase):
def test_crud(self):
model = IntegerFieldModel(integer_field=5)
self.assertIsInstance(
model._meta.get_field("integer_field"), models.IntegerField
)
self.assertEqual(
model.data,
{
"integer_field": 5,
},
)
model.save()
model = IntegerFieldModel.objects.get()
self.assertEqual(
model.data,
{
"integer_field": 5,
},
)
self.assertEqual(model.integer_field, 5)
def test_null_value(self):
model = IntegerFieldModel()
self.assertEqual(model.integer_field, None)
self.assertEqual(model.data, {})
def test_default_value(self):
model = IntegerFieldModel()
self.assertEqual(model.default_integer_field, 42)
| Test |
python | ansible__ansible | test/units/module_utils/basic/test_get_module_path.py | {
"start": 342,
"end": 638
} | class ____(unittest.TestCase):
def test_module_utils_basic_get_module_path(self):
from ansible.module_utils.basic import get_module_path
with patch('os.path.realpath', return_value='/path/to/foo/'):
self.assertEqual(get_module_path(), '/path/to/foo')
| TestGetModulePath |
python | getsentry__sentry | src/sentry/migrations/0913_split_discover_dataset_dashboards_self_hosted.py | {
"start": 4672,
"end": 6068
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
dependencies = [
("sentry", "0912_make_organizationmemberteam_replica_is_active_true"),
]
operations = [
migrations.RunPython(
split_discover_dataset_dashboards_self_hosted,
reverse_code=reverse_split_discover_dataset_dashboards_self_hosted,
hints={"tables": ["sentry_dashboardwidget"]},
)
]
| Migration |
python | pytorch__pytorch | torch/overrides.py | {
"start": 104478,
"end": 105537
} | class ____(TorchFunctionMode):
def __torch_function__(self, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
return func(*args, **kwargs)
@contextlib.contextmanager
def _enable_torch_function():
old_state = torch._C._get_torch_function_state()
try:
torch._C._set_torch_function_state(torch._C._TorchFunctionState.ENABLED)
yield
finally:
torch._C._set_torch_function_state(old_state)
@contextlib.contextmanager
def enable_reentrant_dispatch():
# NB: this can't simply be
# `enable_reentrant_dispatch = torch._C._RestorePythonTLSSnapshot`
# because:
# 1. torch._C._RestorePythonTLSSnapshot is unavailable when this file
# initially gets imported. Probably an import order thing.
# 2. enable_reentrant_dispatch is technically public API; assigning
# it the object would change the __module__ to look private.
with torch._C._RestorePythonTLSSnapshot():
try:
yield
finally:
pass
| BaseTorchFunctionMode |
python | crytic__slither | slither/tools/flattening/flattening.py | {
"start": 1419,
"end": 1619
} | class ____(PythonEnum):
MostDerived = 0
OneFile = 1
LocalImport = 2
STRATEGIES_NAMES = ",".join([i.name for i in Strategy])
DEFAULT_EXPORT_PATH = Path("crytic-export/flattening")
| Strategy |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 43658,
"end": 44614
} | class ____(Widget):
"""A representation of ``st.toggle``."""
_value: bool | None
proto: CheckboxProto = field(repr=False)
label: str
help: str
form_id: str
def __init__(self, proto: CheckboxProto, root: ElementTree) -> None:
super().__init__(proto, root)
self._value = None
self.type = "toggle"
@property
def _widget_state(self) -> WidgetState:
ws = WidgetState()
ws.id = self.id
ws.bool_value = self.value
return ws
@property
def value(self) -> bool:
"""The current value of the widget. (bool)""" # noqa: D400
if self._value is not None:
return self._value
state = self.root.session_state
assert state
return cast("bool", state[self.id])
def set_value(self, v: bool) -> Toggle:
"""Set the value of the widget."""
self._value = v
return self
@dataclass(repr=False)
| Toggle |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/legendgrouptitle/_font.py | {
"start": 233,
"end": 9952
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.legendgrouptitle"
_path_str = "scattersmith.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' 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
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattersmith.l
egendgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
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.scattersmith.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattersmith.legendgrouptitle.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/ingress.py | {
"start": 135,
"end": 268
} | class ____(str, Enum):
EXACT = "Exact"
PREFIX = "Prefix"
IMPLEMENTATION_SPECIFIC = "ImplementationSpecific"
| IngressPathType |
python | apache__airflow | airflow-core/src/airflow/executors/base_executor.py | {
"start": 3580,
"end": 4514
} | class ____:
"""
This class is used to fetch configuration for an executor for a particular team_name.
It wraps the implementation of the configuration.get() to look for the particular section and key
prefixed with the team_name. This makes it easy for child classes (i.e. concrete executors) to fetch
configuration values for a particular team_name without having to worry about passing through the
team_name for every call to get configuration.
Currently config only supports environment variables for team specific configuration.
"""
def __init__(self, team_name: str | None = None) -> None:
self.team_name: str | None = team_name
def get(self, *args, **kwargs) -> str | None:
return conf.get(*args, **kwargs, team_name=self.team_name)
def getboolean(self, *args, **kwargs) -> bool:
return conf.getboolean(*args, **kwargs, team_name=self.team_name)
| ExecutorConf |
python | django__django | tests/db_functions/math/test_power.py | {
"start": 170,
"end": 1870
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_power_small=Power("small", "normal"),
null_power_normal=Power("normal", "big"),
null_power_big=Power("big", "normal"),
).first()
self.assertIsNone(obj.null_power_small)
self.assertIsNone(obj.null_power_normal)
self.assertIsNone(obj.null_power_big)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("-0.6"))
obj = DecimalModel.objects.annotate(n_power=Power("n1", "n2")).first()
self.assertIsInstance(obj.n_power, Decimal)
self.assertAlmostEqual(obj.n_power, Decimal(obj.n1**obj.n2))
def test_float(self):
FloatModel.objects.create(f1=2.3, f2=1.1)
obj = FloatModel.objects.annotate(f_power=Power("f1", "f2")).first()
self.assertIsInstance(obj.f_power, float)
self.assertAlmostEqual(obj.f_power, obj.f1**obj.f2)
def test_integer(self):
IntegerModel.objects.create(small=-1, normal=20, big=3)
obj = IntegerModel.objects.annotate(
small_power=Power("small", "normal"),
normal_power=Power("normal", "big"),
big_power=Power("big", "small"),
).first()
self.assertIsInstance(obj.small_power, float)
self.assertIsInstance(obj.normal_power, float)
self.assertIsInstance(obj.big_power, float)
self.assertAlmostEqual(obj.small_power, obj.small**obj.normal)
self.assertAlmostEqual(obj.normal_power, obj.normal**obj.big)
self.assertAlmostEqual(obj.big_power, obj.big**obj.small)
| PowerTests |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_stateful.py | {
"start": 2122,
"end": 2282
} | class ____:
def __init__(self, value):
if value is None:
self.depth = 0
else:
self.depth = value.depth + 1
| DepthCharge |
python | django__django | tests/mail/tests.py | {
"start": 82152,
"end": 86019
} | class ____(SimpleTestCase):
def assertDeprecatedIn70(self, params, name):
return self.assertWarnsMessage(
RemovedInDjango70Warning,
f"Passing positional argument(s) {params} to {name}() is deprecated.",
)
def test_get_connection(self):
with self.assertDeprecatedIn70("'fail_silently'", "get_connection"):
mail.get_connection(
"django.core.mail.backends.dummy.EmailBackend",
# Deprecated positional arg:
True,
)
def test_send_mail(self):
with self.assertDeprecatedIn70(
"'fail_silently', 'auth_user', 'auth_password', 'connection', "
"'html_message'",
"send_mail",
):
send_mail(
"subject",
"message",
"from@example.com",
["to@example.com"],
# Deprecated positional args:
True,
"username",
"password",
mail.get_connection(),
"html message",
)
def test_send_mass_mail(self):
with self.assertDeprecatedIn70(
"'fail_silently', 'auth_user', 'auth_password', 'connection'",
"send_mass_mail",
):
send_mass_mail(
[],
# Deprecated positional args:
True,
"username",
"password",
mail.get_connection(),
)
def test_mail_admins(self):
with self.assertDeprecatedIn70(
"'fail_silently', 'connection', 'html_message'", "mail_admins"
):
mail_admins(
"subject",
"message",
# Deprecated positional args:
True,
mail.get_connection(),
"html message",
)
def test_mail_managers(self):
with self.assertDeprecatedIn70(
"'fail_silently', 'connection', 'html_message'", "mail_managers"
):
mail_managers(
"subject",
"message",
# Deprecated positional args:
True,
mail.get_connection(),
"html message",
)
def test_email_message_init(self):
with self.assertDeprecatedIn70(
"'bcc', 'connection', 'attachments', 'headers', 'cc', 'reply_to'",
"EmailMessage",
):
EmailMessage(
"subject",
"body\n",
"from@example.com",
["to@example.com"],
# Deprecated positional args:
["bcc@example.com"],
mail.get_connection(),
[EmailAttachment("file.txt", "attachment\n", "text/plain")],
{"X-Header": "custom header"},
["cc@example.com"],
["reply-to@example.com"],
)
def test_email_multi_alternatives_init(self):
with self.assertDeprecatedIn70(
"'bcc', 'connection', 'attachments', 'headers', 'alternatives', 'cc', "
"'reply_to'",
"EmailMultiAlternatives",
):
EmailMultiAlternatives(
"subject",
"body\n",
"from@example.com",
["to@example.com"],
# Deprecated positional args:
["bcc@example.com"],
mail.get_connection(),
[EmailAttachment("file.txt", "attachment\n", "text/plain")],
{"X-Header": "custom header"},
[EmailAlternative("html body", "text/html")],
["cc@example.com"],
["reply-to@example.com"],
)
@requires_tz_support
| MailDeprecatedPositionalArgsTests |
python | spyder-ide__spyder | spyder/plugins/toolbar/container.py | {
"start": 1127,
"end": 1184
} | class ____:
ToolbarsMenu = "toolbars_menu"
| ToolbarMenus |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 41612,
"end": 41740
} | class ____(Exception):
"""Thrown when a recoverable assertion error occurs in internal Pyodide code"""
pass
| InternalError |
python | getsentry__sentry | src/sentry/rules/filters/age_comparison.py | {
"start": 984,
"end": 1188
} | class ____(forms.Form):
comparison_type = forms.ChoiceField(choices=age_comparison_choices)
value = forms.IntegerField()
time = forms.ChoiceField(choices=get_timerange_choices)
| AgeComparisonForm |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-reach-destination-in-time.py | {
"start": 225,
"end": 1269
} | class ____(object):
def minCost(self, maxTime, edges, passingFees):
"""
:type maxTime: int
:type edges: List[List[int]]
:type passingFees: List[int]
:rtype: int
"""
adj = [[] for i in xrange(len(passingFees))]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
best = collections.defaultdict(lambda:float("inf"))
best[0] = 0
min_heap = [(passingFees[0], 0, 0)]
while min_heap:
result, u, w = heapq.heappop(min_heap)
if w > maxTime: # state with best[u] < w can't be filtered, which may have less cost
continue
if u == len(passingFees)-1:
return result
for v, nw in adj[u]:
if w+nw < best[v]: # from less cost to more cost, only need to check state with less time
best[v] = w+nw
heapq.heappush(min_heap, (result+passingFees[v], v, w+nw))
return -1
| Solution |
python | kubernetes-client__python | kubernetes/base/config/kube_config_test.py | {
"start": 4819,
"end": 5441
} | class ____(unittest.TestCase):
def setUp(self):
self._temp_files = []
def tearDown(self):
for f in self._temp_files:
os.remove(f)
def _create_temp_file(self, content=""):
handler, name = tempfile.mkstemp()
self._temp_files.append(name)
os.write(handler, str.encode(content))
os.close(handler)
return name
def expect_exception(self, func, message_part, *args, **kwargs):
with self.assertRaises(ConfigException) as context:
func(*args, **kwargs)
self.assertIn(message_part, str(context.exception))
| BaseTestCase |
python | fluentpython__example-code | attic/objects/cards_format.py | {
"start": 2081,
"end": 3259
} | class ____:
def __init__(self, rank, suite, *, long_rank=None):
self.rank = rank
if long_rank is None:
self.long_rank = self.rank
else:
self.long_rank = long_rank
self.suite = suite
def __str__(self):
return '{long_rank} of {suite.name}'.format(**self.__dict__)
def __repr__(self):
template = '{cls.__name__}({rank!r}, {suite.name!r})'
return template.format(cls=self.__class__, **self.__dict__)
def __bytes__(self):
rank_bytes = bytes(ord(char) for char in self.rank)
return rank_bytes + bytes(self.suite)
rank_codes = {
'r': attrgetter('rank'),
'R': attrgetter('long_rank'),
}
def __format__(self, format_spec):
if not format_spec:
format_spec = 'r-s'
result = []
for code in format_spec:
if code in Card.rank_codes:
result.append(Card.rank_codes[code](self))
else:
try:
result.append(format(self.suite, code))
except ValueError:
result.append(code)
return ''.join(result)
| Card |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 56714,
"end": 57059
} | class ____: # noqa: E742
"Sequence using iterator protocol"
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.seqn):
raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
| I |
python | mwaskom__seaborn | seaborn/external/docscrape.py | {
"start": 18365,
"end": 20227
} | class ____(NumpyDocString):
def __init__(self, func, role='func', doc=None, config={}):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdoc(func) or ''
NumpyDocString.__init__(self, doc, config)
if not self['Signature'] and func is not None:
func, func_name = self.get_func()
try:
try:
signature = str(inspect.signature(func))
except (AttributeError, ValueError):
# try to read signature, backward compat for older Python
if sys.version_info[0] >= 3:
argspec = inspect.getfullargspec(func)
else:
argspec = inspect.getargspec(func)
signature = inspect.formatargspec(*argspec)
signature = f'{func_name}{signature}'
except TypeError:
signature = f'{func_name}()'
self['Signature'] = signature
def get_func(self):
func_name = getattr(self._f, '__name__', self.__class__.__name__)
if inspect.isclass(self._f):
func = getattr(self._f, '__call__', self._f.__init__)
else:
func = self._f
return func, func_name
def __str__(self):
out = ''
func, func_name = self.get_func()
roles = {'func': 'function',
'meth': 'method'}
if self._role:
if self._role not in roles:
print(f"Warning: invalid role {self._role}")
out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
out += super().__str__(func_role=self._role)
return out
| FunctionDoc |
python | jazzband__django-model-utils | model_utils/tracker.py | {
"start": 16654,
"end": 16857
} | class ____(FieldTracker):
tracker_class = ModelInstanceTracker
def get_field_map(self, cls: type[models.Model]) -> dict[str, str]:
return {field: field for field in self.fields}
| ModelTracker |
python | django__django | tests/from_db_value/tests.py | {
"start": 138,
"end": 1099
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
CashModel.objects.create(cash="12.50")
def test_simple_load(self):
instance = CashModel.objects.get()
self.assertIsInstance(instance.cash, Cash)
def test_values_list(self):
values_list = CashModel.objects.values_list("cash", flat=True)
self.assertIsInstance(values_list[0], Cash)
def test_values(self):
values = CashModel.objects.values("cash")
self.assertIsInstance(values[0]["cash"], Cash)
def test_aggregation(self):
maximum = CashModel.objects.aggregate(m=Max("cash"))["m"]
self.assertIsInstance(maximum, Cash)
def test_defer(self):
instance = CashModel.objects.defer("cash").get()
self.assertIsInstance(instance.cash, Cash)
def test_connection(self):
instance = CashModel.objects.get()
self.assertEqual(instance.cash.vendor, connection.vendor)
| FromDBValueTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol33.py | {
"start": 198,
"end": 309
} | class ____(Generic[T, U], Protocol):
def f(self) -> T | U: ...
def g(self) -> "AProto[T, U]": ...
| AProto |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 27671,
"end": 28138
} | class ____(
LinalgSquareTestCase,
LinalgNonsquareTestCase,
LinalgGeneralizedSquareTestCase,
LinalgGeneralizedNonsquareTestCase,
):
def do(self, a, b, tags):
a_ginv = linalg.pinv(a)
# `a @ a_ginv == I` does not hold if a is singular
dot = dot_generalized
assert_almost_equal(
dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11
)
assert_(consistent_subclass(a_ginv, a))
| PinvCases |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 28617,
"end": 29354
} | class ____(AbstractTemplate):
def generic(self, args, kws):
if kws:
raise errors.NumbaAssertionError('kws not supported')
[arg] = args
if isinstance(arg, types.Integer):
return signature(arg, arg)
if isinstance(arg, (types.Float, types.Boolean)):
return signature(types.intp, arg)
if isinstance(arg, types.NPDatetime):
if arg.unit == 'ns':
return signature(types.int64, arg)
else:
raise errors.NumbaTypeError(f"Only datetime64[ns] can be converted, but got datetime64[{arg.unit}]")
if isinstance(arg, types.NPTimedelta):
return signature(types.int64, arg)
@infer_global(float)
| Int |
python | keras-team__keras | keras/src/legacy/preprocessing/text.py | {
"start": 1827,
"end": 11103
} | class ____:
"""DEPRECATED."""
def __init__(
self,
num_words=None,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True,
split=" ",
char_level=False,
oov_token=None,
analyzer=None,
**kwargs,
):
# Legacy support
if "nb_words" in kwargs:
warnings.warn(
"The `nb_words` argument in `Tokenizer` "
"has been renamed `num_words`."
)
num_words = kwargs.pop("nb_words")
document_count = kwargs.pop("document_count", 0)
if kwargs:
raise TypeError(f"Unrecognized keyword arguments: {str(kwargs)}")
self.word_counts = collections.OrderedDict()
self.word_docs = collections.defaultdict(int)
self.filters = filters
self.split = split
self.lower = lower
self.num_words = num_words
self.document_count = document_count
self.char_level = char_level
self.oov_token = oov_token
self.index_docs = collections.defaultdict(int)
self.word_index = {}
self.index_word = {}
self.analyzer = analyzer
def fit_on_texts(self, texts):
for text in texts:
self.document_count += 1
if self.char_level or isinstance(text, list):
if self.lower:
if isinstance(text, list):
text = [text_elem.lower() for text_elem in text]
else:
text = text.lower()
seq = text
else:
if self.analyzer is None:
seq = text_to_word_sequence(
text,
filters=self.filters,
lower=self.lower,
split=self.split,
)
else:
seq = self.analyzer(text)
for w in seq:
if w in self.word_counts:
self.word_counts[w] += 1
else:
self.word_counts[w] = 1
for w in set(seq):
# In how many documents each word occurs
self.word_docs[w] += 1
wcounts = list(self.word_counts.items())
wcounts.sort(key=lambda x: x[1], reverse=True)
# forcing the oov_token to index 1 if it exists
if self.oov_token is None:
sorted_voc = []
else:
sorted_voc = [self.oov_token]
sorted_voc.extend(wc[0] for wc in wcounts)
# note that index 0 is reserved, never assigned to an existing word
self.word_index = dict(
zip(sorted_voc, list(range(1, len(sorted_voc) + 1)))
)
self.index_word = {c: w for w, c in self.word_index.items()}
for w, c in list(self.word_docs.items()):
self.index_docs[self.word_index[w]] = c
def fit_on_sequences(self, sequences):
self.document_count += len(sequences)
for seq in sequences:
seq = set(seq)
for i in seq:
self.index_docs[i] += 1
def texts_to_sequences(self, texts):
return list(self.texts_to_sequences_generator(texts))
def texts_to_sequences_generator(self, texts):
num_words = self.num_words
oov_token_index = self.word_index.get(self.oov_token)
for text in texts:
if self.char_level or isinstance(text, list):
if self.lower:
if isinstance(text, list):
text = [text_elem.lower() for text_elem in text]
else:
text = text.lower()
seq = text
else:
if self.analyzer is None:
seq = text_to_word_sequence(
text,
filters=self.filters,
lower=self.lower,
split=self.split,
)
else:
seq = self.analyzer(text)
vect = []
for w in seq:
i = self.word_index.get(w)
if i is not None:
if num_words and i >= num_words:
if oov_token_index is not None:
vect.append(oov_token_index)
else:
vect.append(i)
elif self.oov_token is not None:
vect.append(oov_token_index)
yield vect
def sequences_to_texts(self, sequences):
return list(self.sequences_to_texts_generator(sequences))
def sequences_to_texts_generator(self, sequences):
num_words = self.num_words
oov_token_index = self.word_index.get(self.oov_token)
for seq in sequences:
vect = []
for num in seq:
word = self.index_word.get(num)
if word is not None:
if num_words and num >= num_words:
if oov_token_index is not None:
vect.append(self.index_word[oov_token_index])
else:
vect.append(word)
elif self.oov_token is not None:
vect.append(self.index_word[oov_token_index])
vect = " ".join(vect)
yield vect
def texts_to_matrix(self, texts, mode="binary"):
sequences = self.texts_to_sequences(texts)
return self.sequences_to_matrix(sequences, mode=mode)
def sequences_to_matrix(self, sequences, mode="binary"):
if not self.num_words:
if self.word_index:
num_words = len(self.word_index) + 1
else:
raise ValueError(
"Specify a dimension (`num_words` argument), "
"or fit on some text data first."
)
else:
num_words = self.num_words
if mode == "tfidf" and not self.document_count:
raise ValueError(
"Fit the Tokenizer on some data before using tfidf mode."
)
x = np.zeros((len(sequences), num_words))
for i, seq in enumerate(sequences):
if not seq:
continue
counts = collections.defaultdict(int)
for j in seq:
if j >= num_words:
continue
counts[j] += 1
for j, c in list(counts.items()):
if mode == "count":
x[i][j] = c
elif mode == "freq":
x[i][j] = c / len(seq)
elif mode == "binary":
x[i][j] = 1
elif mode == "tfidf":
# Use weighting scheme 2 in
# https://en.wikipedia.org/wiki/Tf%E2%80%93idf
tf = 1 + np.log(c)
idf = np.log(
1
+ self.document_count / (1 + self.index_docs.get(j, 0))
)
x[i][j] = tf * idf
else:
raise ValueError("Unknown vectorization mode:", mode)
return x
def get_config(self):
json_word_counts = json.dumps(self.word_counts)
json_word_docs = json.dumps(self.word_docs)
json_index_docs = json.dumps(self.index_docs)
json_word_index = json.dumps(self.word_index)
json_index_word = json.dumps(self.index_word)
return {
"num_words": self.num_words,
"filters": self.filters,
"lower": self.lower,
"split": self.split,
"char_level": self.char_level,
"oov_token": self.oov_token,
"document_count": self.document_count,
"word_counts": json_word_counts,
"word_docs": json_word_docs,
"index_docs": json_index_docs,
"index_word": json_index_word,
"word_index": json_word_index,
}
def to_json(self, **kwargs):
config = self.get_config()
tokenizer_config = {
"class_name": self.__class__.__name__,
"config": config,
}
return json.dumps(tokenizer_config, **kwargs)
@keras_export("keras._legacy.preprocessing.text.tokenizer_from_json")
def tokenizer_from_json(json_string):
"""DEPRECATED."""
tokenizer_config = json.loads(json_string)
config = tokenizer_config.get("config")
word_counts = json.loads(config.pop("word_counts"))
word_docs = json.loads(config.pop("word_docs"))
index_docs = json.loads(config.pop("index_docs"))
# Integer indexing gets converted to strings with json.dumps()
index_docs = {int(k): v for k, v in index_docs.items()}
index_word = json.loads(config.pop("index_word"))
index_word = {int(k): v for k, v in index_word.items()}
word_index = json.loads(config.pop("word_index"))
tokenizer = Tokenizer(**config)
tokenizer.word_counts = word_counts
tokenizer.word_docs = word_docs
tokenizer.index_docs = index_docs
tokenizer.word_index = word_index
tokenizer.index_word = index_word
return tokenizer
| Tokenizer |
python | Pylons__pyramid | tests/test_request.py | {
"start": 20595,
"end": 23399
} | class ____(unittest.TestCase):
def _makeOne(self, *args, **kwargs):
from pyramid.request import RequestLocalCache
return RequestLocalCache(*args, **kwargs)
def test_it_works_with_functions(self):
a = [0]
@self._makeOne()
def foo(request):
a[0] += 1
return a[0]
req1 = DummyRequest()
req2 = DummyRequest()
self.assertEqual(foo(req1), 1)
self.assertEqual(foo(req2), 2)
self.assertEqual(foo(req1), 1)
self.assertEqual(foo(req2), 2)
self.assertEqual(len(req1.finished_callbacks), 1)
self.assertEqual(len(req2.finished_callbacks), 1)
def test_clear_works(self):
a = [0]
@self._makeOne()
def foo(request):
a[0] += 1
return a[0]
req = DummyRequest()
self.assertEqual(foo(req), 1)
self.assertEqual(len(req.finished_callbacks), 1)
foo.cache.clear(req)
self.assertEqual(foo(req), 2)
self.assertEqual(len(req.finished_callbacks), 1)
def test_set_overrides_current_value(self):
a = [0]
@self._makeOne()
def foo(request):
a[0] += 1
return a[0]
req = DummyRequest()
self.assertEqual(foo(req), 1)
self.assertEqual(len(req.finished_callbacks), 1)
foo.cache.set(req, 8)
self.assertEqual(foo(req), 8)
self.assertEqual(len(req.finished_callbacks), 1)
self.assertEqual(foo.cache.get(req), 8)
def test_get_works(self):
cache = self._makeOne()
req = DummyRequest()
self.assertIs(cache.get(req), cache.NO_VALUE)
cache.set(req, 2)
self.assertIs(cache.get(req), 2)
def test_creator_in_constructor(self):
def foo(request):
return 8
cache = self._makeOne(foo)
req = DummyRequest()
result = cache.get_or_create(req)
self.assertEqual(result, 8)
def test_decorator_overrides_creator(self):
def foo(request): # pragma: no cover
raise AssertionError
cache = self._makeOne(foo)
@cache
def bar(request):
return 8
req = DummyRequest()
result = cache.get_or_create(req)
self.assertEqual(result, 8)
def test_get_or_create_overrides_creator(self):
cache = self._makeOne()
@cache
def foo(request): # pragma: no cover
raise AssertionError
req = DummyRequest()
result = cache.get_or_create(req, lambda r: 8)
self.assertEqual(result, 8)
def test_get_or_create_with_no_creator(self):
cache = self._makeOne()
req = DummyRequest()
self.assertRaises(ValueError, cache.get_or_create, req)
| TestRequestLocalCache |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 37238,
"end": 37823
} | class ____(_NoTextCoercion, RoleImpl):
__slots__ = ()
def _implicit_coercions(
self,
element: Any,
resolved: Any,
argname: Optional[str] = None,
**kw: Any,
) -> Any:
if resolved._is_from_clause:
if (
isinstance(resolved, selectable.Alias)
and resolved.element._is_select_base
):
return resolved.element
else:
return resolved.select()
else:
self._raise_for_expected(element, argname, resolved)
| DMLSelectImpl |
python | celery__celery | t/unit/tasks/test_chord.py | {
"start": 1492,
"end": 8078
} | class ____(ChordCase):
def test_unlock_ready(self):
class AlwaysReady(TSR):
is_ready = True
value = [2, 4, 8, 6]
with self._chord_context(AlwaysReady) as (cb, retry, _):
cb.type.apply_async.assert_called_with(
([2, 4, 8, 6],), {}, task_id=cb.id,
)
# didn't retry
assert not retry.call_count
def test_deps_ready_fails(self):
GroupResult = Mock(name='GroupResult')
GroupResult.return_value.ready.side_effect = KeyError('foo')
unlock_chord = self.app.tasks['celery.chord_unlock']
with pytest.raises(KeyError):
unlock_chord('groupid', Mock(), result=[Mock()],
GroupResult=GroupResult, result_from_tuple=Mock())
def test_callback_fails(self):
class AlwaysReady(TSR):
is_ready = True
value = [2, 4, 8, 6]
def setup(callback):
callback.apply_async.side_effect = IOError()
with self._chord_context(AlwaysReady, setup) as (cb, retry, fail):
fail.assert_called()
assert fail.call_args[0][0] == cb.id
assert isinstance(fail.call_args[1]['exc'], ChordError)
def test_unlock_ready_failed(self):
class Failed(TSR):
is_ready = True
value = [2, KeyError('foo'), 8, 6]
with self._chord_context(Failed) as (cb, retry, fail_current):
cb.type.apply_async.assert_not_called()
# didn't retry
assert not retry.call_count
fail_current.assert_called()
assert fail_current.call_args[0][0] == cb.id
assert isinstance(fail_current.call_args[1]['exc'], ChordError)
assert 'some_id' in str(fail_current.call_args[1]['exc'])
def test_unlock_ready_failed_no_culprit(self):
class Failed(TSRNoReport):
is_ready = True
value = [2, KeyError('foo'), 8, 6]
with self._chord_context(Failed) as (cb, retry, fail_current):
fail_current.assert_called()
assert fail_current.call_args[0][0] == cb.id
assert isinstance(fail_current.call_args[1]['exc'], ChordError)
@contextmanager
def _chord_context(self, ResultCls, setup=None, **kwargs):
@self.app.task(shared=False)
def callback(*args, **kwargs):
pass
self.app.finalize()
pts, result.GroupResult = result.GroupResult, ResultCls
callback.apply_async = Mock()
callback_s = callback.s()
callback_s.id = 'callback_id'
fail_current = self.app.backend.fail_from_current_stack = Mock()
try:
with patch_unlock_retry(self.app) as (unlock, retry):
signature, canvas.maybe_signature = (
canvas.maybe_signature, passthru,
)
if setup:
setup(callback)
try:
assert self.app.tasks['celery.chord_unlock'] is unlock
try:
unlock(
'group_id', callback_s,
result=[
self.app.AsyncResult(r) for r in ['1', 2, 3]
],
GroupResult=ResultCls, **kwargs
)
except Retry:
pass
finally:
canvas.maybe_signature = signature
yield callback_s, retry, fail_current
finally:
result.GroupResult = pts
def test_when_not_ready(self):
class NeverReady(TSR):
is_ready = False
with self._chord_context(NeverReady, interval=10, max_retries=30) \
as (cb, retry, _):
cb.type.apply_async.assert_not_called()
# did retry
retry.assert_called_with(countdown=10, max_retries=30)
def test_when_not_ready_with_configured_chord_retry_interval(self):
class NeverReady(TSR):
is_ready = False
self.app.conf.result_chord_retry_interval, prev = 42, self.app.conf.result_chord_retry_interval
try:
with self._chord_context(NeverReady, max_retries=30) as (cb, retry, _):
cb.type.apply_async.assert_not_called()
# did retry
retry.assert_called_with(countdown=42, max_retries=30)
finally:
self.app.conf.result_chord_retry_interval = prev
def test_is_in_registry(self):
assert 'celery.chord_unlock' in self.app.tasks
def _test_unlock_join_timeout(self, timeout):
class MockJoinResult(TSR):
is_ready = True
value = [(None,)]
join = Mock(return_value=value)
join_native = join
self.app.conf.result_chord_join_timeout = timeout
with self._chord_context(MockJoinResult):
MockJoinResult.join.assert_called_with(
timeout=timeout,
propagate=True,
)
def test_unlock_join_timeout_default(self):
self._test_unlock_join_timeout(
timeout=self.app.conf.result_chord_join_timeout,
)
def test_unlock_join_timeout_custom(self):
self._test_unlock_join_timeout(timeout=5.0)
def test_unlock_with_chord_params_default(self):
@self.app.task(shared=False)
def mul(x, y):
return x * y
from celery import chord
g = group(mul.s(1, 1), mul.s(2, 2))
body = mul.s()
ch = chord(g, body, interval=10)
with patch.object(ch, 'run') as run:
ch.apply_async()
run.assert_called_once_with(
AnySignatureWithTask(g),
mul.s(),
(),
task_id=None,
kwargs={},
interval=10,
)
def test_unlock_with_chord_params_and_task_id(self):
@self.app.task(shared=False)
def mul(x, y):
return x * y
from celery import chord
g = group(mul.s(1, 1), mul.s(2, 2))
body = mul.s()
ch = chord(g, body, interval=10)
with patch.object(ch, 'run') as run:
ch.apply_async(task_id=sentinel.task_id)
run.assert_called_once_with(
AnySignatureWithTask(g),
mul.s(),
(),
task_id=sentinel.task_id,
kwargs={},
interval=10,
)
| test_unlock_chord_task |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 57500,
"end": 59524
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
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.num_attention_heads = 1 # 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.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)
def forward(self, query, key, attention_mask):
batch_size, seq_length, _ = query.shape
attention_mask = attention_mask.to(query.dtype)
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
attention_mask = (1.0 - attention_mask) * torch.finfo(query.dtype).min
query_layer = (
self.query(query).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
)
key_layer = (
self.key(key).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
attention_scores = attention_scores + attention_mask
attention_scores = attention_scores.squeeze(1)
return attention_scores
@auto_docstring(
custom_intro="""
VisualBert Model with a Masked Language Modeling head and an attention layer on top for Region-to-Phrase Alignment
e.g. for Flickr30 Entities task.
"""
)
| VisualBertRegionToPhraseAttention |
python | kubernetes-client__python | kubernetes/client/models/v1_endpoints.py | {
"start": 383,
"end": 7596
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'subsets': 'list[V1EndpointSubset]'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'subsets': 'subsets'
}
def __init__(self, api_version=None, kind=None, metadata=None, subsets=None, local_vars_configuration=None): # noqa: E501
"""V1Endpoints - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._kind = None
self._metadata = None
self._subsets = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if subsets is not None:
self.subsets = subsets
@property
def api_version(self):
"""Gets the api_version of this V1Endpoints. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1Endpoints. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1Endpoints.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1Endpoints. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this V1Endpoints. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1Endpoints. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1Endpoints.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1Endpoints. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1Endpoints. # noqa: E501
:return: The metadata of this V1Endpoints. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1Endpoints.
:param metadata: The metadata of this V1Endpoints. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def subsets(self):
"""Gets the subsets of this V1Endpoints. # noqa: E501
The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service. # noqa: E501
:return: The subsets of this V1Endpoints. # noqa: E501
:rtype: list[V1EndpointSubset]
"""
return self._subsets
@subsets.setter
def subsets(self, subsets):
"""Sets the subsets of this V1Endpoints.
The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service. # noqa: E501
:param subsets: The subsets of this V1Endpoints. # noqa: E501
:type: list[V1EndpointSubset]
"""
self._subsets = subsets
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1Endpoints):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1Endpoints):
return True
return self.to_dict() != other.to_dict()
| V1Endpoints |
python | plotly__plotly.py | plotly/graph_objs/isosurface/_lightposition.py | {
"start": 233,
"end": 3509
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface"
_path_str = "isosurface.lightposition"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
Numeric vector, representing the X coordinate for each vertex.
The 'x' property is a number and may be specified as:
- An int or float in the interval [-100000, 100000]
Returns
-------
int|float
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def y(self):
"""
Numeric vector, representing the Y coordinate for each vertex.
The 'y' property is a number and may be specified as:
- An int or float in the interval [-100000, 100000]
Returns
-------
int|float
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def z(self):
"""
Numeric vector, representing the Z coordinate for each vertex.
The 'z' property is a number and may be specified as:
- An int or float in the interval [-100000, 100000]
Returns
-------
int|float
"""
return self["z"]
@z.setter
def z(self, val):
self["z"] = val
@property
def _prop_descriptions(self):
return """\
x
Numeric vector, representing the X coordinate for each
vertex.
y
Numeric vector, representing the Y coordinate for each
vertex.
z
Numeric vector, representing the Z coordinate for each
vertex.
"""
def __init__(self, arg=None, x=None, y=None, z=None, **kwargs):
"""
Construct a new Lightposition object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.Lightposition`
x
Numeric vector, representing the X coordinate for each
vertex.
y
Numeric vector, representing the Y coordinate for each
vertex.
z
Numeric vector, representing the Z coordinate for each
vertex.
Returns
-------
Lightposition
"""
super().__init__("lightposition")
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.isosurface.Lightposition
constructor must be a dict or
an instance of :class:`plotly.graph_objs.isosurface.Lightposition`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("x", arg, x)
self._set_property("y", arg, y)
self._set_property("z", arg, z)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Lightposition |
python | getsentry__sentry-python | sentry_sdk/integrations/clickhouse_driver.py | {
"start": 1109,
"end": 6098
} | class ____(Integration):
identifier = "clickhouse_driver"
origin = f"auto.db.{identifier}"
@staticmethod
def setup_once() -> None:
_check_minimum_version(ClickhouseDriverIntegration, clickhouse_driver.VERSION)
# Every query is done using the Connection's `send_query` function
clickhouse_driver.connection.Connection.send_query = _wrap_start(
clickhouse_driver.connection.Connection.send_query
)
# If the query contains parameters then the send_data function is used to send those parameters to clickhouse
_wrap_send_data()
# Every query ends either with the Client's `receive_end_of_query` (no result expected)
# or its `receive_result` (result expected)
clickhouse_driver.client.Client.receive_end_of_query = _wrap_end(
clickhouse_driver.client.Client.receive_end_of_query
)
if hasattr(clickhouse_driver.client.Client, "receive_end_of_insert_query"):
# In 0.2.7, insert queries are handled separately via `receive_end_of_insert_query`
clickhouse_driver.client.Client.receive_end_of_insert_query = _wrap_end(
clickhouse_driver.client.Client.receive_end_of_insert_query
)
clickhouse_driver.client.Client.receive_result = _wrap_end(
clickhouse_driver.client.Client.receive_result
)
P = ParamSpec("P")
T = TypeVar("T")
def _wrap_start(f: Callable[P, T]) -> Callable[P, T]:
@ensure_integration_enabled(ClickhouseDriverIntegration, f)
def _inner(*args: P.args, **kwargs: P.kwargs) -> T:
connection = args[0]
query = args[1]
query_id = args[2] if len(args) > 2 else kwargs.get("query_id")
params = args[3] if len(args) > 3 else kwargs.get("params")
span = sentry_sdk.start_span(
op=OP.DB,
name=query,
origin=ClickhouseDriverIntegration.origin,
)
connection._sentry_span = span # type: ignore[attr-defined]
_set_db_data(span, connection)
span.set_data("query", query)
if query_id:
span.set_data("db.query_id", query_id)
if params and should_send_default_pii():
span.set_data("db.params", params)
# run the original code
ret = f(*args, **kwargs)
return ret
return _inner
def _wrap_end(f: Callable[P, T]) -> Callable[P, T]:
def _inner_end(*args: P.args, **kwargs: P.kwargs) -> T:
res = f(*args, **kwargs)
instance = args[0]
span = getattr(instance.connection, "_sentry_span", None) # type: ignore[attr-defined]
if span is not None:
if res is not None and should_send_default_pii():
span.set_data("db.result", res)
with capture_internal_exceptions():
span.scope.add_breadcrumb(
message=span._data.pop("query"), category="query", data=span._data
)
span.finish()
return res
return _inner_end
def _wrap_send_data() -> None:
original_send_data = clickhouse_driver.client.Client.send_data
def _inner_send_data( # type: ignore[no-untyped-def] # clickhouse-driver does not type send_data
self, sample_block, data, types_check=False, columnar=False, *args, **kwargs
):
span = getattr(self.connection, "_sentry_span", None)
if span is not None:
_set_db_data(span, self.connection)
if should_send_default_pii():
db_params = span._data.get("db.params", [])
if isinstance(data, (list, tuple)):
db_params.extend(data)
else: # data is a generic iterator
orig_data = data
# Wrap the generator to add items to db.params as they are yielded.
# This allows us to send the params to Sentry without needing to allocate
# memory for the entire generator at once.
def wrapped_generator() -> "Iterator[Any]":
for item in orig_data:
db_params.append(item)
yield item
# Replace the original iterator with the wrapped one.
data = wrapped_generator()
span.set_data("db.params", db_params)
return original_send_data(
self, sample_block, data, types_check, columnar, *args, **kwargs
)
clickhouse_driver.client.Client.send_data = _inner_send_data
def _set_db_data(
span: Span, connection: clickhouse_driver.connection.Connection
) -> None:
span.set_data(SPANDATA.DB_SYSTEM, "clickhouse")
span.set_data(SPANDATA.SERVER_ADDRESS, connection.host)
span.set_data(SPANDATA.SERVER_PORT, connection.port)
span.set_data(SPANDATA.DB_NAME, connection.database)
span.set_data(SPANDATA.DB_USER, connection.user)
| ClickhouseDriverIntegration |
python | huggingface__transformers | src/transformers/models/pvt/modeling_pvt.py | {
"start": 12274,
"end": 13963
} | class ____(nn.Module):
def __init__(
self,
config: PvtConfig,
hidden_size: int,
num_attention_heads: int,
drop_path: float,
sequences_reduction_ratio: float,
mlp_ratio: float,
):
super().__init__()
self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
self.attention = PvtAttention(
config=config,
hidden_size=hidden_size,
num_attention_heads=num_attention_heads,
sequences_reduction_ratio=sequences_reduction_ratio,
)
self.drop_path = PvtDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
mlp_hidden_size = int(hidden_size * mlp_ratio)
self.mlp = PvtFFN(config=config, in_features=hidden_size, hidden_features=mlp_hidden_size)
def forward(self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False):
self_attention_outputs = self.attention(
hidden_states=self.layer_norm_1(hidden_states),
height=height,
width=width,
output_attentions=output_attentions,
)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:]
attention_output = self.drop_path(attention_output)
hidden_states = attention_output + hidden_states
mlp_output = self.mlp(self.layer_norm_2(hidden_states))
mlp_output = self.drop_path(mlp_output)
layer_output = hidden_states + mlp_output
outputs = (layer_output,) + outputs
return outputs
| PvtLayer |
python | PyCQA__pylint | doc/data/messages/i/invalid-hash-returned/good.py | {
"start": 0,
"end": 94
} | class ____:
"""__hash__ returns `int`"""
def __hash__(self):
return 19
| CustomHash |
python | ansible__ansible | lib/ansible/utils/collection_loader/__init__.py | {
"start": 395,
"end": 2564
} | class ____(t.Protocol):
"""Protocol representing an `EncryptedString`, since it cannot be imported here."""
# DTFIX-FUTURE: collapse this with the one in config, once we can
def _decrypt(self) -> str: ...
def _to_text(value: str | bytes | _EncryptedStringProtocol | None, strict: bool = False) -> str | None:
"""Internal implementation to keep collection loader standalone."""
# FUTURE: remove this method when _to_bytes is removed
if value is None:
return None
if isinstance(value, str):
return value
if isinstance(value, bytes):
return value.decode(errors='strict' if strict else 'surrogateescape')
if isinstance(value, _EncryptedStringProtocol):
return value._decrypt()
raise TypeError(f'unsupported type {type(value)}')
def _to_bytes(value: str | bytes | _EncryptedStringProtocol | None, strict: bool = False) -> bytes | None:
"""Internal implementation to keep collection loader standalone."""
# FUTURE: remove this method and rely on automatic str -> bytes conversions of filesystem methods instead
if value is None:
return None
if isinstance(value, bytes):
return value
if isinstance(value, str):
return value.encode(errors='strict' if strict else 'surrogateescape')
if isinstance(value, _EncryptedStringProtocol):
return value._decrypt().encode(errors='strict' if strict else 'surrogateescape')
raise TypeError(f'unsupported type {type(value)}')
def resource_from_fqcr(ref):
"""
Return resource from a fully-qualified collection reference,
or from a simple resource name.
For fully-qualified collection references, this is equivalent to
``AnsibleCollectionRef.from_fqcr(ref).resource``.
:param ref: collection reference to parse
:return: the resource as a unicode string
"""
ref = _to_text(ref, strict=True)
return ref.split(u'.')[-1]
# FIXME: decide what of this we want to actually be public/toplevel, put other stuff on a utility class?
from ._collection_config import AnsibleCollectionConfig
from ._collection_finder import AnsibleCollectionRef
| _EncryptedStringProtocol |
python | getsentry__sentry | tests/sentry/api/bases/test_project.py | {
"start": 476,
"end": 1243
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.permission_cls = ProjectPermission
def has_object_perm(
self,
method: str,
obj: Project,
auth: ApiToken | None = None,
user: User | None = None,
is_superuser: bool | None = None,
is_staff: bool | None = None,
) -> bool:
perm = self.permission_cls()
request = self.make_request(
user=user, auth=auth, method=method, is_superuser=is_superuser, is_staff=is_staff
)
drf_request = drf_request_from_request(request)
return perm.has_permission(drf_request, APIView()) and perm.has_object_permission(
drf_request, APIView(), obj
)
| ProjectPermissionBase |
python | PyCQA__pylint | tests/functional/m/method_cache_max_size_none.py | {
"start": 1437,
"end": 2189
} | class ____:
@lru_cache(maxsize=1)
def my_func(self, param):
return param + 1
@lru_cache(maxsize=1)
def my_func(self, param):
return param + 1
@lru_cache(typed=True)
def my_func(self, param):
return param + 1
@lru_cache(typed=True)
def my_func(self, param):
return param + 1
@lru_cache(typed=True, maxsize=1)
def my_func(self, param):
return param + 1
@lru_cache(typed=True, maxsize=1)
def my_func(self, param):
return param + 1
@lru_cache(typed=True, maxsize=None) # [method-cache-max-size-none]
def my_func(self, param):
return param + 1
@lru_cache(maxsize=None)
def my_func(param):
return param + 1
| MyClassWithMethodsAndMaxSize |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/gcs.py | {
"start": 20863,
"end": 26425
} | class ____(GoogleCloudBaseOperator):
"""
Copies data from a source GCS location to a temporary location on the local filesystem.
Runs a transformation on this file as specified by the transformation script
and uploads the output to a destination bucket. If the output bucket is not
specified the original file will be overwritten.
The locations of the source and the destination files in the local
filesystem is provided as an first and second arguments to the
transformation script. The transformation script is expected to read the
data from source, transform it and write the output to the local
destination file.
:param source_bucket: The bucket to locate the source_object. (templated)
:param source_object: The key to be retrieved from GCS. (templated)
:param destination_bucket: The bucket to upload the key after transformation.
If not provided, source_bucket will be used. (templated)
:param destination_object: The key to be written in GCS.
If not provided, source_object will be used. (templated)
:param transform_script: location of the executable transformation script or list of arguments
passed to subprocess ex. `['python', 'script.py', 10]`. (templated)
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"source_bucket",
"source_object",
"destination_bucket",
"destination_object",
"transform_script",
"gcp_conn_id",
"impersonation_chain",
)
operator_extra_links = (FileDetailsLink(),)
def __init__(
self,
*,
source_bucket: str,
source_object: str,
transform_script: str | list[str],
destination_bucket: str | None = None,
destination_object: str | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.source_bucket = source_bucket
self.source_object = source_object
self.destination_bucket = destination_bucket or self.source_bucket
self.destination_object = destination_object or self.source_object
self.gcp_conn_id = gcp_conn_id
self.transform_script = transform_script
self.output_encoding = sys.getdefaultencoding()
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> None:
hook = GCSHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
with NamedTemporaryFile() as source_file, NamedTemporaryFile() as destination_file:
self.log.info("Downloading file from %s", self.source_bucket)
hook.download(
bucket_name=self.source_bucket, object_name=self.source_object, filename=source_file.name
)
self.log.info("Starting the transformation")
cmd = [self.transform_script] if isinstance(self.transform_script, str) else self.transform_script
cmd += [source_file.name, destination_file.name]
with subprocess.Popen(
args=cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True
) as process:
self.log.info("Process output:")
if process.stdout:
for line in iter(process.stdout.readline, b""):
self.log.info(line.decode(self.output_encoding).rstrip())
process.wait()
if process.returncode:
raise AirflowException(f"Transform script failed: {process.returncode}")
self.log.info("Transformation succeeded. Output temporarily located at %s", destination_file.name)
self.log.info("Uploading file to %s as %s", self.destination_bucket, self.destination_object)
FileDetailsLink.persist(
context=context,
uri=f"{self.destination_bucket}/{self.destination_object}",
project_id=hook.project_id,
)
hook.upload(
bucket_name=self.destination_bucket,
object_name=self.destination_object,
filename=destination_file.name,
)
def get_openlineage_facets_on_start(self):
from airflow.providers.common.compat.openlineage.facet import Dataset
from airflow.providers.openlineage.extractors import OperatorLineage
input_dataset = Dataset(
namespace=f"gs://{self.source_bucket}",
name=self.source_object,
)
output_dataset = Dataset(
namespace=f"gs://{self.destination_bucket}",
name=self.destination_object,
)
return OperatorLineage(inputs=[input_dataset], outputs=[output_dataset])
| GCSFileTransformOperator |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/modules/main.py | {
"start": 1136,
"end": 1772
} | class ____(webapp2.RequestHandler):
def get(self):
# [START gae_standard_modules_access_another_module]
backend_hostname = modules.get_hostname(module="my-backend")
url = "http://{}/".format(backend_hostname)
try:
result = urllib2.urlopen(url).read()
self.response.write("Got response {}".format(result))
except urllib2.URLError:
pass
# [END gae_standard_modules_access_another_module]
app = webapp2.WSGIApplication(
[
("/", GetModuleInfoHandler),
("/access_backend", GetBackendHandler),
],
debug=True,
)
| GetBackendHandler |
python | scrapy__scrapy | tests/test_spidermiddleware_process_start.py | {
"start": 1493,
"end": 1649
} | class ____(Spider):
name = "test"
async def start(self):
yield ITEM_B
def start_requests(self):
yield ITEM_D
| UniversalWrapSpider |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_strategy.py | {
"start": 11842,
"end": 38265
} | class ____(distribute_lib.StrategyExtendedV1):
"""Implementation of MirroredStrategy."""
def __init__(self, container_strategy, devices=None, cross_device_ops=None):
super(MirroredExtended, self).__init__(container_strategy)
if context.executing_eagerly():
if devices and not _is_device_list_single_worker(devices):
raise RuntimeError("In-graph multi-worker training with "
"`MirroredStrategy` is not supported in eager mode.")
else:
if (
tfconfig_cluster_resolver.TFConfigClusterResolver()
.cluster_spec()
.as_dict()
):
# if you are executing in eager mode, only the single machine code
# path is supported.
logging.info("Initializing local devices since in-graph multi-worker "
"training with `MirroredStrategy` is not supported in "
"eager mode. TF_CONFIG will be ignored when "
"when initializing `MirroredStrategy`.")
devices = devices or all_local_devices()
else:
devices = devices or all_devices()
assert devices, ("Got an empty `devices` list and unable to recognize "
"any local devices.")
self._collective_key_base = container_strategy._collective_key_base
self._communication_options = collective_util.Options(
implementation=collective_util.CommunicationImplementation.NCCL)
self._cross_device_ops = cross_device_ops
self._initialize_strategy(devices)
# TODO(b/128995245): Enable last partial batch support in graph mode.
if ops.executing_eagerly_outside_functions():
self.experimental_enable_get_next_as_optional = True
# Flag to turn on VariablePolicy.
self._use_var_policy = False
def _use_merge_call(self):
# We currently only disable merge_call when XLA is used to compile the `fn`
# passed to `strategy.run` and all devices are GPU.
return not control_flow_util.GraphOrParentsInXlaContext(
ops.get_default_graph()) or not all(
[_is_gpu_device(d) for d in self._devices])
def _initialize_strategy(self, devices):
# The _initialize_strategy method is intended to be used by distribute
# coordinator as well.
assert devices, "Must specify at least one device."
devices = tuple(device_util.resolve(d) for d in devices)
assert len(set(devices)) == len(devices), (
"No duplicates allowed in `devices` argument: %s" % (devices,))
self._initialize_single_worker(devices)
self._collective_ops = self._make_collective_ops_with_fallbacks()
# If cross_device_ops is not provided, set it to collective op by default.
if not self._cross_device_ops:
self._cross_device_ops = self._collective_ops
def _make_collective_ops_with_fallbacks(self):
self._collective_keys = cross_device_utils.CollectiveKeys(
group_key_start=1 + self._collective_key_base)
if not ops.executing_eagerly_outside_functions() and any(
"gpu" not in d.lower() for d in self._devices):
# In TF1/Session, fall back to ReductionToOneDevice() if there are
# non-GPU devices or virtual GPUs are used.
return cross_device_ops_lib.ReductionToOneDevice()
# Use ReductionToOneDevice() if mixed devices are used.
if any("cpu" in d.lower() for d in self._devices) and any(
"gpu" in d.lower() for d in self._devices):
return cross_device_ops_lib.ReductionToOneDevice()
if all("cpu" in d.lower() for d in self._devices):
# Use RING collective ops if all devices are CPU.
self._communication_options = collective_util.Options(
implementation=collective_util.CommunicationImplementation.RING)
else:
physical_gpus = context.context().list_physical_devices(device_type="GPU")
logical_gpus = context.context().list_logical_devices(device_type="GPU")
# Use RING collective ops if virtual devices are used.
if len(physical_gpus) < len(logical_gpus):
self._communication_options = collective_util.Options(
implementation=collective_util.CommunicationImplementation.RING)
# If all devices are physical GPU, use NCCL implementation.
return cross_device_ops_lib.CollectiveAllReduce(
devices=self._devices,
group_size=len(self._devices),
options=self._communication_options,
collective_keys=self._collective_keys)
def _initialize_single_worker(self, devices):
"""Initializes the object for single-worker training."""
self._devices = tuple(device_util.canonicalize(d) for d in devices)
self._input_workers_devices = (
(device_util.canonicalize("/device:CPU:0", devices[0]), devices),)
self._host_input_device = numpy_dataset.SingleDevice(
self._input_workers_devices[0][0])
device_spec = tf_device.DeviceSpec.from_string(
self._input_workers_devices[0][0])
# Ensures when we enter strategy.scope() we use the correct default device
if device_spec.job is not None and device_spec.job != "localhost":
self._default_device = "/job:%s/replica:%d/task:%d" % (
device_spec.job, device_spec.replica, device_spec.task)
logging.info("Using MirroredStrategy with devices %r", devices)
def _initialize_multi_worker(self, devices):
"""Initializes the object for multi-worker training."""
device_dict = _group_device_list(devices)
workers = []
worker_devices = []
for job in ("chief", "worker"):
for task in range(len(device_dict.get(job, []))):
worker = "/job:%s/task:%d" % (job, task)
workers.append(worker)
worker_devices.append((worker, device_dict[job][task]))
# Setting `_default_device` will add a device scope in the
# distribution.scope. We set the default device to the first worker. When
# users specify device under distribution.scope by
# with tf.device("/cpu:0"):
# ...
# their ops will end up on the cpu device of its first worker, e.g.
# "/job:worker/task:0/device:CPU:0". Note this is not used in replica mode.
self._default_device = workers[0]
self._host_input_device = numpy_dataset.SingleDevice(workers[0])
self._devices = tuple(devices)
self._input_workers_devices = worker_devices
self._is_multi_worker_training = True
if len(workers) > 1:
# Grandfather usage in the legacy tests if they're configured properly.
if (not isinstance(self._cross_device_ops,
cross_device_ops_lib.ReductionToOneDevice) or
self._cross_device_ops._num_between_graph_workers > 1): # pylint: disable=protected-access
raise ValueError(
"In-graph multi-worker training with `MirroredStrategy` is not "
"supported.")
self._inferred_cross_device_ops = self._cross_device_ops
else:
# TODO(yuefengz): make `select_cross_device_ops` work with device strings
# containing job names.
self._inferred_cross_device_ops = cross_device_ops_lib.NcclAllReduce()
logging.info("Using MirroredStrategy with remote devices %r", devices)
def _input_workers_with_options(self, options=None):
if not options:
return input_lib.InputWorkers(self._input_workers_devices)
if (options.experimental_replication_mode ==
distribute_lib.InputReplicationMode.PER_REPLICA):
if options.experimental_place_dataset_on_device:
self._input_workers_devices = (
tuple(
(device_util.canonicalize(d, d), (d,)) for d in self._devices))
else:
self._input_workers_devices = (
tuple((device_util.canonicalize("/device:CPU:0", d), (d,))
for d in self._devices))
return input_lib.InputWorkers(self._input_workers_devices)
else:
if not options.experimental_fetch_to_device:
return input_lib.InputWorkers([
(host_device, (host_device,) * len(compute_devices))
for host_device, compute_devices in self._input_workers_devices
])
else:
return input_lib.InputWorkers(self._input_workers_devices)
@property
def _input_workers(self):
return self._input_workers_with_options()
def _get_variable_creator_initial_value(self,
replica_id,
device,
primary_var,
**kwargs):
"""Return the initial value for variables on a replica."""
if replica_id == 0:
return kwargs["initial_value"]
else:
assert primary_var is not None
assert device is not None
assert kwargs is not None
def initial_value_fn():
if context.executing_eagerly() or ops.inside_function():
init_value = primary_var.value()
return array_ops.identity(init_value)
else:
with ops.device(device):
init_value = primary_var.initial_value
return array_ops.identity(init_value)
return initial_value_fn
def _create_variable(self, next_creator, **kwargs):
"""Create a mirrored variable. See `DistributionStrategy.scope`."""
colocate_with = kwargs.pop("colocate_with", None)
if colocate_with is None:
devices = self._devices
elif isinstance(colocate_with, numpy_dataset.SingleDevice):
with ops.device(colocate_with.device):
return next_creator(**kwargs)
else:
devices = colocate_with._devices # pylint: disable=protected-access
def _real_mirrored_creator(**kwargs): # pylint: disable=g-missing-docstring
value_list = []
for i, d in enumerate(devices):
with ops.device(d):
kwargs["initial_value"] = self._get_variable_creator_initial_value(
replica_id=i,
device=d,
primary_var=value_list[0] if value_list else None,
**kwargs)
if i > 0:
# Give replicas meaningful distinct names:
var0name = value_list[0].name.split(":")[0]
# We append a / to variable names created on replicas with id > 0 to
# ensure that we ignore the name scope and instead use the given
# name as the absolute name of the variable.
kwargs["name"] = "%s/replica_%d/" % (var0name, i)
with context.device_policy(context.DEVICE_PLACEMENT_SILENT):
# Don't record operations (e.g. other variable reads) during
# variable creation.
with record.stop_recording():
v = next_creator(**kwargs)
assert not isinstance(v, values.DistributedVariable)
value_list.append(v)
return value_list
return distribute_utils.create_mirrored_variable(
self._container_strategy(), _real_mirrored_creator,
distribute_utils.VARIABLE_CLASS_MAPPING,
distribute_utils.VARIABLE_POLICY_MAPPING, **kwargs)
def _validate_colocate_with_variable(self, colocate_with_variable):
distribute_utils.validate_colocate_distributed_variable(
colocate_with_variable, self)
def _make_dataset_iterator(self, dataset):
return input_lib_v1.DatasetIterator(
dataset,
self._input_workers,
self._container_strategy(),
num_replicas_in_sync=self._num_replicas_in_sync)
def _make_input_fn_iterator(
self,
input_fn,
replication_mode=distribute_lib.InputReplicationMode.PER_WORKER):
input_contexts = []
num_workers = self._input_workers.num_workers
for i in range(num_workers):
input_contexts.append(distribute_lib.InputContext(
num_input_pipelines=num_workers,
input_pipeline_id=i,
num_replicas_in_sync=self._num_replicas_in_sync))
return input_lib_v1.InputFunctionIterator(input_fn, self._input_workers,
input_contexts,
self._container_strategy())
def _experimental_distribute_dataset(self, dataset, options):
if (options and options.experimental_replication_mode ==
distribute_lib.InputReplicationMode.PER_REPLICA):
raise NotImplementedError(
"InputReplicationMode.PER_REPLICA "
"is only supported in "
"`distribute_datasets_from_function`."
)
return input_util.get_distributed_dataset(
dataset,
self._input_workers_with_options(options),
self._container_strategy(),
num_replicas_in_sync=self._num_replicas_in_sync,
options=options)
def _experimental_make_numpy_dataset(self, numpy_input, session):
return numpy_dataset.one_host_numpy_dataset(
numpy_input, self._host_input_device, session)
def _distribute_datasets_from_function(self, dataset_fn, options):
input_workers = self._input_workers_with_options(options)
input_contexts = []
num_workers = input_workers.num_workers
for i in range(num_workers):
input_contexts.append(distribute_lib.InputContext(
num_input_pipelines=num_workers,
input_pipeline_id=i,
num_replicas_in_sync=self._num_replicas_in_sync))
return input_util.get_distributed_datasets_from_function(
dataset_fn, input_workers, input_contexts, self._container_strategy(),
options)
def _experimental_distribute_values_from_function(self, value_fn):
per_replica_values = []
for replica_id in range(self._num_replicas_in_sync):
per_replica_values.append(value_fn(
distribute_lib.ValueContext(replica_id,
self._num_replicas_in_sync)))
return distribute_utils.regroup(per_replica_values, always_wrap=True)
# TODO(priyag): Deal with OutOfRange errors once b/111349762 is fixed.
def _experimental_run_steps_on_iterator(self, fn, iterator, iterations,
initial_loop_values=None):
if initial_loop_values is None:
initial_loop_values = {}
initial_loop_values = nest.flatten(initial_loop_values)
ctx = input_lib.MultiStepContext()
def body(i, *args):
"""A wrapper around `fn` to create the while loop body."""
del args
fn_result = fn(ctx, iterator.get_next())
for (name, output) in ctx.last_step_outputs.items():
# Convert all outputs to tensors, potentially from `DistributedValues`.
ctx.last_step_outputs[name] = self._local_results(output)
flat_last_step_outputs = nest.flatten(ctx.last_step_outputs)
with ops.control_dependencies([fn_result]):
return [i + 1] + flat_last_step_outputs
# We capture the control_flow_context at this point, before we run `fn`
# inside a while_loop. This is useful in cases where we might need to exit
# these contexts and get back to the outer context to do some things, for
# e.g. create an op which should be evaluated only once at the end of the
# loop on the host. One such usage is in creating metrics' value op.
self._outer_control_flow_context = (
ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access
cond = lambda i, *args: i < iterations
i = constant_op.constant(0)
loop_result = while_loop.while_loop(
cond,
body, [i] + initial_loop_values,
name="",
parallel_iterations=1,
back_prop=False,
swap_memory=False,
return_same_structure=True)
del self._outer_control_flow_context
ctx.run_op = control_flow_ops.group(loop_result)
# Convert the last_step_outputs from a list to the original dict structure
# of last_step_outputs.
last_step_tensor_outputs = loop_result[1:]
last_step_tensor_outputs_dict = nest.pack_sequence_as(
ctx.last_step_outputs, last_step_tensor_outputs)
for name, reduce_op in ctx._last_step_outputs_reduce_ops.items(): # pylint: disable=protected-access
output = last_step_tensor_outputs_dict[name]
# For outputs that have already been reduced, wrap them in a Mirrored
# container, else in a PerReplica container.
if reduce_op is None:
last_step_tensor_outputs_dict[name] = distribute_utils.regroup(output)
else:
assert len(output) == 1
last_step_tensor_outputs_dict[name] = output[0]
ctx._set_last_step_outputs(last_step_tensor_outputs_dict) # pylint: disable=protected-access
return ctx
def _broadcast_to(self, tensor, destinations):
# This is both a fast path for Python constants, and a way to delay
# converting Python values to a tensor until we know what type it
# should be converted to. Otherwise we have trouble with:
# global_step.assign_add(1)
# since the `1` gets broadcast as an int32 but global_step is int64.
if isinstance(tensor, (float, int)):
return tensor
# TODO(josh11b): In eager mode, use one thread per device, or async mode.
if not destinations:
# TODO(josh11b): Use current logical device instead of 0 here.
destinations = self._devices
return self._get_cross_device_ops(tensor).broadcast(tensor, destinations)
def _call_for_each_replica(self, fn, args, kwargs):
return mirrored_run.call_for_each_replica(
self._container_strategy(), fn, args, kwargs)
def _configure(self,
session_config=None,
cluster_spec=None,
task_type=None,
task_id=None):
del task_type, task_id
if session_config:
session_config.CopyFrom(self._update_config_proto(session_config))
if cluster_spec:
# TODO(yuefengz): remove the following code once cluster_resolver is
# added.
num_gpus_per_worker = _infer_num_gpus_per_worker(self._devices)
multi_worker_devices = _cluster_spec_to_device_list(
cluster_spec, num_gpus_per_worker)
self._initialize_multi_worker(multi_worker_devices)
def _update_config_proto(self, config_proto):
updated_config = copy.deepcopy(config_proto)
updated_config.isolate_session_state = True
return updated_config
def _get_cross_device_ops(self, value):
# Always use CollectiveAllReduce when XLA is enabled, since other cross
# device ops don't have as good support on XLA.
if not self._use_merge_call():
if not isinstance(self._cross_device_ops,
cross_device_ops_lib.CollectiveAllReduce):
logging.warning(
"Under XLA context, MirroredStrategy uses CollectiveAllReduce op. "
"Although %r is provided to initialize MirroredStrategy, it is "
"ignored in XLA. Please use CollectiveAllReduce(or default option) "
"in the future, since other cross device ops are not well "
"supported on XLA.", self._cross_device_ops
)
return self._collective_ops
if isinstance(value, values.DistributedValues):
value_int32 = True in {
dtypes.as_dtype(v.dtype) == dtypes.int32 for v in value.values
}
else:
value_int32 = dtypes.as_dtype(value.dtype) == dtypes.int32
if value_int32:
return cross_device_ops_lib.ReductionToOneDevice()
else:
return self._cross_device_ops
def _gather_to_implementation(self, value, destinations, axis, options):
if not isinstance(value, values.DistributedValues):
# ReductionToOneDevice._gather accepts DistributedValues only.
return value
return self._get_cross_device_ops(value)._gather( # pylint: disable=protected-access
value,
destinations=destinations,
axis=axis,
options=self._communication_options.merge(options))
def _reduce_to(self, reduce_op, value, destinations, options):
if (distribute_utils.is_mirrored(value) and
reduce_op == reduce_util.ReduceOp.MEAN):
return value
assert not distribute_utils.is_mirrored(value)
def get_values(value):
if not isinstance(value, values.DistributedValues):
# This function handles reducing values that are not PerReplica or
# Mirrored values. For example, the same value could be present on all
# replicas in which case `value` would be a single value or value could
# be 0.
return cross_device_ops_lib.reduce_non_distributed_value(
reduce_op, value, destinations, self._num_replicas_in_sync)
if self._use_merge_call() and (
not cross_device_ops_lib._devices_match(value, destinations) or # pylint: disable=protected-access
any("cpu" in d.lower()
for d in cross_device_ops_lib.get_devices_from(destinations))):
return cross_device_ops_lib.ReductionToOneDevice().reduce(
reduce_op, value, destinations)
return self._get_cross_device_ops(value).reduce(
reduce_op,
value,
destinations=destinations,
options=self._communication_options.merge(options))
return nest.map_structure(get_values, value)
def _batch_reduce_to(self, reduce_op, value_destination_pairs, options):
cross_device_ops = None
for value, _ in value_destination_pairs:
if cross_device_ops is None:
cross_device_ops = self._get_cross_device_ops(value)
elif cross_device_ops is not self._get_cross_device_ops(value):
raise ValueError("Inputs to batch_reduce_to must be either all on "
"the host or all on the compute devices.")
return cross_device_ops.batch_reduce(
reduce_op,
value_destination_pairs,
options=self._communication_options.merge(options))
def _update(self, var, fn, args, kwargs, group):
# TODO(josh11b): In eager mode, use one thread per device.
assert isinstance(var, values.DistributedVariable)
updates = []
for i, v in enumerate(var.values):
name = "update_%d" % i
with ops.device(v.device), \
distribute_lib.UpdateContext(i), \
ops.name_scope(name):
# If args and kwargs are not mirrored, the value is returned as is.
updates.append(
fn(v, *distribute_utils.select_replica(i, args),
**distribute_utils.select_replica(i, kwargs)))
return distribute_utils.update_regroup(self, updates, group)
def _replica_ctx_all_reduce(self, reduce_op, value, options=None):
"""Implements `StrategyExtendedV2._replica_ctx_all_reduce`."""
# This implementation avoids using `merge_call` and just launches collective
# ops in one replica.
if options is None:
options = collective_util.Options()
if context.executing_eagerly() or (
not tf2.enabled()) or self._use_merge_call():
# In eager mode, falls back to the default implementation that uses
# `merge_call`. Replica functions are running sequentially in eager mode,
# and due to the blocking nature of collective ops, execution will hang if
# collective ops are to be launched sequentially.
return super()._replica_ctx_all_reduce(reduce_op, value, options)
replica_context = distribute_lib.get_replica_context()
assert replica_context, (
"`StrategyExtended._replica_ctx_all_reduce` must be called in a "
"replica context")
return self._get_cross_device_ops(value)._all_reduce( # pylint: disable=protected-access
reduce_op,
value,
replica_context._replica_id, # pylint: disable=protected-access
options)
def _replica_ctx_update(self, var, fn, args, kwargs, group):
if self._use_merge_call():
return super()._replica_ctx_update(var, fn, args, kwargs, group)
replica_context = distribute_lib.get_replica_context()
assert replica_context
replica_id = values_util.get_current_replica_id_as_int()
name = "update_%d" % replica_id
if isinstance(var, values.DistributedVariable):
var = var._get_replica(replica_id) # pylint: disable=protected-access
with ops.device(var.device), ops.name_scope(name):
result = fn(var, *args, **kwargs)
return result
def _update_non_slot(self, colocate_with, fn, args, kwargs, group):
assert isinstance(colocate_with, tuple)
# TODO(josh11b): In eager mode, use one thread per device.
updates = []
for i, d in enumerate(colocate_with):
name = "update_%d" % i
with ops.device(d), distribute_lib.UpdateContext(i), ops.name_scope(name):
updates.append(
fn(*distribute_utils.select_replica(i, args),
**distribute_utils.select_replica(i, kwargs)))
return distribute_utils.update_regroup(self, updates, group)
def read_var(self, replica_local_var):
"""Read the aggregate value of a replica-local variable."""
# pylint: disable=protected-access
if distribute_utils.is_sync_on_read(replica_local_var):
return replica_local_var._get_cross_replica()
assert distribute_utils.is_mirrored(replica_local_var)
return array_ops.identity(replica_local_var._get())
# pylint: enable=protected-access
def value_container(self, val):
return distribute_utils.value_container(val)
@property
def _num_replicas_in_sync(self):
return len(self._devices)
@property
def worker_devices(self):
return self._devices
@property
def worker_devices_by_replica(self):
return [[d] for d in self._devices]
@property
def parameter_devices(self):
return self.worker_devices
@property
def experimental_between_graph(self):
return False
@property
def experimental_should_init(self):
return True
@property
def should_checkpoint(self):
return True
@property
def should_save_summary(self):
return True
def non_slot_devices(self, var_list):
del var_list
# TODO(josh11b): Should this be the last logical device instead?
return self._devices
# TODO(priyag): Delete this once all strategies use global batch size.
@property
def _global_batch_size(self):
"""`make_dataset_iterator` and `make_numpy_iterator` use global batch size.
`make_input_fn_iterator` assumes per-replica batching.
Returns:
Boolean.
"""
return True
def _in_multi_worker_mode(self):
"""Whether this strategy indicates working in multi-worker settings."""
return False
def _get_local_replica_id(self, replica_id_in_sync_group):
return replica_id_in_sync_group
def _get_replica_id_in_sync_group(self, replica_id):
return replica_id
| MirroredExtended |
python | doocs__leetcode | solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/Solution2.py | {
"start": 0,
"end": 307
} | class ____:
def longestSubarray(self, nums: List[int]) -> int:
ans = 0
cnt = j = 0
for i, x in enumerate(nums):
cnt += x ^ 1
while cnt > 1:
cnt -= nums[j] ^ 1
j += 1
ans = max(ans, i - j)
return ans
| Solution |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/cumulative_vrange_root/package.py | {
"start": 216,
"end": 671
} | class ____(Package):
"""Test that creating cumulative version ranges of the
form X.Y:X works and allows for the selection of all the
versions >= X.Y with major == X
"""
homepage = "https://www.example.org"
url = "https://example.org/files/v3.4/cmake-3.4.3.tar.gz"
version("1.0", md5="4cb3ff35b2472aae70f542116d616e63")
depends_on("cumulative-vrange-middle")
depends_on("cumulative-vrange-bottom@:2")
| CumulativeVrangeRoot |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 7415,
"end": 7697
} | class ____(GQLInput):
user_id: GQLId = Field(alias="userId")
project_id: GQLId = Field(alias="projectId")
user_project_role: str = Field(alias="userProjectRole")
client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
| UpdateProjectMemberInput |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/recurrent.py | {
"start": 69732,
"end": 81366
} | class ____(DropoutRNNCellMixin, Layer):
"""Cell class for the GRU layer.
Args:
units: Positive integer, dimensionality of the output space.
activation: Activation function to use.
Default: hyperbolic tangent (`tanh`).
If you pass None, no activation is applied
(ie. "linear" activation: `a(x) = x`).
recurrent_activation: Activation function to use
for the recurrent step.
Default: hard sigmoid (`hard_sigmoid`).
If you pass `None`, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias: Boolean, whether the layer uses a bias vector.
kernel_initializer: Initializer for the `kernel` weights matrix,
used for the linear transformation of the inputs.
recurrent_initializer: Initializer for the `recurrent_kernel`
weights matrix,
used for the linear transformation of the recurrent state.
bias_initializer: Initializer for the bias vector.
kernel_regularizer: Regularizer function applied to
the `kernel` weights matrix.
recurrent_regularizer: Regularizer function applied to
the `recurrent_kernel` weights matrix.
bias_regularizer: Regularizer function applied to the bias vector.
kernel_constraint: Constraint function applied to
the `kernel` weights matrix.
recurrent_constraint: Constraint function applied to
the `recurrent_kernel` weights matrix.
bias_constraint: Constraint function applied to the bias vector.
dropout: Float between 0 and 1.
Fraction of the units to drop for the linear transformation of the inputs.
recurrent_dropout: Float between 0 and 1.
Fraction of the units to drop for
the linear transformation of the recurrent state.
reset_after: GRU convention (whether to apply reset gate after or
before matrix multiplication). False = "before" (default),
True = "after" (CuDNN compatible).
Call arguments:
inputs: A 2D tensor.
states: List of state tensors corresponding to the previous timestep.
training: Python boolean indicating whether the layer should behave in
training mode or in inference mode. Only relevant when `dropout` or
`recurrent_dropout` is used.
"""
def __init__(self,
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.,
recurrent_dropout=0.,
reset_after=False,
**kwargs):
if units < 0:
raise ValueError(f'Received an invalid value for units, expected '
f'a positive integer, got {units}.')
# By default use cached variable under v2 mode, see b/143699808.
if ops.executing_eagerly_outside_functions():
self._enable_caching_device = kwargs.pop('enable_caching_device', True)
else:
self._enable_caching_device = kwargs.pop('enable_caching_device', False)
super(GRUCell, self).__init__(**kwargs)
self.units = units
self.activation = activations.get(activation)
self.recurrent_activation = activations.get(recurrent_activation)
self.use_bias = use_bias
self.kernel_initializer = initializers.get(kernel_initializer)
self.recurrent_initializer = initializers.get(recurrent_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.recurrent_regularizer = regularizers.get(recurrent_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.recurrent_constraint = constraints.get(recurrent_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.dropout = min(1., max(0., dropout))
self.recurrent_dropout = min(1., max(0., recurrent_dropout))
implementation = kwargs.pop('implementation', 1)
if self.recurrent_dropout != 0 and implementation != 1:
logging.debug(RECURRENT_DROPOUT_WARNING_MSG)
self.implementation = 1
else:
self.implementation = implementation
self.reset_after = reset_after
self.state_size = self.units
self.output_size = self.units
@tf_utils.shape_type_conversion
def build(self, input_shape):
input_dim = input_shape[-1]
default_caching_device = _caching_device(self)
self.kernel = self.add_weight(
shape=(input_dim, self.units * 3),
name='kernel',
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
caching_device=default_caching_device)
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units * 3),
name='recurrent_kernel',
initializer=self.recurrent_initializer,
regularizer=self.recurrent_regularizer,
constraint=self.recurrent_constraint,
caching_device=default_caching_device)
if self.use_bias:
if not self.reset_after:
bias_shape = (3 * self.units,)
else:
# separate biases for input and recurrent kernels
# Note: the shape is intentionally different from CuDNNGRU biases
# `(2 * 3 * self.units,)`, so that we can distinguish the classes
# when loading and converting saved weights.
bias_shape = (2, 3 * self.units)
self.bias = self.add_weight(shape=bias_shape,
name='bias',
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint,
caching_device=default_caching_device)
else:
self.bias = None
self.built = True
def call(self, inputs, states, training=None):
h_tm1 = states[0] if nest.is_nested(states) else states # previous memory
dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=3)
rec_dp_mask = self.get_recurrent_dropout_mask_for_cell(
h_tm1, training, count=3)
if self.use_bias:
if not self.reset_after:
input_bias, recurrent_bias = self.bias, None
else:
input_bias, recurrent_bias = array_ops_stack.unstack(self.bias)
if self.implementation == 1:
if 0. < self.dropout < 1.:
inputs_z = inputs * dp_mask[0]
inputs_r = inputs * dp_mask[1]
inputs_h = inputs * dp_mask[2]
else:
inputs_z = inputs
inputs_r = inputs
inputs_h = inputs
x_z = backend.dot(inputs_z, self.kernel[:, :self.units])
x_r = backend.dot(inputs_r, self.kernel[:, self.units:self.units * 2])
x_h = backend.dot(inputs_h, self.kernel[:, self.units * 2:])
if self.use_bias:
x_z = backend.bias_add(x_z, input_bias[:self.units])
x_r = backend.bias_add(x_r, input_bias[self.units: self.units * 2])
x_h = backend.bias_add(x_h, input_bias[self.units * 2:])
if 0. < self.recurrent_dropout < 1.:
h_tm1_z = h_tm1 * rec_dp_mask[0]
h_tm1_r = h_tm1 * rec_dp_mask[1]
h_tm1_h = h_tm1 * rec_dp_mask[2]
else:
h_tm1_z = h_tm1
h_tm1_r = h_tm1
h_tm1_h = h_tm1
recurrent_z = backend.dot(h_tm1_z, self.recurrent_kernel[:, :self.units])
recurrent_r = backend.dot(
h_tm1_r, self.recurrent_kernel[:, self.units:self.units * 2])
if self.reset_after and self.use_bias:
recurrent_z = backend.bias_add(recurrent_z, recurrent_bias[:self.units])
recurrent_r = backend.bias_add(
recurrent_r, recurrent_bias[self.units:self.units * 2])
z = self.recurrent_activation(x_z + recurrent_z)
r = self.recurrent_activation(x_r + recurrent_r)
# reset gate applied after/before matrix multiplication
if self.reset_after:
recurrent_h = backend.dot(
h_tm1_h, self.recurrent_kernel[:, self.units * 2:])
if self.use_bias:
recurrent_h = backend.bias_add(
recurrent_h, recurrent_bias[self.units * 2:])
recurrent_h = r * recurrent_h
else:
recurrent_h = backend.dot(
r * h_tm1_h, self.recurrent_kernel[:, self.units * 2:])
hh = self.activation(x_h + recurrent_h)
else:
if 0. < self.dropout < 1.:
inputs = inputs * dp_mask[0]
# inputs projected by all gate matrices at once
matrix_x = backend.dot(inputs, self.kernel)
if self.use_bias:
# biases: bias_z_i, bias_r_i, bias_h_i
matrix_x = backend.bias_add(matrix_x, input_bias)
x_z, x_r, x_h = array_ops.split(matrix_x, 3, axis=-1)
if self.reset_after:
# hidden state projected by all gate matrices at once
matrix_inner = backend.dot(h_tm1, self.recurrent_kernel)
if self.use_bias:
matrix_inner = backend.bias_add(matrix_inner, recurrent_bias)
else:
# hidden state projected separately for update/reset and new
matrix_inner = backend.dot(
h_tm1, self.recurrent_kernel[:, :2 * self.units])
recurrent_z, recurrent_r, recurrent_h = array_ops.split(
matrix_inner, [self.units, self.units, -1], axis=-1)
z = self.recurrent_activation(x_z + recurrent_z)
r = self.recurrent_activation(x_r + recurrent_r)
if self.reset_after:
recurrent_h = r * recurrent_h
else:
recurrent_h = backend.dot(
r * h_tm1, self.recurrent_kernel[:, 2 * self.units:])
hh = self.activation(x_h + recurrent_h)
# previous and candidate state mixed by update gate
h = z * h_tm1 + (1 - z) * hh
new_state = [h] if nest.is_nested(states) else h
return h, new_state
def get_config(self):
config = {
'units': self.units,
'activation': activations.serialize(self.activation),
'recurrent_activation':
activations.serialize(self.recurrent_activation),
'use_bias': self.use_bias,
'kernel_initializer': initializers.serialize(self.kernel_initializer),
'recurrent_initializer':
initializers.serialize(self.recurrent_initializer),
'bias_initializer': initializers.serialize(self.bias_initializer),
'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
'recurrent_regularizer':
regularizers.serialize(self.recurrent_regularizer),
'bias_regularizer': regularizers.serialize(self.bias_regularizer),
'kernel_constraint': constraints.serialize(self.kernel_constraint),
'recurrent_constraint':
constraints.serialize(self.recurrent_constraint),
'bias_constraint': constraints.serialize(self.bias_constraint),
'dropout': self.dropout,
'recurrent_dropout': self.recurrent_dropout,
'implementation': self.implementation,
'reset_after': self.reset_after
}
config.update(_config_for_enable_caching_device(self))
base_config = super(GRUCell, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype)
| GRUCell |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 42625,
"end": 47260
} | class ____(fixtures.TestBase):
"""tests for #8661
at the moment most of these are using the default setinputsizes enabled
behavior, with the exception of the plain executemany() calls for inserts.
"""
__only_on__ = "mssql"
__backend__ = True
@testing.combinations(
("unicode", True), ("ascii", False), argnames="unicode_", id_="ia"
)
@testing.combinations(
String,
Unicode,
NVARCHAR,
NTEXT,
Text,
UnicodeText,
argnames="datatype",
)
@testing.combinations(
100, 1999, 2000, 2001, 3999, 4000, 4001, 5000, argnames="length"
)
def test_long_strings_inpplace(
self, connection, unicode_, length, datatype
):
if datatype is NVARCHAR and length != "max" and length > 4000:
return
elif unicode_ and datatype not in (NVARCHAR, UnicodeText):
return
if datatype in (String, NVARCHAR):
dt = datatype(length)
else:
dt = datatype()
if length == "max":
length = 12000
if unicode_:
data = "réve🐍illé" * ((length // 9) + 1)
data = data[0 : (length // 2)]
else:
data = "abcdefg" * ((length // 7) + 1)
data = data[0:length]
assert len(data) == length
stmt = select(cast(literal(data, type_=dt), type_=dt))
result = connection.scalar(stmt)
eq_(result, data)
@testing.combinations(
("unicode", True), ("ascii", False), argnames="unicode_", id_="ia"
)
@testing.combinations(
("returning", True),
("noreturning", False),
argnames="use_returning",
id_="ia",
)
@testing.combinations(
# disabled due to #9603
# ("insertmany", True),
("insertsingle", False),
argnames="insertmany",
id_="ia",
)
@testing.combinations(
String,
Unicode,
NVARCHAR,
NTEXT,
Text,
UnicodeText,
argnames="datatype",
)
@testing.combinations(
100, 1999, 2000, 2001, 3999, 4000, 4001, 5000, "max", argnames="length"
)
def test_long_strings_in_context(
self,
connection,
metadata,
unicode_,
length,
datatype,
use_returning,
insertmany,
):
if datatype is NVARCHAR and length != "max" and length > 4000:
return
elif unicode_ and datatype not in (NVARCHAR, UnicodeText):
return
if datatype in (String, NVARCHAR):
dt = datatype(length)
else:
dt = datatype()
t = Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("data", dt),
)
t.create(connection)
if length == "max":
length = 12000
if unicode_:
data = "réve🐍illé" * ((length // 9) + 1)
data = data[0 : (length // 2)]
else:
data = "abcdefg" * ((length // 7) + 1)
data = data[0:length]
assert len(data) == length
if insertmany:
insert_data = [{"data": data}, {"data": data}, {"data": data}]
expected_data = [data, data, data]
else:
insert_data = {"data": data}
expected_data = [data]
if use_returning:
result = connection.execute(
t.insert().returning(t.c.data), insert_data
)
eq_(result.scalars().all(), expected_data)
else:
connection.execute(t.insert(), insert_data)
result = connection.scalars(select(t.c.data))
eq_(result.all(), expected_data)
# note that deprecate_large_types indicates that UnicodeText
# will be fulfilled by NVARCHAR, and not NTEXT. However if NTEXT
# is used directly, it isn't supported in WHERE clauses:
# "The data types ntext and (anything, including ntext itself) are
# incompatible in the equal to operator."
if datatype is NTEXT:
return
# test WHERE criteria
connection.execute(
t.insert(), [{"data": "some other data %d" % i} for i in range(3)]
)
result = connection.scalars(select(t.c.data).where(t.c.data == data))
eq_(result.all(), expected_data)
result = connection.scalars(
select(t.c.data).where(t.c.data != data).order_by(t.c.id)
)
eq_(result.all(), ["some other data %d" % i for i in range(3)])
| StringRoundTripTest |
python | fastai__fastai | fastai/data/load.py | {
"start": 3781,
"end": 11680
} | class ____(GetAttr):
_noop_methods = 'wif before_iter after_item before_batch after_batch after_iter'.split()
for o in _noop_methods: exec(f"def {o}(self, x=None, *args, **kwargs): return x")
_methods = _noop_methods + 'create_batches create_item create_batch retain \
get_idxs sample shuffle_fn do_batch create_batch'.split()
_default = 'dataset'
def __init__(self, dataset=None, bs=None, num_workers=0, pin_memory=False, timeout=0, batch_size=None,
shuffle=False, drop_last=False, indexed=None, n=None, device=None, persistent_workers=False,
pin_memory_device='', **kwargs):
if batch_size is not None: bs = batch_size # PyTorch compatibility
assert not (bs is None and drop_last)
if indexed is None: indexed = (hasattr(dataset,'__getitem__')
and not isinstance(dataset, IterableDataset))
if not indexed and shuffle: raise ValueError("Can only shuffle an indexed dataset (not an iterable one).")
if n is None:
try: n = len(dataset)
except TypeError: pass
store_attr('dataset,bs,shuffle,drop_last,indexed,n,pin_memory,timeout,device')
self.rng,self.num_workers,self.offs = random.Random(random.randint(0,2**32-1)),1,0
if sys.platform == "win32" and IN_NOTEBOOK and num_workers > 0: num_workers = 0
if sys.platform == "darwin" and num_workers > 0: num_workers = 0
self.fake_l = _FakeLoader(self, pin_memory, num_workers, timeout, persistent_workers=persistent_workers,
pin_memory_device=pin_memory_device)
def __len__(self):
if self.n is None: raise TypeError
if self.bs is None: return self.n
return self.n//self.bs + (0 if self.drop_last or self.n%self.bs==0 else 1)
def get_idxs(self):
idxs = Inf.count if self.indexed else Inf.nones
if self.n is not None: idxs = list(itertools.islice(idxs, self.n))
if self.shuffle: idxs = self.shuffle_fn(idxs)
return idxs
def sample(self):
return (b for i,b in enumerate(self.__idxs) if i//(self.bs or 1)%self.num_workers==self.offs)
def __iter__(self):
self.randomize()
self.before_iter()
self.__idxs=self.get_idxs() # called in context of main process (not workers/subprocesses)
for b in _loaders[self.fake_l.num_workers==0](self.fake_l):
# pin_memory causes tuples to be converted to lists, so convert them back to tuples
if self.pin_memory and type(b) == list: b = tuple(b)
if self.device is not None: b = to_device(b, self.device)
yield self.after_batch(b)
self.after_iter()
if hasattr(self, 'it'): del(self.it)
def create_batches(self, samps):
if self.dataset is not None: self.it = iter(self.dataset)
res = filter(lambda o:o is not None, map(self.do_item, samps))
yield from map(self.do_batch, self.chunkify(res))
def new(self, dataset=None, cls=None, **kwargs):
if dataset is None: dataset = self.dataset
if cls is None: cls = type(self)
cur_kwargs = dict(dataset=dataset, num_workers=self.fake_l.num_workers, pin_memory=self.pin_memory, timeout=self.timeout,
bs=self.bs, shuffle=self.shuffle, drop_last=self.drop_last, indexed=self.indexed, device=self.device)
for n in self._methods:
o = getattr(self, n)
if not isinstance(o, MethodType): cur_kwargs[n] = o
return cls(**merge(cur_kwargs, kwargs))
@property
def device(self) -> torch.device|None:
return self._device
@device.setter
def device(self, device:int|str|torch.device|None):
self._device, *_ = torch._C._nn._parse_to(device=device)
if hasattr(self, 'after_batch') and hasattr(self.after_batch, 'fs'):
for tfm in self.after_batch.fs:
# Check that tfm.to is callable as TabularPandas & transforms set tfm.to as an object
if hasattr(tfm, 'to') and callable(tfm.to): tfm.to(device)
else:
for a in L(getattr(tfm, 'parameters', None)):
if hasattr(getattr(tfm, a), 'to'): setattr(tfm, a, getattr(tfm, a).to(device))
@property
def prebatched(self): return self.bs is None
def do_item(self, s):
try: return self.after_item(self.create_item(s))
except SkipItemException: return None
def chunkify(self, b): return b if self.prebatched else chunked(b, self.bs, self.drop_last)
def shuffle_fn(self, idxs): return self.rng.sample(idxs, len(idxs))
def randomize(self): self.rng = random.Random(self.rng.randint(0,2**32-1))
def retain(self, res, b): return retain_types(res, b[0] if is_listy(b) else b)
def create_item(self, s):
if self.indexed: return self.dataset[s or 0]
elif s is None: return next(self.it)
else: raise IndexError("Cannot index an iterable dataset numerically - must use `None`.")
def create_batch(self, b):
try: return (fa_collate,fa_convert)[self.prebatched](b)
except Exception as e:
if not self.prebatched: collate_error(e,b)
raise
def do_batch(self, b): return self.retain(self.create_batch(self.before_batch(b)), b)
def to(self, device): self.device = device
def one_batch(self):
if self.n is not None and len(self)==0: raise ValueError(f'This DataLoader does not contain any batches')
with self.fake_l.no_multiproc(): res = first(self)
if hasattr(self, 'it'): delattr(self, 'it')
return res
# %% ../../nbs/02_data.load.ipynb 19
add_docs(DataLoader, "API compatible with PyTorch DataLoader, with a lot more callbacks and flexibility",
get_idxs = "Return a list of indices to reference the dataset. Calls `shuffle_fn` internally if `shuffle=True`.",
sample = "Same as `get_idxs` but returns a generator of indices to reference the dataset.",
create_batches = "Takes output of `sample` as input, and returns batches of data. Does not apply `after_batch`.",
new = "Create a new `DataLoader` with given arguments keeping remaining arguments same as original `DataLoader`.",
prebatched = "Check if `bs` is None.",
do_item = "Combines `after_item` and `create_item` to get an item from dataset by providing index as input.",
chunkify = "Used by `create_batches` to turn generator of items (`b`) into batches.",
shuffle_fn = "Returns a random permutation of `idxs`.",
randomize = "Set's `DataLoader` random number generator state.",
retain = "Cast each item of `res` to type of matching item in `b` if its a superclass.",
create_item = "Subset of the dataset containing the index values of sample if exists, else next iterator.",
create_batch = "Collate a list of items into a batch.",
do_batch = "Combines `create_batch` and `before_batch` to get a batch of items. Input is a list of items to collate.",
to = "Sets `self.device=device`.",
one_batch = "Return one batch from `DataLoader`.",
wif = "See pytorch `worker_init_fn` for details.",
before_iter = "Called before `DataLoader` starts to read/iterate over the dataset.",
after_item = "Takes output of `create_item` as input and applies this function on it.",
before_batch = "It is called before collating a list of items into a batch. Input is a list of items.",
after_batch = "After collating mini-batch of items, the mini-batch is passed through this function.",
after_iter = "Called after `DataLoader` has fully read/iterated over the dataset.")
| DataLoader |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.