language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/llama4/image_processing_llama4_fast.py | {
"start": 10571,
"end": 11303
} | class ____(ImagesKwargs, total=False):
r"""
max_patches (`int`, *optional*, defaults to 16):
The maximum number of patches to be extracted from the image.
Can be overridden by the `max_patches` parameter in the `preprocess` method.
resize_to_max_canvas (`bool`, *optional*, defaults to False):
Whether to resize the image to the maximum canvas size.
If True, picks the canvas the allows the largest resizing without distortion.
If False, downsample as little as possible, including no resizing at all,
but never upsample, unless the image is smaller than the patch size.
"""
max_patches: int
resize_to_max_canvas: bool
@auto_docstring
| Llama4ImageProcessorKwargs |
python | readthedocs__readthedocs.org | readthedocs/proxito/exceptions.py | {
"start": 4177,
"end": 4936
} | class ____(ContextualizedHttp404):
"""
Raised if a translation of a project was not found.
This means that the project does not exist for requested language.
If a page isn't found, raise a ProjectPageHttp404.
"""
template_name = "errors/proxito/404/no_project.html"
not_found_subject = pgettext_lazy("Names an object not found in a 404 error", "translation")
def __init__(self, project, **kwargs):
"""
Raised if a translation of a project was not found.
:param project: The project in which the translation could not be found
:param kwargs: Context dictionary of the rendered template
"""
kwargs["project"] = project
super().__init__(**kwargs)
| ProjectTranslationHttp404 |
python | jazzband__django-oauth-toolkit | oauth2_provider/contrib/rest_framework/permissions.py | {
"start": 349,
"end": 1908
} | class ____(BasePermission):
"""
The request is authenticated as a user and the token used has the right scope
"""
def has_permission(self, request, view):
token = request.auth
if not token:
return False
if hasattr(token, "scope"): # OAuth 2
required_scopes = self.get_scopes(request, view)
log.debug("Required scopes to access resource: {0}".format(required_scopes))
if token.is_valid(required_scopes):
return True
# Provide information about required scope?
include_required_scope = (
oauth2_settings.ERROR_RESPONSE_WITH_SCOPES
and required_scopes
and not token.is_expired()
and not token.allow_scopes(required_scopes)
)
if include_required_scope:
self.message = {
"detail": PermissionDenied.default_detail,
"required_scopes": list(required_scopes),
}
return False
assert False, (
"TokenHasScope requires the"
"`oauth2_provider.rest_framework.OAuth2Authentication` authentication "
"class to be used."
)
def get_scopes(self, request, view):
try:
return getattr(view, "required_scopes")
except AttributeError:
raise ImproperlyConfigured(
"TokenHasScope requires the view to define the required_scopes attribute"
)
| TokenHasScope |
python | huggingface__transformers | src/transformers/models/table_transformer/modeling_table_transformer.py | {
"start": 2034,
"end": 3522
} | class ____(BaseModelOutputWithCrossAttentions):
r"""
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=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 of the decoder's cross-attention layer, after the attention softmax,
used to compute the weighted average in the cross-attention heads.
intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
layernorm.
"""
intermediate_hidden_states: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for outputs of the TABLE_TRANSFORMER encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
"""
)
# Copied from transformers.models.detr.modeling_detr.DetrModelOutput with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
| TableTransformerDecoderOutput |
python | huggingface__transformers | src/transformers/models/bert_generation/modeling_bert_generation.py | {
"start": 11874,
"end": 12542
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
| BertGenerationIntermediate |
python | plotly__plotly.py | tests/test_optional/test_figure_factory/test_figure_factory.py | {
"start": 141257,
"end": 144901
} | class ____(NumpyTestUtilsMixin, TestCaseNoTemplate):
def test_wrong_coordinates(self):
a, b = np.mgrid[0:1:20j, 0:1:20j]
a = a.ravel()
b = b.ravel()
z = a * b
with self.assertRaises(
ValueError, msg="Barycentric coordinates should be positive."
):
_ = ff.create_ternary_contour(np.stack((a, b)), z)
mask = a + b <= 1.0
a = a[mask]
b = b[mask]
with self.assertRaises(ValueError):
_ = ff.create_ternary_contour(np.stack((a, b, a, b)), z)
with self.assertRaises(ValueError, msg="different number of values and points"):
_ = ff.create_ternary_contour(
np.stack((a, b, 1 - a - b)), np.concatenate((z, [1]))
)
# Different sums for different points
c = a
with self.assertRaises(ValueError):
_ = ff.create_ternary_contour(np.stack((a, b, c)), z)
# Sum of coordinates is different from one but is equal
# for all points.
with self.assertRaises(ValueError):
_ = ff.create_ternary_contour(np.stack((a, b, 2 - a - b)), z)
def test_simple_ternary_contour(self):
a, b = np.mgrid[0:1:20j, 0:1:20j]
mask = a + b < 1.0
a = a[mask].ravel()
b = b[mask].ravel()
c = 1 - a - b
z = a * b * c
fig = ff.create_ternary_contour(np.stack((a, b, c)), z)
fig2 = ff.create_ternary_contour(np.stack((a, b)), z)
np.testing.assert_array_almost_equal(
fig2["data"][0]["a"], fig["data"][0]["a"], decimal=3
)
def test_colorscale(self):
a, b = np.mgrid[0:1:20j, 0:1:20j]
mask = a + b < 1.0
a = a[mask].ravel()
b = b[mask].ravel()
c = 1 - a - b
z = a * b * c
z /= z.max()
fig = ff.create_ternary_contour(np.stack((a, b, c)), z, showscale=True)
fig2 = ff.create_ternary_contour(
np.stack((a, b, c)), z, showscale=True, showmarkers=True
)
assert isinstance(fig.data[-1]["marker"]["colorscale"], tuple)
assert isinstance(fig2.data[-1]["marker"]["colorscale"], tuple)
assert fig.data[-1]["marker"]["cmax"] == 1
assert fig2.data[-1]["marker"]["cmax"] == 1
def check_pole_labels(self):
a, b = np.mgrid[0:1:20j, 0:1:20j]
mask = a + b < 1.0
a = a[mask].ravel()
b = b[mask].ravel()
c = 1 - a - b
z = a * b * c
pole_labels = ["A", "B", "C"]
fig = ff.create_ternary_contour(np.stack((a, b, c)), z, pole_labels=pole_labels)
assert fig.layout.ternary.aaxis.title.text == pole_labels[0]
assert fig.data[-1].hovertemplate[0] == pole_labels[0]
def test_optional_arguments(self):
a, b = np.mgrid[0:1:20j, 0:1:20j]
mask = a + b <= 1.0
a = a[mask].ravel()
b = b[mask].ravel()
c = 1 - a - b
z = a * b * c
ncontours = 7
args = [
dict(showmarkers=False, showscale=False),
dict(showmarkers=True, showscale=False),
dict(showmarkers=False, showscale=True),
dict(showmarkers=True, showscale=True),
]
for arg_set in args:
fig = ff.create_ternary_contour(
np.stack((a, b, c)),
z,
interp_mode="cartesian",
ncontours=ncontours,
**arg_set,
)
# This test does not work for ilr interpolation
print(len(fig.data))
assert len(fig.data) == ncontours + 2 + arg_set["showscale"]
| TestTernarycontour |
python | streamlit__streamlit | lib/streamlit/runtime/runtime_util.py | {
"start": 2068,
"end": 3997
} | class ____(StreamlitAPIException):
"""Raised when a bad duration argument string is passed."""
def __init__(self, duration: str) -> None:
MarkdownFormattedException.__init__(
self,
"TTL string doesn't look right. It should be formatted as"
f"`'1d2h34m'` or `2 days`, for example. Got: {duration}",
)
def serialize_forward_msg(msg: ForwardMsg) -> bytes:
"""Serialize a ForwardMsg to send to a client.
If the message is too large, it will be converted to an exception message
instead.
"""
msg_str = msg.SerializeToString()
if len(msg_str) > get_max_message_size_bytes():
# Overwrite the offending ForwardMsg.delta with an error to display.
# This assumes that the size limit wasn't exceeded due to metadata.
from streamlit.elements import exception
msg_size_error = MessageSizeError(msg_str)
_LOGGER.warning(
"Websocket message size limit exceeded. Showing error to the user: %s",
msg_size_error,
)
exception.marshall(msg.delta.new_element.exception, msg_size_error)
# Deactivate caching for this error message:
msg.metadata.cacheable = False
msg_str = msg.SerializeToString()
return msg_str
# This needs to be initialized lazily to avoid calling config.get_option() and
# thus initializing config options when this file is first imported.
_max_message_size_bytes: int | None = None
def get_max_message_size_bytes() -> int:
"""Returns the max websocket message size in bytes.
This will lazyload the value from the config and store it in the global symbol table.
"""
global _max_message_size_bytes # noqa: PLW0603
if _max_message_size_bytes is None:
_max_message_size_bytes = config.get_option("server.maxMessageSize") * int(1e6)
return cast("int", _max_message_size_bytes)
| BadDurationStringError |
python | django__django | tests/gis_tests/geoapp/models.py | {
"start": 1140,
"end": 1391
} | class ____(models.Model):
city = models.CharField(max_length=30)
point = models.PointField()
class Meta:
unique_together = ("city", "point")
required_db_features = ["supports_geometry_field_unique_index"]
| UniqueTogetherModel |
python | numba__numba | numba/core/ssa.py | {
"start": 840,
"end": 6742
} | class ____:
def __init__(self):
self._saved = {}
def get(self, inst):
got = self._saved.get(inst)
if got is None:
self._saved[inst] = got = inst.list_vars()
return got
def _run_ssa(blocks):
"""Run SSA reconstruction on IR blocks of a function.
"""
if not blocks:
# Empty blocks?
return {}
# Run CFG on the blocks
cfg = compute_cfg_from_blocks(blocks)
df_plus = _iterated_domfronts(cfg)
# Find SSA violators
violators = _find_defs_violators(blocks, cfg)
# Make cache for .list_vars()
cache_list_vars = _CacheListVars()
# Process one SSA-violating variable at a time
for varname in violators:
_logger.debug(
"Fix SSA violator on var %s", varname,
)
# Fix up the LHS
# Put fresh variables for all assignments to the variable
blocks, defmap = _fresh_vars(blocks, varname)
_logger.debug("Replaced assignments: %s", _lazy_pformat(defmap))
# Fix up the RHS
# Re-associate the variable uses with the reaching definition
blocks = _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus,
cache_list_vars)
# Post-condition checks.
# CFG invariant
cfg_post = compute_cfg_from_blocks(blocks)
if cfg_post != cfg:
raise errors.CompilerError("CFG mutated in SSA pass")
return blocks
def _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus, cache_list_vars):
"""Rewrite all uses to ``varname`` given the definition map
"""
states = _make_states(blocks)
states['varname'] = varname
states['defmap'] = defmap
states['phimap'] = phimap = defaultdict(list)
states['cfg'] = cfg
states['phi_locations'] = _compute_phi_locations(df_plus, defmap)
newblocks = _run_block_rewrite(blocks, states, _FixSSAVars(cache_list_vars))
# insert phi nodes
for label, philist in phimap.items():
curblk = newblocks[label]
# Prepend PHI nodes to the block
curblk.body = philist + curblk.body
return newblocks
def _iterated_domfronts(cfg):
"""Compute the iterated dominance frontiers (DF+ in literatures).
Returns a dictionary which maps block label to the set of labels of its
iterated dominance frontiers.
"""
domfronts = {k: set(vs) for k, vs in cfg.dominance_frontier().items()}
keep_going = True
while keep_going:
keep_going = False
for k, vs in domfronts.items():
inner = reduce(operator.or_, [domfronts[v] for v in vs], set())
if inner.difference(vs):
vs |= inner
keep_going = True
return domfronts
def _compute_phi_locations(iterated_df, defmap):
# See basic algorithm in Ch 4.1 in Inria SSA Book
# Compute DF+(defs)
# DF of all DFs is the union of all DFs
phi_locations = set()
for deflabel, defstmts in defmap.items():
if defstmts:
phi_locations |= iterated_df[deflabel]
return phi_locations
def _fresh_vars(blocks, varname):
"""Rewrite to put fresh variable names
"""
states = _make_states(blocks)
states['varname'] = varname
states['defmap'] = defmap = defaultdict(list)
newblocks = _run_block_rewrite(blocks, states, _FreshVarHandler())
return newblocks, defmap
def _get_scope(blocks):
first, *_ = blocks.values()
return first.scope
def _find_defs_violators(blocks, cfg):
"""
Returns
-------
res : Set[str]
The SSA violators in a dictionary of variable names.
"""
defs = defaultdict(list)
uses = defaultdict(set)
states = dict(defs=defs, uses=uses)
_run_block_analysis(blocks, states, _GatherDefsHandler())
_logger.debug("defs %s", _lazy_pformat(defs))
# Gather violators by number of definitions.
# The violators are added by the order that they are seen and the algorithm
# scan from the first to the last basic-block as they occur in bytecode.
violators = OrderedSet([k for k, vs in defs.items() if len(vs) > 1])
# Gather violators by uses not dominated by the one def
doms = cfg.dominators()
for k, use_blocks in uses.items():
if k not in violators:
for label in use_blocks:
dom = doms[label]
def_labels = {label for _assign, label in defs[k] }
if not def_labels.intersection(dom):
violators.add(k)
break
_logger.debug("SSA violators %s", _lazy_pformat(violators))
return violators
def _run_block_analysis(blocks, states, handler):
for label, blk in blocks.items():
_logger.debug("==== SSA block analysis pass on %s", label)
states['label'] = label
for _ in _run_ssa_block_pass(states, blk, handler):
pass
def _run_block_rewrite(blocks, states, handler):
newblocks = {}
for label, blk in blocks.items():
_logger.debug("==== SSA block rewrite pass on %s", label)
newblk = ir.Block(scope=blk.scope, loc=blk.loc)
newbody = []
states['label'] = label
states['block'] = blk
for stmt in _run_ssa_block_pass(states, blk, handler):
assert stmt is not None
newbody.append(stmt)
newblk.body = newbody
newblocks[label] = newblk
return newblocks
def _make_states(blocks):
return dict(
scope=_get_scope(blocks),
)
def _run_ssa_block_pass(states, blk, handler):
_logger.debug("Running %s", handler)
for stmt in blk.body:
_logger.debug("on stmt: %s", stmt)
if isinstance(stmt, ir.Assign):
ret = handler.on_assign(states, stmt)
else:
ret = handler.on_other(states, stmt)
if ret is not stmt and ret is not None:
_logger.debug("replaced with: %s", ret)
yield ret
| _CacheListVars |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_legacy_tests.py | {
"start": 28338,
"end": 30416
} | class ____(TestCase):
class Schema:
site_dir = c.SiteDir()
docs_dir = c.Dir()
def test_doc_dir_in_site_dir(self):
j = os.path.join
# The parent dir is not the same on every system, so use the actual dir name
parent_dir = mkdocs.__file__.split(os.sep)[-3]
test_configs = (
{'docs_dir': j('site', 'docs'), 'site_dir': 'site'},
{'docs_dir': 'docs', 'site_dir': '.'},
{'docs_dir': '.', 'site_dir': '.'},
{'docs_dir': 'docs', 'site_dir': ''},
{'docs_dir': '', 'site_dir': ''},
{'docs_dir': j('..', parent_dir, 'docs'), 'site_dir': 'docs'},
{'docs_dir': 'docs', 'site_dir': '/'},
)
for test_config in test_configs:
with self.subTest(test_config):
with self.expect_error(
site_dir=re.compile(r"The 'docs_dir' should not be within the 'site_dir'.*")
):
self.get_config(self.Schema, test_config)
def test_site_dir_in_docs_dir(self):
j = os.path.join
test_configs = (
{'docs_dir': 'docs', 'site_dir': j('docs', 'site')},
{'docs_dir': '.', 'site_dir': 'site'},
{'docs_dir': '', 'site_dir': 'site'},
{'docs_dir': '/', 'site_dir': 'site'},
)
for test_config in test_configs:
with self.subTest(test_config):
with self.expect_error(
site_dir=re.compile(r"The 'site_dir' should not be within the 'docs_dir'.*")
):
self.get_config(self.Schema, test_config)
def test_common_prefix(self):
"""Legitimate settings with common prefixes should not fail validation."""
test_configs = (
{'docs_dir': 'docs', 'site_dir': 'docs-site'},
{'docs_dir': 'site-docs', 'site_dir': 'site'},
)
for test_config in test_configs:
with self.subTest(test_config):
self.get_config(self.Schema, test_config)
| SiteDirTest |
python | python__mypy | mypy/checker_shared.py | {
"start": 3451,
"end": 7681
} | class ____(CheckerPluginInterface):
plugin: Plugin
module_refs: set[str]
scope: CheckerScope
checking_missing_await: bool
allow_constructor_cache: bool
@property
@abstractmethod
def expr_checker(self) -> ExpressionCheckerSharedApi:
raise NotImplementedError
@abstractmethod
def named_type(self, name: str) -> Instance:
raise NotImplementedError
@abstractmethod
def lookup_typeinfo(self, fullname: str) -> TypeInfo:
raise NotImplementedError
@abstractmethod
def lookup_type(self, node: Expression) -> Type:
raise NotImplementedError
@abstractmethod
def handle_cannot_determine_type(self, name: str, context: Context) -> None:
raise NotImplementedError
@abstractmethod
def handle_partial_var_type(
self, typ: PartialType, is_lvalue: bool, node: Var, context: Context
) -> Type:
raise NotImplementedError
@overload
@abstractmethod
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
code: ErrorCode | None = None,
outer_context: Context | None = None,
) -> bool: ...
@overload
@abstractmethod
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: ErrorMessage,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
outer_context: Context | None = None,
) -> bool: ...
# Unfortunately, mypyc doesn't support abstract overloads yet.
@abstractmethod
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str | ErrorMessage,
subtype_label: str | None = None,
supertype_label: str | None = None,
*,
notes: list[str] | None = None,
code: ErrorCode | None = None,
outer_context: Context | None = None,
) -> bool:
raise NotImplementedError
@abstractmethod
def get_final_context(self) -> bool:
raise NotImplementedError
@overload
@abstractmethod
def conditional_types_with_intersection(
self,
expr_type: Type,
type_ranges: list[TypeRange] | None,
ctx: Context,
default: None = None,
) -> tuple[Type | None, Type | None]: ...
@overload
@abstractmethod
def conditional_types_with_intersection(
self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type
) -> tuple[Type, Type]: ...
# Unfortunately, mypyc doesn't support abstract overloads yet.
@abstractmethod
def conditional_types_with_intersection(
self,
expr_type: Type,
type_ranges: list[TypeRange] | None,
ctx: Context,
default: Type | None = None,
) -> tuple[Type | None, Type | None]:
raise NotImplementedError
@abstractmethod
def check_deprecated(self, node: Node | None, context: Context) -> None:
raise NotImplementedError
@abstractmethod
def warn_deprecated(self, node: Node | None, context: Context) -> None:
raise NotImplementedError
@abstractmethod
def type_is_iterable(self, type: Type) -> bool:
raise NotImplementedError
@abstractmethod
def iterable_item_type(
self, it: Instance | CallableType | TypeType | Overloaded, context: Context
) -> Type:
raise NotImplementedError
@abstractmethod
@contextmanager
def checking_await_set(self) -> Iterator[None]:
raise NotImplementedError
@abstractmethod
def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:
raise NotImplementedError
@abstractmethod
def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:
raise NotImplementedError
@abstractmethod
def is_defined_in_stub(self, typ: Instance, /) -> bool:
raise NotImplementedError
| TypeCheckerSharedApi |
python | pytorch__pytorch | tools/linter/adapters/grep_linter.py | {
"start": 547,
"end": 733
} | class ____(str, Enum):
ERROR = "error"
WARNING = "warning"
ADVICE = "advice"
DISABLED = "disabled"
LINTER_NAME: str = ""
ERROR_DESCRIPTION: str | None = None
| LintSeverity |
python | scipy__scipy | scipy/linalg/tests/test_special_matrices.py | {
"start": 4449,
"end": 7515
} | class ____:
def test_basic(self, xp):
dtype = xp.asarray(1).dtype
x = block_diag(xp.eye(2, dtype=dtype), xp.asarray([[1, 2], [3, 4], [5, 6]]),
xp.asarray([[1, 2, 3]]))
xp_assert_equal(x, xp.asarray([[1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0, 0],
[0, 0, 3, 4, 0, 0, 0],
[0, 0, 5, 6, 0, 0, 0],
[0, 0, 0, 0, 1, 2, 3]]))
def test_dtype(self, xp):
x = block_diag(xp.asarray([[1.5]]))
assert x.dtype == xp_default_dtype(xp)
x = block_diag(xp.asarray([[True]]))
assert x.dtype == xp.bool
def test_mixed_dtypes(self, xp):
actual = block_diag(xp.asarray([[1.]]), xp.asarray([[1j]]))
desired = xp.asarray([[1, 0], [0, 1j]])
xp_assert_equal(actual, desired)
def test_scalar_and_1d_args(self, xp):
a = block_diag(xp.asarray(1))
assert a.shape == (1, 1)
xp_assert_equal(a, xp.asarray([[1]]))
a = block_diag(xp.asarray([2, 3]), xp.asarray(4))
xp_assert_equal(a, xp.asarray([[2, 3, 0], [0, 0, 4]]))
def test_no_args(self):
a = block_diag()
assert a.ndim == 2
assert a.nbytes == 0
def test_empty_matrix_arg(self, xp):
# regression test for gh-4596: check the shape of the result
# for empty matrix inputs. Empty matrices are no longer ignored
# (gh-4908) it is viewed as a shape (1, 0) matrix.
dtype = xp.asarray(1).dtype
a = block_diag(xp.asarray([[1, 0], [0, 1]]),
xp.asarray([], dtype=dtype),
xp.asarray([[2, 3], [4, 5], [6, 7]]))
xp_assert_equal(a, xp.asarray([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 2, 3],
[0, 0, 4, 5],
[0, 0, 6, 7]]))
@pytest.mark.skip_xp_backends("dask.array", reason="dask/dask#11800")
def test_zerosized_matrix_arg(self, xp):
# test for gh-4908: check the shape of the result for
# zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0).
# note that [[]] takes shape (1,0)
dtype = xp.asarray(1).dtype
a = block_diag(xp.asarray([[1, 0], [0, 1]]),
xp.asarray([[]], dtype=dtype),
xp.asarray([[2, 3], [4, 5], [6, 7]]),
xp.zeros([0, 2], dtype=dtype))
xp_assert_equal(a, xp.asarray([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 2, 3, 0, 0],
[0, 0, 4, 5, 0, 0],
[0, 0, 6, 7, 0, 0]]))
| TestBlockDiag |
python | falconry__falcon | falcon/errors.py | {
"start": 19998,
"end": 23117
} | class ____(HTTPError):
"""405 Method Not Allowed.
The method received in the request-line is known by the origin
server but not supported by the target resource.
The origin server MUST generate an Allow header field in a 405
response containing a list of the target resource's currently
supported methods.
A 405 response is cacheable by default; i.e., unless otherwise
indicated by the method definition or explicit cache controls.
(See also: RFC 7231, Section 6.5.5)
`allowed_methods` is the only positional argument allowed,
the other arguments are defined as keyword-only.
Args:
allowed_methods (list of str): Allowed HTTP methods for this
resource (e.g., ``['GET', 'POST', 'HEAD']``).
Note:
If previously set, the Allow response header will be
overridden by this value.
Keyword Args:
title (str): Human-friendly error title. If not provided, and
`description` is also not provided, no body will be included
in the response.
description (str): Human-friendly description of the error, along with
a helpful suggestion or two (default ``None``).
headers (dict or list): A ``dict`` of header names and values
to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
*value* must be of type ``str`` or ``StringType``, and only
character values 0x00 through 0xFF may be used on platforms that
use wide characters.
Note:
The Content-Type header, if present, will be overridden. If
you wish to return custom error messages, you can create
your own HTTP error class, and install an error handler
to convert it into an appropriate HTTP response for the
client
Note:
Falcon can process a list of ``tuple`` slightly faster
than a ``dict``.
href (str): A URL someone can visit to find out more information
(default ``None``). Unicode characters are percent-encoded.
href_text (str): If href is given, use this as the friendly
title/description for the link (default 'API documentation
for this error').
code (int): An internal code that customers can reference in their
support request or to help them when searching for knowledge
base articles related to this error (default ``None``).
"""
def __init__(
self,
allowed_methods: Iterable[str],
*,
title: str | None = None,
description: str | None = None,
headers: HeaderArg | None = None,
**kwargs: HTTPErrorKeywordArguments,
):
headers = _load_headers(headers)
headers['Allow'] = ', '.join(allowed_methods)
super().__init__(
status.HTTP_405,
title=title,
description=description,
headers=headers,
**kwargs, # type: ignore[arg-type]
)
| HTTPMethodNotAllowed |
python | dask__distributed | distributed/_concurrent_futures_thread.py | {
"start": 2864,
"end": 5530
} | class ____(_base.Executor):
# Used to assign unique thread names when thread_name_prefix is not supplied.
_counter = itertools.count()
def __init__(self, max_workers=None, thread_name_prefix=""):
"""Initializes a new ThreadPoolExecutor instance.
Args:
max_workers: The maximum number of threads that can be used to
execute the given calls.
thread_name_prefix: An optional name prefix to give our threads.
"""
if max_workers is None:
# Use this number because ThreadPoolExecutor is often
# used to overlap I/O instead of CPU work.
max_workers = (os.cpu_count() or 1) * 5
if max_workers <= 0:
raise ValueError("max_workers must be greater than 0")
self._max_workers = max_workers
self._work_queue = queue.Queue()
self._threads = set()
self._shutdown = False
self._shutdown_lock = threading.Lock()
self._thread_name_prefix = thread_name_prefix or (
"ThreadPoolExecutor-%d" % next(self._counter)
)
def submit(self, fn, *args, **kwargs):
with self._shutdown_lock:
if self._shutdown: # pragma: no cover
raise RuntimeError("cannot schedule new futures after shutdown")
f = _base.Future()
w = _WorkItem(f, fn, args, kwargs)
self._work_queue.put(w)
self._adjust_thread_count()
return f
submit.__doc__ = _base.Executor.submit.__doc__
def _adjust_thread_count(self):
# When the executor gets lost, the weakref callback will wake up
# the worker threads.
def weakref_cb(_, q=self._work_queue):
q.put(None)
# TODO(bquinlan): Should avoid creating new threads if there are more
# idle threads than items in the work queue.
num_threads = len(self._threads)
if num_threads < self._max_workers:
thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)
t = threading.Thread(
name=thread_name,
target=_worker,
args=(weakref.ref(self, weakref_cb), self._work_queue),
)
t.daemon = True
t.start()
self._threads.add(t)
_threads_queues[t] = self._work_queue
def shutdown(self, wait=True):
with self._shutdown_lock:
self._shutdown = True
self._work_queue.put(None)
if wait:
for t in self._threads:
t.join()
shutdown.__doc__ = _base.Executor.shutdown.__doc__
| ThreadPoolExecutor |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 115215,
"end": 116549
} | class ____(TensorLikePair):
"""Pair for tensor-like inputs.
On the one hand this class is stricter than the builtin :class:`TensorLikePair` since it only allows instances of
:class:`torch.Tensor` and :class:`numpy.ndarray` rather than allowing any tensor-like than can be converted into a
tensor. On the other hand this class is looser since it converts all inputs into tensors with no regard of their
relationship, e.g. comparing a :class:`torch.Tensor` to :class:`numpy.ndarray` is fine.
In addition, this class supports overriding the absolute and relative tolerance through the ``@precisionOverride``
and ``@toleranceOverride`` decorators.
"""
def __init__(self, actual, expected, *, rtol_override=0.0, atol_override=0.0, **other_parameters):
super().__init__(actual, expected, **other_parameters)
self.rtol = max(self.rtol, rtol_override)
self.atol = max(self.atol, atol_override)
def _process_inputs(self, actual, expected, *, id, allow_subclasses):
self._check_inputs_isinstance(actual, expected, cls=(torch.Tensor, np.ndarray))
actual, expected = (self._to_tensor(input) for input in (actual, expected))
for tensor in (actual, expected):
self._check_supported(tensor, id=id)
return actual, expected
| TensorOrArrayPair |
python | tensorflow__tensorflow | tensorflow/python/saved_model/save_test.py | {
"start": 39557,
"end": 41392
} | class ____(test.TestCase):
def testFromObj(self):
self.assertEqual(save_options.VariablePolicy.NONE,
save_options.VariablePolicy.from_obj(None))
self.assertEqual(
save_options.VariablePolicy.SAVE_VARIABLE_DEVICES,
save_options.VariablePolicy.from_obj(
save_options.VariablePolicy.SAVE_VARIABLE_DEVICES))
self.assertEqual(
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES,
save_options.VariablePolicy.from_obj(
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES))
self.assertEqual(
save_options.VariablePolicy.SAVE_VARIABLE_DEVICES,
save_options.VariablePolicy.from_obj("save_variable_devices"))
self.assertEqual(
save_options.VariablePolicy.SAVE_VARIABLE_DEVICES,
save_options.VariablePolicy.from_obj("SaVe_VaRiAbLe_DeViCeS"))
self.assertEqual(
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES,
save_options.VariablePolicy.from_obj("expand_distributed_variables"))
self.assertEqual(
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES,
save_options.VariablePolicy.from_obj("eXpAnD_dIsTrIbUtEd_VaRiAbLeS"))
for invalid in ["not_a_valid_value", 2.0, []]:
with self.assertRaisesRegex(ValueError, "invalid VariablePolicy value"):
save_options.VariablePolicy.from_obj(invalid)
def testNamingConvention(self):
"""Enforces names are uppercase versions of values."""
for policy in save_options.VariablePolicy:
if policy == save_options.VariablePolicy.NONE:
self.assertIsNone(policy.value)
else:
self.assertEqual(policy.name, policy.name.upper())
self.assertEqual(policy.value, policy.value.lower())
self.assertEqual(policy.name, policy.value.upper())
| VariablePolicyEnumTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/messages/message_batch_errored_result.py | {
"start": 252,
"end": 351
} | class ____(BaseModel):
error: ErrorResponse
type: Literal["errored"]
| MessageBatchErroredResult |
python | pytorch__pytorch | test/distributed/pipelining/schedule_registry.py | {
"start": 3253,
"end": 4983
} | class ____(PipelineScheduleMulti):
n_stages = 4
num_microbatches = 2
rank_stages = {
0: [0, 2],
1: [1, 3],
}
def __init__(
self,
stages: list[_PipelineStageBase],
n_microbatches: int,
loss_fn: Optional[Callable] = None,
enable_zero_bubble: bool = True,
scale_grads: bool = True,
):
super().__init__(
stages=stages,
n_microbatches=n_microbatches,
loss_fn=loss_fn,
scale_grads=scale_grads,
)
# Needs to be updated as part of all schedules using "W"
self.use_full_backward = False
# Go through two microbatches
self.pipeline_order = {
0: [
_Action(0, F, 0),
_Action(0, F, 1),
_Action(2, F, 0),
_Action(2, F, 1),
None,
_Action(2, I, 0),
_Action(2, W, 0),
_Action(0, I, 0),
_Action(2, I, 1),
_Action(0, W, 0),
_Action(0, I, 1),
_Action(2, W, 1),
_Action(0, W, 1),
],
1: [
None,
_Action(1, F, 0),
_Action(1, F, 1),
_Action(3, F, 0),
_Action(3, I, 0),
_Action(3, F, 1),
_Action(1, I, 0),
_Action(3, I, 1),
_Action(3, W, 0),
_Action(1, I, 1),
_Action(1, W, 0),
_Action(3, W, 1),
_Action(1, W, 1),
],
}
self._validate_and_set_stage_mapping(self.pipeline_order)
| ScheduleWithW |
python | getsentry__sentry | src/sentry/feedback/migrations/0007_cleanup_failed_safe_deletes.py | {
"start": 207,
"end": 1671
} | 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 = False
dependencies = [
("feedback", "0006_safe_del_feedback_model"),
]
operations = [
# Clean up table that may not have been deleted due to missing
# historical_silo_assignments entry before the fix
SafeRunSQL(
sql="DROP TABLE IF EXISTS feedback_feedback CASCADE;",
reverse_sql=migrations.RunSQL.noop,
hints={"tables": ["feedback_feedback"]},
),
]
| Migration |
python | pytest-dev__pytest | testing/_py/test_local.py | {
"start": 32717,
"end": 37186
} | class ____:
@pytest.fixture(autouse=True)
def preserve_sys(self):
with mock.patch.dict(sys.modules):
with mock.patch.object(sys, "path", list(sys.path)):
yield
def test_pyimport(self, path1):
obj = path1.join("execfile.py").pyimport()
assert obj.x == 42
assert obj.__name__ == "execfile"
def test_pyimport_renamed_dir_creates_mismatch(self, tmpdir, monkeypatch):
p = tmpdir.ensure("a", "test_x123.py")
p.pyimport()
tmpdir.join("a").move(tmpdir.join("b"))
with pytest.raises(tmpdir.ImportMismatchError):
tmpdir.join("b", "test_x123.py").pyimport()
# Errors can be ignored.
monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "1")
tmpdir.join("b", "test_x123.py").pyimport()
# PY_IGNORE_IMPORTMISMATCH=0 does not ignore error.
monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "0")
with pytest.raises(tmpdir.ImportMismatchError):
tmpdir.join("b", "test_x123.py").pyimport()
def test_pyimport_messy_name(self, tmpdir):
# http://bitbucket.org/hpk42/py-trunk/issue/129
path = tmpdir.ensure("foo__init__.py")
path.pyimport()
def test_pyimport_dir(self, tmpdir):
p = tmpdir.join("hello_123")
p_init = p.ensure("__init__.py")
m = p.pyimport()
assert m.__name__ == "hello_123"
m = p_init.pyimport()
assert m.__name__ == "hello_123"
def test_pyimport_execfile_different_name(self, path1):
obj = path1.join("execfile.py").pyimport(modname="0x.y.z")
assert obj.x == 42
assert obj.__name__ == "0x.y.z"
def test_pyimport_a(self, path1):
otherdir = path1.join("otherdir")
mod = otherdir.join("a.py").pyimport()
assert mod.result == "got it"
assert mod.__name__ == "otherdir.a"
def test_pyimport_b(self, path1):
otherdir = path1.join("otherdir")
mod = otherdir.join("b.py").pyimport()
assert mod.stuff == "got it"
assert mod.__name__ == "otherdir.b"
def test_pyimport_c(self, path1):
otherdir = path1.join("otherdir")
mod = otherdir.join("c.py").pyimport()
assert mod.value == "got it"
def test_pyimport_d(self, path1):
otherdir = path1.join("otherdir")
mod = otherdir.join("d.py").pyimport()
assert mod.value2 == "got it"
def test_pyimport_and_import(self, tmpdir):
tmpdir.ensure("xxxpackage", "__init__.py")
mod1path = tmpdir.ensure("xxxpackage", "module1.py")
mod1 = mod1path.pyimport()
assert mod1.__name__ == "xxxpackage.module1"
from xxxpackage import module1
assert module1 is mod1
def test_pyimport_check_filepath_consistency(self, monkeypatch, tmpdir):
name = "pointsback123"
ModuleType = type(os)
p = tmpdir.ensure(name + ".py")
with monkeypatch.context() as mp:
for ending in (".pyc", "$py.class", ".pyo"):
mod = ModuleType(name)
pseudopath = tmpdir.ensure(name + ending)
mod.__file__ = str(pseudopath)
mp.setitem(sys.modules, name, mod)
newmod = p.pyimport()
assert mod == newmod
mod = ModuleType(name)
pseudopath = tmpdir.ensure(name + "123.py")
mod.__file__ = str(pseudopath)
monkeypatch.setitem(sys.modules, name, mod)
excinfo = pytest.raises(pseudopath.ImportMismatchError, p.pyimport)
modname, modfile, orig = excinfo.value.args
assert modname == name
assert modfile == pseudopath
assert orig == p
assert issubclass(pseudopath.ImportMismatchError, ImportError)
def test_issue131_pyimport_on__init__(self, tmpdir):
# __init__.py files may be namespace packages, and thus the
# __file__ of an imported module may not be ourselves
# see issue
p1 = tmpdir.ensure("proja", "__init__.py")
p2 = tmpdir.ensure("sub", "proja", "__init__.py")
m1 = p1.pyimport()
m2 = p2.pyimport()
assert m1 == m2
def test_ensuresyspath_append(self, tmpdir):
root1 = tmpdir.mkdir("root1")
file1 = root1.ensure("x123.py")
assert str(root1) not in sys.path
file1.pyimport(ensuresyspath="append")
assert str(root1) == sys.path[-1]
assert str(root1) not in sys.path[:-1]
| TestImport |
python | scrapy__scrapy | tests/spiders.py | {
"start": 12780,
"end": 13308
} | class ____(CrawlSpiderWithParseMethod):
"""A CrawlSpider with an async def callback"""
name = "crawl_spider_with_async_callback"
rules = (Rule(LinkExtractor(), callback="parse_async", follow=True),)
async def parse_async(self, response, foo=None):
self.logger.info("[parse_async] status %i (foo: %s)", response.status, foo)
return Request(
self.mockserver.url("/status?n=202"),
self.parse_async,
cb_kwargs={"foo": "bar"},
)
| CrawlSpiderWithAsyncCallback |
python | spack__spack | var/spack/test_repos/spack_repo/flags_test/packages/w/package.py | {
"start": 216,
"end": 504
} | class ____(Package):
version("3.1")
version("3.0")
variant("moveflaglater", default=False)
depends_on("x +activatemultiflag")
depends_on('y cflags="-d0"', when="~moveflaglater")
depends_on('y cflags="-d3"', when="+moveflaglater")
depends_on("c", type="build")
| W |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/baidu/tests.py | {
"start": 238,
"end": 610
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = BaiduProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{"portrait": "78c0e9839de59bbde7859ccf43",
"uname": "\u90dd\u56fd\u715c", "uid": "3225892368"}""",
)
def get_expected_to_str(self):
return "\u90dd\u56fd\u715c"
| BaiduTests |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 636731,
"end": 638007
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("id", "stargazer_count", "stargazers", "viewer_has_starred")
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
stargazer_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="stargazerCount"
)
stargazers = sgqlc.types.Field(
sgqlc.types.non_null(StargazerConnection),
graphql_name="stargazers",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(StarOrder, graphql_name="orderBy", default=None),
),
)
),
)
viewer_has_starred = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="viewerHasStarred"
)
| Starrable |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py | {
"start": 24033,
"end": 25120
} | class ____(CheckSection):
header = "Changelog"
def check_section(self, connector: Connector) -> List[str]:
documentation = DocumentationContent(connector=connector)
if self.header not in documentation.headers:
if self.required:
return [f"Documentation does not have {self.header} section."]
return []
errors = []
expected = TemplateContent(connector.name_from_metadata).section(self.header)[self.expected_section_index] # type: ignore
actual_contents = documentation.section(self.header)
if actual_contents is None:
return [f"Documentation {self.header} section is empty"]
if len(actual_contents) > 1:
return [f"Documentation has more than one {self.header} section. Please check it."]
actual = prepare_changelog_to_compare(actual_contents[0])[: len(expected)]
if actual != expected:
errors = list(ndiff(actual.splitlines(keepends=True), expected.splitlines(keepends=True)))
return errors
| CheckChangelogSectionContent |
python | jina-ai__jina | tests/integration/v2_api/test_yaml_dump_load.py | {
"start": 124,
"end": 1646
} | class ____(Executor):
def __init__(self, bar: str, bar2: int = 3, **kwargs):
super().__init__(**kwargs)
self.bar = bar
self.bar2 = bar2
@requests(on=['/foo', '/foo2'])
def foo(self, docs, **kwargs):
for d in docs:
d.text = '/foo'
@requests
def bar(self, docs, **kwargs):
for d in docs:
d.text = '/bar'
def random(self, docs, **kwargs):
for d in docs:
d.text = '/random'
y = """
jtype: MyExec
with:
bar: hello
bar2: 1
metas:
name: my-awesomeness
description: this is an awesome executor
requests:
/foo_endpoint: foo
/random_endpoint: random
"""
def test_load_save_yml(tmp_path):
m = Executor.load_config(y)
m.save_config(os.path.join(tmp_path, 'a.yml'))
assert m.bar == 'hello'
assert m.bar2 == 1
assert m.metas.name == 'my-awesomeness'
for k in ('/default', '/foo_endpoint', '/random_endpoint'):
assert k in m.requests
@pytest.mark.parametrize(
'req_endpoint, doc_text',
[
('/foo', '/foo'),
('/foo2', '/bar'),
('/foo3', '/bar'),
('/foo_endpoint', '/foo'),
('/random_endpoint', '/random'),
('/bar', '/bar'),
],
)
def test_load_yaml_route(req_endpoint, doc_text):
port = random_port()
f = Flow(port=port).add(uses=y)
c = Client(port=f.port)
with f:
results = c.post(req_endpoint, Document(), return_responses=True)
assert results[0].docs[0].text == doc_text
| MyExec |
python | redis__redis-py | redis/multidb/exception.py | {
"start": 373,
"end": 513
} | class ____(Exception):
"""Exception raised when all databases in setup are temporary unavailable."""
pass
| TemporaryUnavailableException |
python | pytorch__pytorch | test/test_sparse_csr.py | {
"start": 4837,
"end": 6945
} | class ____(TestCase):
def test_make_crow_indices(self):
# Here we test the correctness of the crow_indices algorithm
# and testing it on CPU and with int32 dtype will be
# sufficient.
device = torch.device('cpu')
index_dtype = torch.int32
for n_rows in range(1, 10):
for n_cols in range(1, 10):
for nnz in range(n_rows * n_cols + 1):
crow_indices = self._make_crow_indices(
n_rows, n_cols, nnz,
device=device, dtype=index_dtype)
self.assertEqual(len(crow_indices), n_rows + 1)
counts = crow_indices[1:] - crow_indices[:-1]
self.assertEqual(counts.sum(), nnz)
self.assertGreaterEqual(counts.min(), 0)
self.assertLessEqual(counts.max(), n_cols)
def all_sparse_compressed_layouts(test_name='layout'):
return parametrize(test_name, [
subtest(torch.sparse_csr, name='SparseCSR'),
subtest(torch.sparse_csc, name='SparseCSC'),
subtest(torch.sparse_bsr, name='SparseBSR'),
subtest(torch.sparse_bsc, name='SparseBSC')])
def sparse_compressed_nonblock_layouts(test_name='layout'):
return parametrize(test_name, [
subtest(torch.sparse_csr, name='SparseCSR'),
subtest(torch.sparse_csc, name='SparseCSC')])
sparse_compressed_indices_methods = {
torch.sparse_csr: (torch.Tensor.crow_indices, torch.Tensor.col_indices),
torch.sparse_csc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices),
torch.sparse_bsr: (torch.Tensor.crow_indices, torch.Tensor.col_indices),
torch.sparse_bsc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices),
}
def batched_nonbatched(test_name='batched'):
return parametrize(test_name, [
subtest(True, name="Batched"),
subtest(False, name="NonBatched")
])
def hybrid_nonhybrid(test_name='hybrid'):
return parametrize(test_name, [
subtest(True, name="Hybrid"),
subtest(False, name="NonHybrid")
])
| TestSparseCSRSampler |
python | lepture__authlib | tests/flask/test_oauth2/rfc9068/test_token_generation.py | {
"start": 1580,
"end": 7141
} | class ____(CodeGrantMixin, _AuthorizationCodeGrant):
TOKEN_ENDPOINT_AUTH_METHODS = ["client_secret_basic", "client_secret_post", "none"]
def save_authorization_code(self, code, request):
return save_authorization_code(code, request)
def test_generate_jwt_access_token(test_client, client, user, jwks):
res = test_client.post(
"/oauth/authorize",
data={
"response_type": client.response_types[0],
"client_id": client.client_id,
"redirect_uri": client.redirect_uris[0],
"scope": client.scope,
"user_id": user.id,
},
)
params = dict(url_decode(urlparse.urlparse(res.location).query))
code = params["code"]
res = test_client.post(
"/oauth/token",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": client.client_id,
"client_secret": client.client_secret,
"scope": " ".join(client.scope),
"redirect_uri": client.redirect_uris[0],
},
)
access_token = res.json["access_token"]
claims = jwt.decode(access_token, jwks)
assert claims["iss"] == issuer
assert claims["sub"] == user.id
assert claims["scope"] == client.scope
assert claims["client_id"] == client.client_id
# This specification registers the 'application/at+jwt' media type, which can
# be used to indicate that the content is a JWT access token. JWT access tokens
# MUST include this media type in the 'typ' header parameter to explicitly
# declare that the JWT represents an access token complying with this profile.
# Per the definition of 'typ' in Section 4.1.9 of [RFC7515], it is RECOMMENDED
# that the 'application/' prefix be omitted. Therefore, the 'typ' value used
# SHOULD be 'at+jwt'.
assert claims.header["typ"] == "at+jwt"
def test_generate_jwt_access_token_extra_claims(
test_client, token_generator, user, client, jwks
):
"""Authorization servers MAY return arbitrary attributes not defined in any
existing specification, as long as the corresponding claim names are collision
resistant or the access tokens are meant to be used only within a private
subsystem. Please refer to Sections 4.2 and 4.3 of [RFC7519] for details.
"""
def get_extra_claims(client, grant_type, user, scope):
return {"username": user.username}
token_generator.get_extra_claims = get_extra_claims
res = test_client.post(
"/oauth/authorize",
data={
"response_type": client.response_types[0],
"client_id": client.client_id,
"redirect_uri": client.redirect_uris[0],
"scope": client.scope,
"user_id": user.id,
},
)
params = dict(url_decode(urlparse.urlparse(res.location).query))
code = params["code"]
res = test_client.post(
"/oauth/token",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": client.client_id,
"client_secret": client.client_secret,
"scope": " ".join(client.scope),
"redirect_uri": client.redirect_uris[0],
},
)
access_token = res.json["access_token"]
claims = jwt.decode(access_token, jwks)
assert claims["username"] == user.username
@pytest.mark.skip
def test_generate_jwt_access_token_no_user(test_client, client, user, jwks):
res = test_client.post(
"/oauth/authorize",
data={
"response_type": client.response_types[0],
"client_id": client.client_id,
"redirect_uri": client.redirect_uris[0],
"scope": client.scope,
#'user_id': user.id,
},
)
params = dict(url_decode(urlparse.urlparse(res.location).query))
code = params["code"]
res = test_client.post(
"/oauth/token",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": client.client_id,
"client_secret": client.client_secret,
"scope": " ".join(client.scope),
"redirect_uri": client.redirect_uris[0],
},
)
access_token = res.json["access_token"]
claims = jwt.decode(access_token, jwks)
assert claims["sub"] == client.client_id
def test_optional_fields(test_client, token_generator, user, client, jwks):
token_generator.get_auth_time = lambda *args: 1234
token_generator.get_amr = lambda *args: "amr"
token_generator.get_acr = lambda *args: "acr"
res = test_client.post(
"/oauth/authorize",
data={
"response_type": client.response_types[0],
"client_id": client.client_id,
"redirect_uri": client.redirect_uris[0],
"scope": client.scope,
"user_id": user.id,
},
)
params = dict(url_decode(urlparse.urlparse(res.location).query))
code = params["code"]
res = test_client.post(
"/oauth/token",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": client.client_id,
"client_secret": client.client_secret,
"scope": " ".join(client.scope),
"redirect_uri": client.redirect_uris[0],
},
)
access_token = res.json["access_token"]
claims = jwt.decode(access_token, jwks)
assert claims["auth_time"] == 1234
assert claims["amr"] == "amr"
assert claims["acr"] == "acr"
| AuthorizationCodeGrant |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/range_test.py | {
"start": 7351,
"end": 9350
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 2, 3])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.range(2)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=index))
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 0])))
def testEmptyDataset(self, index):
dataset = dataset_ops.Dataset.range(0)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=index))
@combinations.generate(
combinations.times(test_base.default_test_combinations()))
def testBasic(self):
dataset = dataset_ops.Dataset.range(10)
for i in range(10):
self.assertEqual(self.evaluate(random_access.at(dataset, index=i)), i)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
start=[-1, 0, 5],
stop=[-5, 0, 10],
step=[-3, 1, 5],
output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testMultipleCombinations(self, start, stop, step, output_type):
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
expected_output = np.arange(
start, stop, step, dtype=output_type.as_numpy_dtype)
len_dataset = self.evaluate(dataset.cardinality())
for i in range(len_dataset):
self.assertEqual(
self.evaluate(random_access.at(dataset, index=i)), expected_output[i])
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=len_dataset))
if __name__ == "__main__":
test.main()
| RangeRandomAccessTest |
python | huggingface__transformers | tests/models/minimax/test_modeling_minimax.py | {
"start": 8590,
"end": 10316
} | class ____(unittest.TestCase):
def test_small_model_logits(self):
model_id = "hf-internal-testing/MiniMax-tiny"
dummy_input = torch.LongTensor([[0, 1, 0], [0, 1, 0]]).to(torch_device)
model = MiniMaxForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
).to(torch_device)
with torch.no_grad():
logits = model(dummy_input).logits
logits = logits.float()
expectations = Expectations(
{
(None, None): [[1.0312, -0.5156, -0.3262], [-0.1152, 0.4336, 0.2412], [1.2188, -0.5898, -0.0381]],
("cuda", 8): [[1.0312, -0.5156, -0.3203], [-0.1201, 0.4375, 0.2402], [1.2188, -0.5898, -0.0396]],
}
)
expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device)
torch.testing.assert_close(logits[0, :3, :3], expected_slice, atol=1e-3, rtol=1e-3)
torch.testing.assert_close(logits[1, :3, :3], expected_slice, atol=1e-3, rtol=1e-3)
def test_small_model_generation(self):
model_id = "hf-internal-testing/MiniMax-tiny"
dummy_input = torch.LongTensor([[0, 1, 0], [0, 1, 0]]).to(torch_device)
model = MiniMaxForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
).to(torch_device)
expected_slice = (
torch.tensor([[0, 1, 0, 933, 307, 3102, 2457, 1208], [0, 1, 0, 933, 307, 3102, 2457, 1208]])
.to(torch.int64)
.to(torch_device)
)
outputs = model.generate(dummy_input, max_new_tokens=5, do_sample=False)
torch.testing.assert_close(outputs, expected_slice, atol=1e-3, rtol=1e-3)
| MiniMaxIntegrationTest |
python | wandb__wandb | wandb/vendor/pygments/styles/fruity.py | {
"start": 385,
"end": 1298
} | class ____(Style):
"""
Pygments version of the "native" vim theme.
"""
background_color = '#111111'
highlight_color = '#333333'
styles = {
Whitespace: '#888888',
Token: '#ffffff',
Generic.Output: '#444444 bg:#222222',
Keyword: '#fb660a bold',
Keyword.Pseudo: 'nobold',
Number: '#0086f7 bold',
Name.Tag: '#fb660a bold',
Name.Variable: '#fb660a',
Comment: '#008800 bg:#0f140f italic',
Name.Attribute: '#ff0086 bold',
String: '#0086d2',
Name.Function: '#ff0086 bold',
Generic.Heading: '#ffffff bold',
Keyword.Type: '#cdcaa9 bold',
Generic.Subheading: '#ffffff bold',
Name.Constant: '#0086d2',
Comment.Preproc: '#ff0007 bold'
}
| FruityStyle |
python | wandb__wandb | wandb/sdk/lib/console_capture.py | {
"start": 1262,
"end": 1363
} | class ____(Exception):
"""The module failed to patch stdout or stderr."""
| CannotCaptureConsoleError |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 14188,
"end": 14370
} | class ____(test.TestCase, _PinvTest):
dtype = np.float64
use_static_shape = True
use_default_rcond = True
@test_util.run_all_in_graph_and_eager_modes
| PinvTestStatic64DefaultRcond |
python | apache__airflow | helm-tests/tests/helm_tests/webserver/test_webserver.py | {
"start": 44118,
"end": 45374
} | class ____:
"""Tests webserver configmap."""
def test_no_webserver_config_configmap_by_default(self):
docs = render_chart(show_only=["templates/configmaps/webserver-configmap.yaml"])
assert len(docs) == 0
def test_no_webserver_config_configmap_with_configmap_name(self):
docs = render_chart(
values={
"webserver": {
"webserverConfig": "CSRF_ENABLED = True # {{ .Release.Name }}",
"webserverConfigConfigMapName": "my-configmap",
}
},
show_only=["templates/configmaps/webserver-configmap.yaml"],
)
assert len(docs) == 0
def test_webserver_config_configmap(self):
docs = render_chart(
values={"webserver": {"webserverConfig": "CSRF_ENABLED = True # {{ .Release.Name }}"}},
show_only=["templates/configmaps/webserver-configmap.yaml"],
)
assert docs[0]["kind"] == "ConfigMap"
assert jmespath.search("metadata.name", docs[0]) == "release-name-webserver-config"
assert (
jmespath.search('data."webserver_config.py"', docs[0]).strip()
== "CSRF_ENABLED = True # release-name"
)
| TestWebserverConfigmap |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 11701,
"end": 15073
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Optional[UniSpeechConfig] = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
self.config = config
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.is_causal = is_causal
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = False,
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
# determine input shapes
bsz, tgt_len = hidden_states.shape[:-1]
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
kv_input_shape = (bsz, src_len, -1, self.head_dim)
# get query proj
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
current_states = key_value_states if is_cross_attention else hidden_states
key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
output_attentions=output_attentions,
**kwargs,
)
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights, None
| UniSpeechAttention |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 162790,
"end": 169731
} | class ____(ParseExpression):
"""
Requires all given :class:`ParserElement` s to be found in the given order.
Expressions may be separated by whitespace.
May be constructed using the ``'+'`` operator.
May also be constructed using the ``'-'`` operator, which will
suppress backtracking.
Example:
.. testcode::
integer = Word(nums)
name_expr = Word(alphas)[1, ...]
expr = And([integer("id"), name_expr("name"), integer("age")])
# more easily written as:
expr = integer("id") + name_expr("name") + integer("age")
"""
class _ErrorStop(Empty):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.leave_whitespace()
def _generateDefaultName(self) -> str:
return "-"
def __init__(
self,
exprs_arg: typing.Iterable[Union[ParserElement, str]],
savelist: bool = True,
) -> None:
# instantiate exprs as a list, converting strs to ParserElements
exprs: list[ParserElement] = [
self._literalStringClass(e) if isinstance(e, str) else e for e in exprs_arg
]
# convert any Ellipsis elements to SkipTo
if Ellipsis in exprs:
# Ellipsis cannot be the last element
if exprs[-1] is Ellipsis:
raise Exception("cannot construct And with sequence ending in ...")
tmp: list[ParserElement] = []
for cur_expr, next_expr in zip(exprs, exprs[1:]):
if cur_expr is Ellipsis:
tmp.append(SkipTo(next_expr)("_skipped*"))
else:
tmp.append(cur_expr)
exprs[:-1] = tmp
super().__init__(exprs, savelist)
if self.exprs:
self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs)
if not isinstance(self.exprs[0], White):
self.set_whitespace_chars(
self.exprs[0].whiteChars,
copy_defaults=self.exprs[0].copyDefaultWhiteChars,
)
self.skipWhitespace = self.exprs[0].skipWhitespace
else:
self.skipWhitespace = False
else:
self._may_return_empty = True
self.callPreparse = True
def streamline(self) -> ParserElement:
"""
Collapse `And` expressions like `And(And(And(A, B), C), D)`
to `And(A, B, C, D)`.
.. doctest::
>>> expr = Word("A") + Word("B") + Word("C") + Word("D")
>>> # Using '+' operator creates nested And expression
>>> expr
{{{W:(A) W:(B)} W:(C)} W:(D)}
>>> # streamline simplifies to a single And with multiple expressions
>>> expr.streamline()
{W:(A) W:(B) W:(C) W:(D)}
Guards against collapsing out expressions that have special features,
such as results names or parse actions.
Resolves pending Skip commands defined using `...` terms.
"""
# collapse any _PendingSkip's
if self.exprs and any(
isinstance(e, ParseExpression)
and e.exprs
and isinstance(e.exprs[-1], _PendingSkip)
for e in self.exprs[:-1]
):
deleted_expr_marker = NoMatch()
for i, e in enumerate(self.exprs[:-1]):
if e is deleted_expr_marker:
continue
if (
isinstance(e, ParseExpression)
and e.exprs
and isinstance(e.exprs[-1], _PendingSkip)
):
e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]
self.exprs[i + 1] = deleted_expr_marker
self.exprs = [e for e in self.exprs if e is not deleted_expr_marker]
super().streamline()
# link any IndentedBlocks to the prior expression
prev: ParserElement
cur: ParserElement
for prev, cur in zip(self.exprs, self.exprs[1:]):
# traverse cur or any first embedded expr of cur looking for an IndentedBlock
# (but watch out for recursive grammar)
seen = set()
while True:
if id(cur) in seen:
break
seen.add(id(cur))
if isinstance(cur, IndentedBlock):
prev.add_parse_action(
lambda s, l, t, cur_=cur: setattr(
cur_, "parent_anchor", col(l, s)
)
)
break
subs = cur.recurse()
next_first = next(iter(subs), None)
if next_first is None:
break
cur = typing.cast(ParserElement, next_first)
self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs)
return self
def parseImpl(self, instring, loc, do_actions=True):
# pass False as callPreParse arg to _parse for first element, since we already
# pre-parsed the string as part of our And pre-parsing
loc, resultlist = self.exprs[0]._parse(
instring, loc, do_actions, callPreParse=False
)
errorStop = False
for e in self.exprs[1:]:
# if isinstance(e, And._ErrorStop):
if type(e) is And._ErrorStop:
errorStop = True
continue
if errorStop:
try:
loc, exprtokens = e._parse(instring, loc, do_actions)
except ParseSyntaxException:
raise
except ParseBaseException as pe:
pe.__traceback__ = None
raise ParseSyntaxException._from_exception(pe)
except IndexError:
raise ParseSyntaxException(
instring, len(instring), self.errmsg, self
)
else:
loc, exprtokens = e._parse(instring, loc, do_actions)
resultlist += exprtokens
return loc, resultlist
def __iadd__(self, other):
if isinstance(other, str_type):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
return NotImplemented
return self.append(other) # And([self, other])
def _checkRecursion(self, parseElementList):
subRecCheckList = parseElementList[:] + [self]
for e in self.exprs:
e._checkRecursion(subRecCheckList)
if not e.mayReturnEmpty:
break
def _generateDefaultName(self) -> str:
inner = " ".join(str(e) for e in self.exprs)
# strip off redundant inner {}'s
while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}":
inner = inner[1:-1]
return f"{{{inner}}}"
| And |
python | mlflow__mlflow | examples/pydanticai/tracing.py | {
"start": 1029,
"end": 1100
} | class ____:
customer_id: int
db: DatabaseConn
| SupportDependencies |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py | {
"start": 2195,
"end": 3679
} | class ____(object):
"""
Immutable type that represents a file system event that is triggered
when a change occurs on the monitored file system.
All FileSystemEvent objects are required to be immutable and hence
can be used as keys in dictionaries or be added to sets.
"""
event_type = None
"""The type of the event as a string."""
is_directory = False
"""True if event was emitted for a directory; False otherwise."""
def __init__(self, src_path):
self._src_path = src_path
@property
def src_path(self):
"""Source path of the file system object that triggered this event."""
return self._src_path
def __str__(self):
return self.__repr__()
def __repr__(self):
return ("<%(class_name)s: event_type=%(event_type)s, "
"src_path=%(src_path)r, "
"is_directory=%(is_directory)s>"
) % (dict(
class_name=self.__class__.__name__,
event_type=self.event_type,
src_path=self.src_path,
is_directory=self.is_directory))
# Used for comparison of events.
@property
def key(self):
return (self.event_type, self.src_path, self.is_directory)
def __eq__(self, event):
return self.key == event.key
def __ne__(self, event):
return self.key != event.key
def __hash__(self):
return hash(self.key)
| FileSystemEvent |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 3283,
"end": 3672
} | class ____(Spider):
name = "GeneratorCallbackSpider"
custom_settings = {
"SPIDER_MIDDLEWARES": {
LogExceptionMiddleware: 10,
},
}
async def start(self):
yield Request(self.mockserver.url("/status?n=200"))
def parse(self, response):
yield {"test": 1}
yield {"test": 2}
raise ImportError
| GeneratorCallbackSpider |
python | doocs__leetcode | solution/0200-0299/0254.Factor Combinations/Solution.py | {
"start": 0,
"end": 413
} | class ____:
def getFactors(self, n: int) -> List[List[int]]:
def dfs(n, i):
if t:
ans.append(t + [n])
j = i
while j * j <= n:
if n % j == 0:
t.append(j)
dfs(n // j, j)
t.pop()
j += 1
t = []
ans = []
dfs(n, 2)
return ans
| Solution |
python | huggingface__transformers | src/transformers/models/glm4v_moe/configuration_glm4v_moe.py | {
"start": 5585,
"end": 14576
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Glm4vMoeModel`]. It is used to instantiate a
GLM-4.5V model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of
GLM-4.5V [zai-org/GLM-4.5V](https://huggingface.co/zai-org/GLM-4.5V).
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 151424):
Vocabulary size of the Glm4vMoe model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Glm4vMoeModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 10944):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 46):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 96):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 65536):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, defaults to `True`, *optional*, defaults to `True`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
moe_intermediate_size (`int`, *optional*, defaults to 1408):
Intermediate size of the routed expert.
num_experts_per_tok (`int`, *optional*, defaults to 8):
number of experts per token.
n_shared_experts (`int`, *optional*, defaults to 1):
Number of shared experts.
n_routed_experts (`int`, *optional*, defaults to 128):
Number of routed experts.
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
Scaling factor or routed experts.
n_group (`int`, *optional*, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, *optional*, defaults to 1):
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
first_k_dense_replace (`int`, *optional*, defaults to 1):
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
\--k dense layers--/
norm_topk_prob (`bool`, *optional*, defaults to `True`):
Whether to normalize the topk probabilities.
router_aux_loss_coef (`float`, *optional*, defaults to 0.0001):
The aux loss factor for the loss.
```python
>>> from transformers import Glm4vMoeTextModel, Glm4vMoeConfig
>>> # Initializing a GLM-4.5V style configuration
>>> configuration = Glm4vMoeConfig()
>>> # Initializing a model from the GLM-4.5V style configuration
>>> model = Glm4vMoeTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "glm4v_moe_text"
keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Glm4vMoe`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
attribute_map = {
"num_local_experts": "n_routed_experts",
}
base_config_key = "text_config"
def __init__(
self,
vocab_size: Optional[int] = 151424,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 10944,
num_hidden_layers: Optional[int] = 46,
num_attention_heads: Optional[int] = 96,
num_key_value_heads: Optional[int] = 8,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 65536,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-5,
use_cache: Optional[bool] = True,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = True,
attention_dropout: Optional[float] = 0.0,
moe_intermediate_size: Optional[int] = 1408,
num_experts_per_tok: Optional[int] = 8,
n_shared_experts: Optional[int] = 1,
n_routed_experts: Optional[int] = 128,
routed_scaling_factor: Optional[float] = 1.0,
n_group: Optional[int] = 1,
topk_group: Optional[int] = 1,
first_k_dense_replace: Optional[int] = 1,
norm_topk_prob: Optional[bool] = True,
router_aux_loss_coef: Optional[float] = 0.0001,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.rope_parameters = rope_parameters
kwargs.setdefault("partial_rotary_factor", 0.5) # assign default for BC
# MoE arguments
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.n_shared_experts = n_shared_experts
self.n_routed_experts = n_routed_experts
self.routed_scaling_factor = routed_scaling_factor
self.first_k_dense_replace = first_k_dense_replace
self.norm_topk_prob = norm_topk_prob
self.router_aux_loss_coef = router_aux_loss_coef
super().__init__(tie_word_embeddings=tie_word_embeddings, ignore_keys_at_rope_validation={"mrope"}, **kwargs)
| Glm4vMoeTextConfig |
python | django__django | tests/delete_regress/models.py | {
"start": 1284,
"end": 1360
} | class ____(models.Model):
label = models.CharField(max_length=100)
| Contact |
python | huggingface__transformers | tests/models/exaone4/test_modeling_exaone4.py | {
"start": 1357,
"end": 1518
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = Exaone4ModelTester
model_split_percents = [0.5, 0.6]
@require_torch
| Exaone4ModelTest |
python | kamyu104__LeetCode-Solutions | Python/stream-of-characters.py | {
"start": 793,
"end": 2812
} | class ____(object):
def step(self, letter):
while self.__node and letter not in self.__node.children:
self.__node = self.__node.suffix
self.__node = self.__node.children[letter] if self.__node else self.__root
return self.__get_ac_node_outputs(self.__node)
def __init__(self, patterns):
self.__root = self.__create_ac_trie(patterns)
self.__node = self.__create_ac_suffix_and_output_links(self.__root)
def __create_ac_trie(self, patterns): # Time: O(n), Space: O(t)
root = AhoNode()
for i, pattern in enumerate(patterns):
node = root
for c in pattern:
node = node.children[c]
node.indices.append(i)
return root
def __create_ac_suffix_and_output_links(self, root): # Time: O(n), Space: O(t)
queue = collections.deque()
for node in root.children.itervalues():
queue.append(node)
node.suffix = root
while queue:
node = queue.popleft()
for c, child in node.children.iteritems():
queue.append(child)
suffix = node.suffix
while suffix and c not in suffix.children:
suffix = suffix.suffix
child.suffix = suffix.children[c] if suffix else root
child.output = child.suffix if child.suffix.indices else child.suffix.output
return root
def __get_ac_node_outputs(self, node): # Time: O(z), in this question, it could be improved to O(1)
# if we only return a matched pattern without all matched ones
result = []
for i in node.indices:
result.append(i)
# return result
output = node.output
while output:
for i in output.indices:
result.append(i)
# return result
output = output.output
return result
| AhoTrie |
python | davidhalter__parso | test/normalizer_issue_files/E30not.py | {
"start": 7,
"end": 87
} | class ____:
pass
# Okay
def foo():
pass
# Okay
# -*- coding: utf-8 -*-
| X |
python | takluyver__flit | flit/install.py | {
"start": 2601,
"end": 2796
} | class ____(Exception):
def __str__(self):
return ("Installing packages as root is not recommended. "
"To allow this, set FLIT_ROOT_INSTALL=1 and try again.")
| RootInstallError |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 69213,
"end": 69820
} | class ____(themeable):
"""
x-axis minor-tick padding
Parameters
----------
theme_element : float
Note
----
Padding is not applied when the
[](`~plotnine.theme.themeables.axis_ticks_minor_x`) are
blank, but it does apply when the
[](`~plotnine.theme.themeables.axis_ticks_length_minor_x`) is zero.
"""
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
val = self.properties["value"]
for t in ax.xaxis.get_minor_ticks():
_val = val if t.tick1line.get_visible() else 0
t.set_pad(_val)
| axis_ticks_pad_minor_x |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py | {
"start": 3885,
"end": 29826
} | class ____(ProcessGroupAllocMixin, ReduceScatter):
def __init__(self, group: dist.ProcessGroup) -> None:
super().__init__(group)
def __call__(
self,
output_tensor: torch.Tensor,
input_tensor: torch.Tensor,
group: dist.ProcessGroup,
op: _ReduceOp,
async_op: bool = False,
) -> dist.Work:
return dist.reduce_scatter_tensor(
output=output_tensor,
input=input_tensor,
group=group,
op=op,
async_op=async_op,
)
@torch.library.impl(lib, "all_gather_copy_in", "Meta")
def all_gather_copy_in_meta(
all_gather_inputs: list[torch.Tensor],
all_gather_output: torch.Tensor,
inp_split_sizes: list[int],
all_gather_input_numel: int,
rank: int,
) -> tuple[torch.Tensor, torch.Tensor]:
all_gather_input = all_gather_output.narrow(
0, all_gather_input_numel * rank, all_gather_input_numel
)
return all_gather_input, all_gather_output
@torch.library.impl(lib, "all_gather_copy_in", "CUDA")
@torch.library.impl(lib, "all_gather_copy_in", "XPU")
@torch.library.impl(lib, "all_gather_copy_in", "HPU")
@torch.library.impl(lib, "all_gather_copy_in", "CPU")
@torch.library.impl(lib, "all_gather_copy_in", "MTIA")
@torch.library.impl(lib, "all_gather_copy_in", "PrivateUse1")
def all_gather_copy_in_cuda(
all_gather_inputs: list[torch.Tensor],
all_gather_output: torch.Tensor,
inp_split_sizes: list[int],
all_gather_input_numel: int,
rank: int,
) -> tuple[torch.Tensor, torch.Tensor]:
all_gather_input = all_gather_output.narrow(
0, all_gather_input_numel * rank, all_gather_input_numel
)
foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
with torch.no_grad():
torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
return all_gather_input, all_gather_output
lib.define(
"split_with_sizes_copy(Tensor all_gather_output, SymInt[] all_gather_input_split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()"
)
@torch.library.impl(lib, "split_with_sizes_copy", "Meta")
@torch.library.impl(lib, "split_with_sizes_copy", "CUDA")
@torch.library.impl(lib, "split_with_sizes_copy", "XPU")
@torch.library.impl(lib, "split_with_sizes_copy", "HPU")
@torch.library.impl(lib, "split_with_sizes_copy", "CPU")
@torch.library.impl(lib, "split_with_sizes_copy", "MTIA")
@torch.library.impl(lib, "split_with_sizes_copy", "PrivateUse1")
def split_with_sizes_copy(
all_gather_output: torch.Tensor,
all_gather_input_split_sizes: list[int],
dim: int,
out: list[torch.Tensor],
) -> None:
torch.split_with_sizes_copy(
all_gather_output, all_gather_input_split_sizes, dim=dim, out=out
)
lib.define(
"chunk_cat(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"
)
@torch.library.impl(lib, "chunk_cat", "Meta")
@torch.library.impl(lib, "chunk_cat", "CUDA")
@torch.library.impl(lib, "chunk_cat", "XPU")
@torch.library.impl(lib, "chunk_cat", "HPU")
@torch.library.impl(lib, "chunk_cat", "CPU")
@torch.library.impl(lib, "chunk_cat", "MTIA")
@torch.library.impl(lib, "chunk_cat", "PrivateUse1")
def chunk_cat(
tensors: list[torch.Tensor],
dim: int,
num_chunks: int,
out: torch.Tensor,
) -> None:
torch._chunk_cat(tensors, dim, num_chunks, out=out)
@torch.no_grad()
def foreach_all_gather(
fsdp_params: list[FSDPParam],
group: dist.ProcessGroup,
async_op: bool,
all_gather_copy_in_stream: torch.Stream,
all_gather_stream: torch.Stream,
device: torch.device,
all_gather_comm: AllGather,
) -> Optional[AllGatherResult]:
world_size, rank = group.size(), group.rank()
device_handle = _get_device_handle(device.type)
with device_handle.stream(all_gather_copy_in_stream):
param_all_gather_inputs = _get_param_all_gather_inputs(fsdp_params)
(
param_all_gather_input_dtypes,
param_all_gather_input_numels,
dtype,
) = _get_all_gather_input_metadatas(param_all_gather_inputs)
if dtype == torch.uint8:
all_gather_inputs = [
t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
]
else:
all_gather_inputs = [*chain.from_iterable(param_all_gather_inputs)]
inp_split_sizes = [t.numel() for t in all_gather_inputs]
all_gather_input_numel = sum(inp_split_sizes)
all_gather_output = all_gather_comm.allocate(
(all_gather_input_numel * world_size,), dtype=dtype, device=device
)
all_gather_input, all_gather_output = torch.ops.fsdp.all_gather_copy_in(
all_gather_inputs,
all_gather_output,
inp_split_sizes,
all_gather_input_numel,
rank,
)
del param_all_gather_inputs
all_gather_stream.wait_stream(all_gather_copy_in_stream)
with device_handle.stream(all_gather_stream):
all_gather_work = all_gather_comm(
output_tensor=all_gather_output,
input_tensor=all_gather_input,
group=group,
async_op=async_op,
)
all_gather_event = all_gather_stream.record_event()
return AllGatherResult(
all_gather_output,
all_gather_event,
all_gather_work,
param_all_gather_input_dtypes,
param_all_gather_input_numels,
inp_split_sizes,
)
@torch.no_grad()
def _get_param_all_gather_inputs(
fsdp_params: list[FSDPParam],
) -> list[list[torch.Tensor]]:
if compiled_autograd_enabled():
return [fsdp_param.all_gather_inputs for fsdp_param in fsdp_params]
# Intentionally try to run a fast-path that bypasses abstractions for the
# common FSDP case of bf16/fp32 mixed precision in order to use foreach
# copy for lower CPU overhead and more efficient copying in eager
def use_foreach_copy(fsdp_param: FSDPParam) -> bool:
return (
fsdp_param.param_dtype is not None
and not fsdp_param.offload_to_cpu
and not hasattr(fsdp_param._sharded_local_tensor, "fsdp_pre_all_gather")
)
param_all_gather_inputs: list[list[torch.Tensor]] = [[] for _ in fsdp_params]
foreach_copy_indices: list[int] = []
foreach_copy_inputs: list[torch.Tensor] = []
foreach_copy_input_numels: list[int] = []
# 1st pass: for foreach-copy parameters, get inputs and metadata for the
# foreach copy, and for the others, actually get their all-gather inputs
for i, fsdp_param in enumerate(fsdp_params):
if use_foreach_copy(fsdp_param):
foreach_copy_indices.append(i)
all_gather_input = (
fsdp_param._sharded_param_data
if fsdp_param.sharded_state == ShardedState.SHARDED
else cast(torch.Tensor, fsdp_param._sharded_post_forward_param_data)
)
foreach_copy_inputs.append(all_gather_input)
foreach_copy_input_numels.append(all_gather_input.numel())
else:
param_all_gather_inputs[i] = fsdp_param.all_gather_inputs
# 2nd pass: use foreach copy to compute the remaining all-gather inputs
if foreach_copy_inputs:
fsdp_param_0 = fsdp_params[foreach_copy_indices[0]]
param_dtype, device = fsdp_param_0.param_dtype, fsdp_param_0.device
flat_foreach_copy_input = torch.empty(
(sum(foreach_copy_input_numels),), device=device, dtype=param_dtype
)
splits = torch.split(flat_foreach_copy_input, foreach_copy_input_numels)
torch._foreach_copy_(splits, foreach_copy_inputs)
for i, split in zip(foreach_copy_indices, splits):
param_all_gather_inputs[i] = [split]
return param_all_gather_inputs
@torch.no_grad()
def foreach_all_gather_copy_out(
all_gather_result: AllGatherResult,
fsdp_params: list[FSDPParam],
group: dist.ProcessGroup,
) -> None:
(
all_gather_output,
all_gather_event,
all_gather_work,
param_all_gather_input_dtypes,
param_all_gather_input_numels,
all_gather_input_split_sizes,
) = all_gather_result
_dtype, device = all_gather_output.dtype, all_gather_output.device
device_handle = _get_device_handle(device.type)
if all_gather_event is not None: # sync op
device_handle.current_stream().wait_event(all_gather_event)
if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
all_gather_work.wait()
world_size, device = group.size(), all_gather_output.device
split_with_sizes_out: list[torch.Tensor] = []
shard_i_copy_infos: list[tuple[FSDPParam, list[torch.Tensor]]] = []
for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
):
# NOTE: Under compile, make sure we always recreate all_gather_outputs
# per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
force_recreate = compiled_autograd_enabled()
fsdp_param.init_all_gather_outputs(
all_gather_input_numels,
all_gather_input_dtypes,
world_size,
device,
force_recreate=force_recreate,
)
if not force_recreate:
fsdp_param.alloc_all_gather_outputs()
param_all_gather_outputs = fsdp_param.all_gather_outputs
if fsdp_param.fsdp_placement.dim != 0:
# Copy to a temporary and then chunk-cat into the final all-gather
# output tensors
param_all_gather_outputs = [
torch.empty_like(t) for t in param_all_gather_outputs
]
shard_i_copy_infos.append((fsdp_param, param_all_gather_outputs))
split_with_sizes_out.extend(param_all_gather_outputs)
all_gather_output = all_gather_output.view(world_size, -1)
if all_gather_output.dtype == torch.uint8:
out = [t.view(world_size, -1).view(torch.uint8) for t in split_with_sizes_out]
else:
out = [t.view(world_size, -1) for t in split_with_sizes_out]
# only avoid VC bump if we are not in inference mode
if torch._dynamo.is_compiling():
# For torch.compile, we turn off inference_mode for fake tensor
# propagation, and therefore graph break on is_inference. For `compile`,
# we don't care about VCs, so just skip the optimization.
non_inference_outs = []
else:
non_inference_outs = [o for o in out if not o.is_inference()]
if len(non_inference_outs) > 0:
with torch.autograd._unsafe_preserve_version_counter(tuple(non_inference_outs)):
torch.ops.fsdp.split_with_sizes_copy(
all_gather_output, all_gather_input_split_sizes, dim=1, out=out
)
else:
torch.ops.fsdp.split_with_sizes_copy(
all_gather_output, all_gather_input_split_sizes, dim=1, out=out
)
for fsdp_param, param_all_gather_outputs in shard_i_copy_infos:
# Chunk-cat from the temporary to the final all-gather output tensors
shard_dim = fsdp_param.fsdp_placement.dim
with torch.autograd._unsafe_preserve_version_counter(
tuple(fsdp_param.all_gather_outputs)
):
for param_all_gather_output, target_all_gather_output in zip(
param_all_gather_outputs, fsdp_param.all_gather_outputs
):
padded_sharded_size = (
fsdp_param.padded_sharded_param_size
if fsdp_param.sharded_state == ShardedState.SHARDED
else cast(
torch.Tensor, fsdp_param._sharded_post_forward_param_data
).size()
)
pre_param_size = list(padded_sharded_size)
pre_param_size[0] *= world_size
chunks = torch.chunk(
param_all_gather_output.view(pre_param_size), world_size, dim=0
)
post_param_size = list(padded_sharded_size)
post_param_size[shard_dim] *= world_size
cat_out = target_all_gather_output.view(post_param_size)
torch.cat(chunks, dim=shard_dim, out=cat_out)
@torch.no_grad()
def foreach_reduce(
fsdp_params: list[FSDPParam],
unsharded_grads: list[torch.Tensor],
reduce_scatter_group: dist.ProcessGroup,
reduce_scatter_stream: torch.Stream,
reduce_scatter_comm: ReduceScatter,
orig_dtype: Optional[torch.dtype],
reduce_dtype: Optional[torch.dtype],
device: torch.device,
gradient_divide_factor: Optional[float],
all_reduce_group: Optional[dist.ProcessGroup], # not `None` iff HSDP
all_reduce_stream: torch.Stream,
all_reduce_grads: bool,
partial_reduce_output: Optional[torch.Tensor], # only used for HSDP
all_reduce_hook: Optional[Callable[[torch.Tensor], None]],
force_sum_reduction_for_comms: bool = False,
) -> tuple[
torch.Tensor,
torch.Event,
torch.Event,
Optional[torch.Tensor],
Optional[torch.Event],
Optional[torch.Tensor],
]:
"""
``unsharded_grads`` owns the references to the gradients computed by
autograd, so clearing the list frees the gradients.
"""
grad_dtypes = {grad.dtype for grad in unsharded_grads}
if len(grad_dtypes) != 1:
# Check this at runtime since it could be a real runtime error if e.g.
# fp8 weights do not produce the correct higher precision gradients
_raise_assert_with_print(
f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
)
grad_dtype = unsharded_grads[0].dtype
reduce_dtype = reduce_dtype or grad_dtype
(predivide_factor, postdivide_factor, reduce_scatter_op, all_reduce_op) = (
_get_gradient_divide_factors(
reduce_scatter_group,
all_reduce_group,
reduce_dtype,
device.type,
gradient_divide_factor,
force_sum_reduction_for_comms,
)
)
if reduce_scatter_group is None:
world_size = 1
else:
world_size = reduce_scatter_group.size()
device_handle = _get_device_handle(device.type)
current_stream = device_handle.current_stream()
if world_size > 1:
for i, (fsdp_param, unsharded_grad) in enumerate(
zip(fsdp_params, unsharded_grads)
):
if (shard_dim := fsdp_param.fsdp_placement.dim) == 0:
continue
if unsharded_grad.size(shard_dim) % world_size != 0:
raise AssertionError(
f"Shard({shard_dim}) requires even sharding: {unsharded_grad.size()=} {world_size=}"
)
chunks = torch.chunk(unsharded_grad, world_size, dim=shard_dim)
unsharded_grads[i] = torch.cat(chunks, dim=0)
padded_unsharded_sizes = tuple(
_get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
)
reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
reduce_scatter_input = reduce_scatter_comm.allocate(
(reduce_scatter_input_numel,),
dtype=reduce_dtype,
device=device,
)
foreach_reduce_scatter_copy_in(unsharded_grads, reduce_scatter_input, world_size)
# Only after the copy-in finishes can we free the gradients
unsharded_grads.clear()
reduce_scatter_stream.wait_stream(current_stream)
all_reduce_input = None
all_reduce_event = None
with device_handle.stream(reduce_scatter_stream):
reduce_output = reduce_scatter_comm.allocate(
(reduce_scatter_output_numel,),
dtype=reduce_dtype,
device=device,
)
_div_if_needed(reduce_scatter_input, predivide_factor)
if world_size > 1:
reduce_scatter_comm(
output_tensor=reduce_output,
input_tensor=reduce_scatter_input,
group=reduce_scatter_group,
op=reduce_scatter_op,
)
else:
# For single GPU, just copy the input to output (no actual reduce-scatter needed), and
# account for a possible gradient_divide_factor.
if gradient_divide_factor is not None:
reduce_output.copy_(reduce_scatter_input / gradient_divide_factor)
else:
reduce_output.copy_(reduce_scatter_input)
reduce_scatter_event = reduce_scatter_stream.record_event()
post_reduce_stream = reduce_scatter_stream
if all_reduce_group is not None: # HSDP or DDP/replicate
# Accumulations must run in the reduce-scatter stream
if not all_reduce_grads:
if partial_reduce_output is not None:
partial_reduce_output += reduce_output
else:
partial_reduce_output = reduce_output
return (
reduce_scatter_input,
reduce_scatter_event,
post_reduce_stream.record_event(),
all_reduce_input,
all_reduce_event,
partial_reduce_output,
)
if partial_reduce_output is not None:
reduce_output += partial_reduce_output
post_reduce_stream = all_reduce_stream
if world_size >= 1:
all_reduce_stream.wait_stream(reduce_scatter_stream)
else:
all_reduce_stream.wait_stream(current_stream)
with device_handle.stream(all_reduce_stream):
dist.all_reduce(
reduce_output,
group=all_reduce_group,
op=all_reduce_op,
)
all_reduce_input = reduce_output
all_reduce_event = all_reduce_stream.record_event()
# -- END: ops in reduce_scatter stream
if all_reduce_hook is not None:
# Execute user-specified all reduce hook.
# If native HSDP is used, this is executed after the HSDP all reduce.
# If 1-d FSDP is used, this is executed post reduce-scatter.
post_reduce_stream = all_reduce_stream
all_reduce_stream.wait_stream(reduce_scatter_stream)
with device_handle.stream(all_reduce_stream):
all_reduce_hook(reduce_output)
# -- END: ops post reduce_scatter
with device_handle.stream(post_reduce_stream):
_div_if_needed(reduce_output, postdivide_factor)
reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
# View out and accumulate sharded gradients
flat_grad_offset = 0 # [0, reduce_scatter_output_numel - 1]
for padded_unsharded_size, fsdp_param in zip(
padded_unsharded_sizes, fsdp_params
):
# Assume even sharding for Shard(i), i > 0; otherwise would require
# copy-out for contiguous strides
new_sharded_grad = torch.as_strided(
reduce_output,
size=fsdp_param.sharded_size,
stride=fsdp_param.contiguous_sharded_stride,
storage_offset=flat_grad_offset,
)
to_accumulate_grad = fsdp_param.sharded_param.grad is not None
if fsdp_param.offload_to_cpu:
# Only overlap the D2H copy (copying to pinned memory) if not
# accumulating gradients since the CPU add kernel depends on
# the copy result and we cannot run the add as a callback
non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
# Since the GPU sharded gradient is allocated in the RS stream,
# we can free it here by not keeping a ref without waiting for
# the D2H copy since future RS-stream ops run after the copy
new_sharded_grad = new_sharded_grad.to(
torch.device("cpu"), non_blocking=non_blocking
)
if non_blocking:
# Record an event on which to block the CPU thread to
# ensure that the D2H copy finishes before the optimizer
fsdp_param.grad_offload_event = post_reduce_stream.record_event()
if to_accumulate_grad:
if not isinstance(fsdp_param.sharded_param.grad, DTensor):
raise AssertionError(
f"Expected fsdp_param.sharded_param.grad to be DTensor, got {type(fsdp_param.sharded_param.grad)}"
)
fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
else:
new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
new_sharded_grad
)
fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
if not compiled_autograd_enabled():
for hook in (
getattr(fsdp_param.sharded_param, "_post_accumulate_grad_hooks", {})
or {}
).values():
hook(fsdp_param.sharded_param)
padded_sharded_numel = padded_unsharded_size.numel() // world_size
flat_grad_offset += padded_sharded_numel
post_reduce_event = post_reduce_stream.record_event()
# The RS output is allocated in the RS stream and used in the default
# stream (for optimizer). To ensure its memory is not reused for later
# RSs, we do not need extra synchronization since the sharded parameters
# hold refs through the end of backward.
return (
reduce_scatter_input,
reduce_scatter_event,
post_reduce_event,
all_reduce_input,
all_reduce_event,
None,
)
def foreach_reduce_scatter_copy_in(
unsharded_grads: list[torch.Tensor],
reduce_scatter_input: torch.Tensor,
world_size: int,
) -> None:
reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
torch.ops.fsdp.chunk_cat(
unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
)
def _get_all_gather_input_metadatas(
param_all_gather_inputs: list[list[torch.Tensor]],
) -> tuple[list[list[torch.dtype]], list[list[int]], torch.dtype]:
param_all_gather_input_dtypes: list[list[torch.dtype]] = []
param_all_gather_input_numels: list[list[int]] = []
all_gather_dtype = param_all_gather_inputs[0][0].dtype
for all_gather_inputs in param_all_gather_inputs:
input_dtypes: list[torch.dtype] = []
input_numels: list[int] = []
for all_gather_input in all_gather_inputs:
if all_gather_input.dtype != all_gather_dtype:
all_gather_dtype = torch.uint8
input_dtypes.append(all_gather_input.dtype)
input_numels.append(all_gather_input.numel())
param_all_gather_input_dtypes.append(input_dtypes)
param_all_gather_input_numels.append(input_numels)
return (
param_all_gather_input_dtypes,
param_all_gather_input_numels,
all_gather_dtype,
)
def _get_gradient_divide_factors(
reduce_scatter_group: Optional[dist.ProcessGroup],
all_reduce_group: Optional[dist.ProcessGroup],
reduce_dtype: torch.dtype,
device_type: str = "",
factor: Optional[float] = None,
force_sum_reduction_for_comms: bool = False,
) -> tuple[
Optional[float],
Optional[float],
Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
]:
# MTIA appears to only support SUM reduction, hence we force it implicitly
if device_type == "mtia":
force_sum_reduction_for_comms = True
# For fp32/bf16, we do not need to worry about overflow/underflow, so we
# use NCCL's built-in division to avoid separate div kernels
overflow_risk = reduce_dtype not in (torch.float32, torch.bfloat16)
if reduce_scatter_group is not None:
data_parallel_size = reduce_scatter_group.size()
else:
data_parallel_size = 1
if all_reduce_group is not None:
data_parallel_size *= all_reduce_group.size()
if not overflow_risk and not force_sum_reduction_for_comms:
if factor is None:
# Warning: NCCL ReduceOp.AVG may produce incorrect results with
# world size 1.
if data_parallel_size == 1:
return None, None, ReduceOp.SUM, ReduceOp.SUM
return None, None, ReduceOp.AVG, ReduceOp.AVG
if reduce_scatter_group is not None and factor == reduce_scatter_group.size():
reduce_scatter_op = ReduceOp.AVG
else:
reduce_scatter_op = torch.distributed._make_nccl_premul_sum(1 / factor)
return None, None, reduce_scatter_op, ReduceOp.SUM
if factor is None:
factor = float(data_parallel_size)
pre_factor: Optional[float]
if overflow_risk:
# Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
# overflow/underflow. For N data parallel workers, each worker computes
# g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
# overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
pre_factor = 1
while factor % pre_factor == 0 and factor / pre_factor > pre_factor:
pre_factor *= 2
post_factor = factor / pre_factor
else:
# Prefer post-multiplying as it operates on less data and is thus faster
pre_factor, post_factor = None, factor
return pre_factor, post_factor, ReduceOp.SUM, ReduceOp.SUM
def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
if div_factor is not None and div_factor != 1:
tensor.div_(div_factor)
| ProcessGroupAllocReduceScatter |
python | google__jax | tests/pmap_test.py | {
"start": 83480,
"end": 85795
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if jax.device_count() < 2:
raise SkipTest('test requires at least two devices')
@config.pmap_shmap_merge(True)
def test_store_exception(self):
def f(x):
return x
inp = jnp.ones((jax.device_count(), 1), dtype=jnp.float32)
jax.pmap(f, axis_name='i')(inp)
inp = jnp.ones((jax.device_count(), 1), dtype=jnp.int32)
jax.pmap(f, axis_name='i')(inp)
@config.pmap_shmap_merge(True)
def test_prng_key(self):
keys = jax.random.split(jax.random.key(0), jax.device_count())
out = jax.pmap(lambda x: x)(keys)
self.assertEqual(type(out), type(keys))
out = jax.pmap(lambda x, y: y, in_axes=(0, None))(keys, jax.random.key(0))
self.assertEqual(type(out), type(keys))
out = jax.pmap(lambda x, y: y, in_axes=(0, None), out_axes=None)(
keys, jax.random.key(0))
self.assertEqual(type(out), type(keys))
@config.pmap_shmap_merge(True)
def test_lower_with_flattened_args(self):
shape = (jax.device_count(), 3)
inputs = np.reshape(np.arange(math.prod(shape)), shape)
# The shard_map implementation of pmap takes pytree args, but the inner
# jitted_f must take flattened args.
_ = jax.pmap(lambda x: x[0]).lower((inputs, ())).compile() # doesn't crash
@config.pmap_shmap_merge(True)
def test_float0_dtype_input(self):
inputs = np.array([b''] * jax.device_count(), dtype=dtypes.float0)
_ = jax.pmap(lambda x: x)(inputs) # doesn't crash
@config.pmap_shmap_merge(True)
def test_float0_dtype_output(self):
inputs = np.ones(jax.device_count())
_ = jax.pmap(lambda x: jnp.array(b'', dtype=dtypes.float0))(inputs) # doesn't crash
@config.pmap_shmap_merge(True)
def test_lowered_args_info(self):
shmap_lowered = jax.pmap(lambda x: x).lower((jnp.ones((1,), jnp.float32), ()))
aval = core.ShapedArray((1,), jnp.float32)
expected_args_info = (((stages.ArgInfo(aval, donated=False), (),),),{},)
self.assertEqual(shmap_lowered.args_info, expected_args_info) # doesn't crash
@config.pmap_shmap_merge(True)
def test_wrapped(self):
f = lambda x: x
g = jax.pmap(f)
self.assertTrue(hasattr(g, '__wrapped__'))
self.assertEqual(g.__wrapped__, f)
@jtu.pytest_mark_if_available('multiaccelerator')
| PmapShmapMergeTest |
python | pola-rs__polars | py-polars/tests/unit/constructors/test_constructors.py | {
"start": 1775,
"end": 1855
} | class ____(pydantic.BaseModel):
a: str
b: int
c: _TestBazPD
| _TestBarPD |
python | django__django | tests/contenttypes_tests/test_checks.py | {
"start": 457,
"end": 5502
} | class ____(SimpleTestCase):
databases = "__all__"
def test_missing_content_type_field(self):
class TaggedItem(models.Model):
# no content_type field
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
field = TaggedItem._meta.get_field("content_object")
expected = [
checks.Error(
"The GenericForeignKey content type references the nonexistent "
"field 'TaggedItem.content_type'.",
obj=field,
id="contenttypes.E002",
)
]
self.assertEqual(field.check(), expected)
def test_invalid_content_type_field(self):
class Model(models.Model):
content_type = models.IntegerField() # should be ForeignKey
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
field = Model._meta.get_field("content_object")
self.assertEqual(
field.check(),
[
checks.Error(
"'Model.content_type' is not a ForeignKey.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=field,
id="contenttypes.E003",
)
],
)
def test_content_type_field_pointing_to_wrong_model(self):
class Model(models.Model):
content_type = models.ForeignKey(
"self", models.CASCADE
) # should point to ContentType
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
field = Model._meta.get_field("content_object")
self.assertEqual(
field.check(),
[
checks.Error(
"'Model.content_type' is not a ForeignKey to "
"'contenttypes.ContentType'.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=field,
id="contenttypes.E004",
)
],
)
def test_content_type_db_on_delete(self):
class Model(models.Model):
content_type = models.ForeignKey(ContentType, models.DB_CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
field = Model._meta.get_field("content_object")
self.assertEqual(
field.check(),
[
checks.Error(
"'Model.content_type' cannot use the database-level on_delete "
"variant.",
hint="Change the on_delete rule to the non-database variant.",
obj=field,
id="contenttypes.E006",
)
],
)
def test_missing_object_id_field(self):
class TaggedItem(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
# missing object_id field
content_object = GenericForeignKey()
field = TaggedItem._meta.get_field("content_object")
self.assertEqual(
field.check(),
[
checks.Error(
"The GenericForeignKey object ID references the nonexistent "
"field 'object_id'.",
obj=field,
id="contenttypes.E001",
)
],
)
def test_field_name_ending_with_underscore(self):
class Model(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object_ = GenericForeignKey("content_type", "object_id")
field = Model._meta.get_field("content_object_")
self.assertEqual(
field.check(),
[
checks.Error(
"Field names must not end with an underscore.",
obj=field,
id="fields.E001",
)
],
)
@override_settings(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"contenttypes_tests",
]
)
def test_generic_foreign_key_checks_are_performed(self):
class Model(models.Model):
content_object = GenericForeignKey()
with mock.patch.object(GenericForeignKey, "check") as check:
checks.run_checks(app_configs=self.apps.get_app_configs())
check.assert_called_once_with()
@isolate_apps("contenttypes_tests")
| GenericForeignKeyTests |
python | bokeh__bokeh | tests/unit/bokeh/plotting/test_figure.py | {
"start": 8471,
"end": 11858
} | class ____:
@pytest.mark.parametrize('marker', NONCIRCLE_MARKERS)
def test_mixed_inputs(self, marker) -> None:
p = bpf.figure()
rgb = (100, 0, 0)
rgb_other = (0, 100, 0)
alpha1 = 0.5
alpha2 = 0.75
func = getattr(p, marker)
# color/line_color
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], color=rgb, line_color=rgb_other)
assert r.glyph.fill_color == rgb
assert r.glyph.line_color == rgb_other
# color/fill_color
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], color=rgb, fill_color=rgb_other)
assert r.glyph.line_color == rgb
assert r.glyph.fill_color == rgb_other
# alpha/line_alpha
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], color=rgb, alpha=alpha1, line_alpha=alpha2)
assert r.glyph.line_alpha == alpha2
assert r.glyph.fill_alpha == alpha1
@pytest.mark.parametrize('marker', NONCIRCLE_MARKERS)
@pytest.mark.parametrize('color', [(100., 100., 100.), (50., 100., 50., 0.5), (100, 100, 100), (50, 100, 50, 0.5)])
def test_color_input(self, color, marker) -> None:
p = bpf.figure()
func = getattr(p, marker)
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], color=color)
assert r.glyph.line_color == color
assert r.glyph.fill_color == color
# rgb should always be an integer by the time it is added to property
for v in r.glyph.line_color[0:3]:
assert isinstance(v, int)
for v in r.glyph.fill_color[0:3]:
assert isinstance(v, int)
@pytest.mark.parametrize('marker', NONCIRCLE_MARKERS)
@pytest.mark.parametrize('color', [(100., 100., 100.), (50., 100., 50., 0.5), (100, 100, 100), (50, 100, 50, 0.5)])
def test_line_color_input(self, color, marker) -> None:
p = bpf.figure()
func = getattr(p, marker)
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], line_color=color)
assert r.glyph.line_color == color
# rgb should always be an integer by the time it is added to property
for v in r.glyph.line_color[0:3]:
assert isinstance(v, int)
@pytest.mark.parametrize('marker', NONCIRCLE_MARKERS)
@pytest.mark.parametrize('color', [(100., 100., 100.), (50., 100., 50., 0.5), (50, 100, 50, 0.5)])
def test_fill_color_input(self, color, marker) -> None:
p = bpf.figure()
func = getattr(p, marker)
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], fill_color=color)
assert r.glyph.fill_color == color
# rgb should always be an integer by the time it is added to property
for v in r.glyph.fill_color[0:3]:
assert isinstance(v, int)
@pytest.mark.parametrize('marker', NONCIRCLE_MARKERS)
def test_render_level(self, marker) -> None:
p = bpf.figure()
func = getattr(p, marker)
with pytest.warns(BokehDeprecationWarning):
r = func([1, 2, 3], [1, 2, 3], level="underlay")
assert r.level == "underlay"
with pytest.raises(ValueError):
p.scatter([1, 2, 3], [1, 2, 3], level="bad_input")
| TestMarkers |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/test/data_versions.py | {
"start": 1144,
"end": 1544
} | class ____:
def __init__(self, materializations: Mapping[AssetKey, AssetMaterialization]):
self.materializations = materializations
def __getitem__(self, key: Union[str, AssetKey]) -> AssetMaterialization:
asset_key = AssetKey([key]) if isinstance(key, str) else key
return self.materializations[asset_key]
# Used to provide source asset dependency
| MaterializationTable |
python | doocs__leetcode | solution/2200-2299/2289.Steps to Make Array Non-decreasing/Solution.py | {
"start": 0,
"end": 327
} | class ____:
def totalSteps(self, nums: List[int]) -> int:
stk = []
ans, n = 0, len(nums)
dp = [0] * n
for i in range(n - 1, -1, -1):
while stk and nums[i] > nums[stk[-1]]:
dp[i] = max(dp[i] + 1, dp[stk.pop()])
stk.append(i)
return max(dp)
| Solution |
python | getsentry__sentry | src/sentry/middleware/integrations/classifications.py | {
"start": 1236,
"end": 1951
} | class ____(BaseClassification):
plugin_prefix = "/plugins/"
"""Prefix for plugin requests."""
def should_operate(self, request: HttpRequest) -> bool:
from .parsers import PluginRequestParser
is_plugin = request.path.startswith(self.plugin_prefix)
if not is_plugin:
return False
rp = PluginRequestParser(request=request, response_handler=self.response_handler)
return rp.should_operate()
def get_response(self, request: HttpRequest) -> HttpResponseBase:
from .parsers import PluginRequestParser
rp = PluginRequestParser(request=request, response_handler=self.response_handler)
return rp.get_response()
| PluginClassification |
python | pypa__setuptools | setuptools/config/_validate_pyproject/extra_validations.py | {
"start": 325,
"end": 691
} | class ____(ValidationError):
_DESC = """According to PEP 621:
Build back-ends MUST raise an error if the metadata specifies a field
statically as well as being listed in dynamic.
"""
__doc__ = _DESC
_URL = (
"https://packaging.python.org/en/latest/specifications/"
"pyproject-toml/#dynamic"
)
| RedefiningStaticFieldAsDynamic |
python | ansible__ansible | lib/ansible/_internal/_templating/_marker_behaviors.py | {
"start": 2966,
"end": 3439
} | class ____(MarkerBehavior):
"""Routes instances of Marker (by type reference) to another MarkerBehavior, defaulting to FailingMarkerBehavior."""
def __init__(self, dispatch_table: dict[type[Marker], MarkerBehavior]) -> None:
self._dispatch_table = dispatch_table
def handle_marker(self, value: Marker) -> t.Any:
behavior = self._dispatch_table.get(type(value), FAIL_ON_UNDEFINED)
return behavior.handle_marker(value)
| RoutingMarkerBehavior |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_registries.py | {
"start": 517,
"end": 643
} | class ____(GQLResult):
projects: Optional[FetchRegistriesOrganizationOrgEntityProjects]
| FetchRegistriesOrganizationOrgEntity |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 60415,
"end": 61869
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_doesnt_raise_when_zero_and_negative(self):
tom = constant_op.constant([0, -2], name="tom")
with ops.control_dependencies([check_ops.assert_non_positive(tom)]):
out = array_ops.identity(tom)
self.evaluate(out)
@test_util.run_in_graph_and_eager_modes
@test_util.run_deprecated_v1
def test_raises_when_positive(self):
rachel = constant_op.constant([0, 2], name="rachel")
with self.assertRaisesOpError("x <= 0 did not hold"):
with ops.control_dependencies([check_ops.assert_non_positive(rachel)]):
out = array_ops.identity(rachel)
self.evaluate(out)
@test_util.run_in_graph_and_eager_modes
def test_empty_tensor_doesnt_raise(self):
# A tensor is non-positive when it satisfies:
# For every element x_i in x, x_i <= 0
# and an empty tensor has no elements, so this is trivially satisfied.
# This is standard set theory.
empty = constant_op.constant([], name="empty")
with ops.control_dependencies([check_ops.assert_non_positive(empty)]):
out = array_ops.identity(empty)
self.evaluate(out)
def test_static_check_in_graph_mode(self):
with ops.Graph().as_default():
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Custom error message"):
check_ops.assert_non_positive(1, message="Custom error message")
| AssertNonPositiveTest |
python | numba__numba | numba/tests/support.py | {
"start": 33391,
"end": 37837
} | class ____(EnableNRTStatsMixin, MemoryLeak):
def setUp(self):
super(MemoryLeakMixin, self).setUp()
self.memory_leak_setup()
def tearDown(self):
gc.collect()
self.memory_leak_teardown()
super(MemoryLeakMixin, self).tearDown()
@contextlib.contextmanager
def forbid_codegen():
"""
Forbid LLVM code generation during the execution of the context
manager's enclosed block.
If code generation is invoked, a RuntimeError is raised.
"""
from numba.core import codegen
patchpoints = ['CPUCodeLibrary._finalize_final_module']
old = {}
def fail(*args, **kwargs):
raise RuntimeError("codegen forbidden by test case")
try:
# XXX use the mock library instead?
for name in patchpoints:
parts = name.split('.')
obj = codegen
for attrname in parts[:-1]:
obj = getattr(obj, attrname)
attrname = parts[-1]
value = getattr(obj, attrname)
assert callable(value), ("%r should be callable" % name)
old[obj, attrname] = value
setattr(obj, attrname, fail)
yield
finally:
for (obj, attrname), value in old.items():
setattr(obj, attrname, value)
# For details about redirection of file-descriptor, read
# https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/
@contextlib.contextmanager
def redirect_fd(fd):
"""
Temporarily redirect *fd* to a pipe's write end and return a file object
wrapping the pipe's read end.
"""
from numba import _helperlib
libnumba = ctypes.CDLL(_helperlib.__file__)
libnumba._numba_flush_stdout()
save = os.dup(fd)
r, w = os.pipe()
try:
os.dup2(w, fd)
yield io.open(r, "r")
finally:
libnumba._numba_flush_stdout()
os.close(w)
os.dup2(save, fd)
os.close(save)
def redirect_c_stdout():
"""Redirect C stdout
"""
fd = sys.__stdout__.fileno()
return redirect_fd(fd)
def redirect_c_stderr():
"""Redirect C stderr
"""
fd = sys.__stderr__.fileno()
return redirect_fd(fd)
def run_in_new_process_caching(func, cache_dir_prefix=__name__, verbose=True):
"""Spawn a new process to run `func` with a temporary cache directory.
The childprocess's stdout and stderr will be captured and redirected to
the current process's stdout and stderr.
Returns
-------
ret : dict
exitcode: 0 for success. 1 for exception-raised.
stdout: str
stderr: str
"""
cache_dir = temp_directory(cache_dir_prefix)
return run_in_new_process_in_cache_dir(func, cache_dir, verbose=verbose)
def run_in_new_process_in_cache_dir(func, cache_dir, verbose=True):
"""Spawn a new process to run `func` with a temporary cache directory.
The childprocess's stdout and stderr will be captured and redirected to
the current process's stdout and stderr.
Similar to ``run_in_new_process_caching()`` but the ``cache_dir`` is a
directory path instead of a name prefix for the directory path.
Returns
-------
ret : dict
exitcode: 0 for success. 1 for exception-raised.
stdout: str
stderr: str
"""
ctx = mp.get_context('spawn')
qout = ctx.Queue()
with override_env_config('NUMBA_CACHE_DIR', cache_dir):
proc = ctx.Process(target=_remote_runner, args=[func, qout])
proc.start()
proc.join()
stdout = qout.get_nowait()
stderr = qout.get_nowait()
if verbose and stdout.strip():
print()
print('STDOUT'.center(80, '-'))
print(stdout)
if verbose and stderr.strip():
print(file=sys.stderr)
print('STDERR'.center(80, '-'), file=sys.stderr)
print(stderr, file=sys.stderr)
return {
'exitcode': proc.exitcode,
'stdout': stdout,
'stderr': stderr,
}
def _remote_runner(fn, qout):
"""Used by `run_in_new_process_caching()`
"""
with captured_stderr() as stderr:
with captured_stdout() as stdout:
try:
fn()
except Exception:
traceback.print_exc()
exitcode = 1
else:
exitcode = 0
qout.put(stdout.getvalue())
qout.put(stderr.getvalue())
sys.exit(exitcode)
| MemoryLeakMixin |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py | {
"start": 5917,
"end": 6090
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
enabled: bool
packageName: str = Field(..., description="The name of the package on PyPi.")
| PyPi |
python | falconry__falcon | tests/test_slots.py | {
"start": 83,
"end": 671
} | class ____:
def test_slots_request(self, asgi):
req = testing.create_asgi_req() if asgi else testing.create_req()
try:
req.doesnt = 'exist'
except AttributeError:
pytest.fail('Unable to add additional variables dynamically')
def test_slots_response(self, asgi):
if asgi:
resp = falcon.asgi.Response()
else:
resp = falcon.Response()
try:
resp.doesnt = 'exist'
except AttributeError:
pytest.fail('Unable to add additional variables dynamically')
| TestSlots |
python | gevent__gevent | src/gevent/tests/test__local.py | {
"start": 1033,
"end": 1125
} | class ____(object):
def __del__(self):
deleted_sentinels.append(id(self))
| Sentinel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 22437,
"end": 37088
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset"))
@mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook"))
def test_execute(self, mock_hook, mock_dataset):
mock_hook.return_value.create_custom_python_package_training_job.return_value = (
None,
"training_id",
"custom_job_id",
)
op = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
model_serving_container_image_uri=CONTAINER_URI,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
dataset_id=TEST_DATASET_ID,
parent_model=TEST_PARENT_MODEL,
)
op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()})
mock_dataset.assert_called_once_with(name=TEST_DATASET_ID)
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.create_custom_python_package_training_job.assert_called_once_with(
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
args=ARGS,
container_uri=CONTAINER_URI,
model_serving_container_image_uri=CONTAINER_URI,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
dataset=mock_dataset.return_value,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
parent_model=TEST_PARENT_MODEL,
is_default_version=None,
model_version_aliases=None,
model_version_description=None,
model_serving_container_predict_route=None,
model_serving_container_health_route=None,
model_serving_container_command=None,
model_serving_container_args=None,
model_serving_container_environment_variables=None,
model_serving_container_ports=None,
model_description=None,
model_instance_schema_uri=None,
model_parameters_schema_uri=None,
model_prediction_schema_uri=None,
labels=None,
training_encryption_spec_key_name=None,
model_encryption_spec_key_name=None,
# RUN
annotation_schema_uri=None,
model_labels=None,
base_output_dir=None,
service_account=None,
network=None,
bigquery_destination=None,
environment_variables=None,
boot_disk_type="pd-ssd",
boot_disk_size_gb=100,
training_filter_split=None,
validation_filter_split=None,
test_filter_split=None,
predefined_split_column_name=None,
timestamp_split_column_name=None,
tensorboard=None,
sync=True,
psc_interface_config=None,
)
@mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset"))
@mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook"))
def test_execute__parent_model_version_index_is_removed(self, mock_hook, mock_dataset):
mock_hook.return_value.create_custom_python_package_training_job.return_value = (
None,
"training_id",
"custom_job_id",
)
op = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
model_serving_container_image_uri=CONTAINER_URI,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
dataset_id=TEST_DATASET_ID,
parent_model=VERSIONED_TEST_PARENT_MODEL,
)
op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()})
mock_hook.return_value.create_custom_python_package_training_job.assert_called_once_with(
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
args=ARGS,
container_uri=CONTAINER_URI,
model_serving_container_image_uri=CONTAINER_URI,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
dataset=mock_dataset.return_value,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
parent_model=TEST_PARENT_MODEL,
is_default_version=None,
model_version_aliases=None,
model_version_description=None,
model_serving_container_predict_route=None,
model_serving_container_health_route=None,
model_serving_container_command=None,
model_serving_container_args=None,
model_serving_container_environment_variables=None,
model_serving_container_ports=None,
model_description=None,
model_instance_schema_uri=None,
model_parameters_schema_uri=None,
model_prediction_schema_uri=None,
labels=None,
training_encryption_spec_key_name=None,
model_encryption_spec_key_name=None,
# RUN
annotation_schema_uri=None,
model_labels=None,
base_output_dir=None,
service_account=None,
network=None,
bigquery_destination=None,
environment_variables=None,
boot_disk_type="pd-ssd",
boot_disk_size_gb=100,
training_filter_split=None,
validation_filter_split=None,
test_filter_split=None,
predefined_split_column_name=None,
timestamp_split_column_name=None,
tensorboard=None,
sync=True,
psc_interface_config=None,
)
@mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomPythonPackageTrainingJobOperator.hook"))
def test_execute_enters_deferred_state(self, mock_hook):
task = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
model_serving_container_image_uri=CONTAINER_URI,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
deferrable=True,
)
mock_hook.return_value.exists.return_value = False
with pytest.raises(TaskDeferred) as exc:
task.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()})
assert isinstance(exc.value.trigger, CustomPythonPackageTrainingJobTrigger), (
"Trigger is not a CustomPythonPackageTrainingJobTrigger"
)
@mock.patch(VERTEX_AI_LINKS_PATH.format("VertexAIModelLink.persist"))
@mock.patch(
VERTEX_AI_PATH.format("custom_job.CreateCustomPythonPackageTrainingJobOperator.hook.extract_model_id")
)
@mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomPythonPackageTrainingJobOperator.hook"))
def test_execute_complete_success(
self,
mock_hook,
hook_extract_model_id,
mock_link_persist,
):
task = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
model_serving_container_image_uri=CONTAINER_URI,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
deferrable=True,
)
expected_result = TEST_TRAINING_PIPELINE_DATA["model_to_upload"]
hook_extract_model_id.return_value = "test-model"
mock_ti = mock.MagicMock()
mock_context = {"ti": mock_ti}
actual_result = task.execute_complete(
context=mock_context,
event={
"status": "success",
"message": "",
"job": TEST_TRAINING_PIPELINE_DATA,
},
)
mock_ti.xcom_push.assert_any_call(key="model_id", value="test-model")
mock_link_persist.assert_called_once_with(context=mock_context, model_id="test-model")
assert actual_result == expected_result
def test_execute_complete_error_status_raises_exception(self):
task = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
model_serving_container_image_uri=CONTAINER_URI,
model_display_name=DISPLAY_NAME_2,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
deferrable=True,
)
with pytest.raises(AirflowException):
task.execute_complete(context=None, event={"status": "error", "message": "test message"})
@mock.patch(VERTEX_AI_LINKS_PATH.format("VertexAIModelLink.persist"))
@mock.patch(
VERTEX_AI_PATH.format("custom_job.CreateCustomPythonPackageTrainingJobOperator.hook.extract_model_id")
)
@mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomPythonPackageTrainingJobOperator.hook"))
def test_execute_complete_no_model_produced(
self,
mock_hook,
hook_extract_model_id,
mock_link_persist,
):
task = CreateCustomPythonPackageTrainingJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
staging_bucket=STAGING_BUCKET,
display_name=DISPLAY_NAME,
python_package_gcs_uri=PYTHON_PACKAGE_GCS_URI,
python_module_name=PYTHON_MODULE_NAME,
container_uri=CONTAINER_URI,
args=ARGS,
replica_count=REPLICA_COUNT,
machine_type=MACHINE_TYPE,
accelerator_type=ACCELERATOR_TYPE,
accelerator_count=ACCELERATOR_COUNT,
training_fraction_split=TRAINING_FRACTION_SPLIT,
validation_fraction_split=VALIDATION_FRACTION_SPLIT,
test_fraction_split=TEST_FRACTION_SPLIT,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
deferrable=True,
)
mock_ti = mock.MagicMock()
expected_result = None
actual_result = task.execute_complete(
context={"ti": mock_ti},
event={"status": "success", "message": "", "job": TEST_TRAINING_PIPELINE_DATA_NO_MODEL},
)
mock_ti.xcom_push.assert_called_once()
mock_link_persist.assert_not_called()
assert actual_result == expected_result
| TestVertexAICreateCustomPythonPackageTrainingJobOperator |
python | spack__spack | lib/spack/spack/test/llnl/util/lock.py | {
"start": 37441,
"end": 43607
} | class ____:
def __init__(self, lock_path):
self.lock_path = lock_path
self.host = socket.gethostname()
def p1(self, barrier, q1, q2):
# exchange pids
p1_pid = os.getpid()
q1.put(p1_pid)
p2_pid = q2.get()
# set up lock
lock = lk.Lock(self.lock_path, debug=True)
with lk.WriteTransaction(lock):
# p1 takes write lock and writes pid/host to file
barrier.wait() # ------------------------------------ 1
assert lock.pid == p1_pid
assert lock.host == self.host
# wait for p2 to verify contents of file
barrier.wait() # ---------------------------------------- 2
# wait for p2 to take a write lock
barrier.wait() # ---------------------------------------- 3
# verify pid/host info again
with lk.ReadTransaction(lock):
assert lock.old_pid == p1_pid
assert lock.old_host == self.host
assert lock.pid == p2_pid
assert lock.host == self.host
barrier.wait() # ---------------------------------------- 4
def p2(self, barrier, q1, q2):
# exchange pids
p2_pid = os.getpid()
p1_pid = q1.get()
q2.put(p2_pid)
# set up lock
lock = lk.Lock(self.lock_path, debug=True)
# p1 takes write lock and writes pid/host to file
barrier.wait() # ---------------------------------------- 1
# verify that p1 wrote information to lock file
with lk.ReadTransaction(lock):
assert lock.pid == p1_pid
assert lock.host == self.host
barrier.wait() # ---------------------------------------- 2
# take a write lock on the file and verify pid/host info
with lk.WriteTransaction(lock):
assert lock.old_pid == p1_pid
assert lock.old_host == self.host
assert lock.pid == p2_pid
assert lock.host == self.host
barrier.wait() # ------------------------------------ 3
# wait for p1 to verify pid/host info
barrier.wait() # ---------------------------------------- 4
def test_lock_debug_output(lock_path):
test_debug = LockDebugOutput(lock_path)
q1, q2 = Queue(), Queue()
local_multiproc_test(test_debug.p2, test_debug.p1, extra_args=(q1, q2))
def test_lock_with_no_parent_directory(tmp_path: pathlib.Path):
"""Make sure locks work even when their parent directory does not exist."""
with working_dir(str(tmp_path)):
lock = lk.Lock("foo/bar/baz/lockfile")
with lk.WriteTransaction(lock):
pass
def test_lock_in_current_directory(tmp_path: pathlib.Path):
"""Make sure locks work even when their parent directory does not exist."""
with working_dir(str(tmp_path)):
# test we can create a lock in the current directory
lock = lk.Lock("lockfile")
for i in range(10):
with lk.ReadTransaction(lock):
pass
with lk.WriteTransaction(lock):
pass
# and that we can do the same thing after it's already there
lock = lk.Lock("lockfile")
for i in range(10):
with lk.ReadTransaction(lock):
pass
with lk.WriteTransaction(lock):
pass
def test_attempts_str():
assert lk._attempts_str(0, 0) == ""
assert lk._attempts_str(0.12, 1) == ""
assert lk._attempts_str(12.345, 2) == " after 12.345s and 2 attempts"
def test_lock_str():
lock = lk.Lock("lockfile")
lockstr = str(lock)
assert "lockfile[0:0]" in lockstr
assert "timeout=None" in lockstr
assert "#reads=0, #writes=0" in lockstr
def test_downgrade_write_okay(tmp_path: pathlib.Path):
"""Test the lock write-to-read downgrade operation."""
with working_dir(str(tmp_path)):
lock = lk.Lock("lockfile")
lock.acquire_write()
lock.downgrade_write_to_read()
assert lock._reads == 1
assert lock._writes == 0
lock.release_read()
def test_downgrade_write_fails(tmp_path: pathlib.Path):
"""Test failing the lock write-to-read downgrade operation."""
with working_dir(str(tmp_path)):
lock = lk.Lock("lockfile")
lock.acquire_read()
msg = "Cannot downgrade lock from write to read on file: lockfile"
with pytest.raises(lk.LockDowngradeError, match=msg):
lock.downgrade_write_to_read()
lock.release_read()
@pytest.mark.parametrize(
"err_num,err_msg",
[
(errno.EACCES, "Fake EACCES error"),
(errno.EAGAIN, "Fake EAGAIN error"),
(errno.ENOENT, "Fake ENOENT error"),
],
)
def test_poll_lock_exception(tmp_path: pathlib.Path, monkeypatch, err_num, err_msg):
"""Test poll lock exception handling."""
def _lockf(fd, cmd, len, start, whence):
raise OSError(err_num, err_msg)
with working_dir(str(tmp_path)):
lockfile = "lockfile"
lock = lk.Lock(lockfile)
lock.acquire_read()
monkeypatch.setattr(fcntl, "lockf", _lockf)
if err_num in [errno.EAGAIN, errno.EACCES]:
assert not lock._poll_lock(fcntl.LOCK_EX)
else:
with pytest.raises(OSError, match=err_msg):
lock._poll_lock(fcntl.LOCK_EX)
monkeypatch.undo()
lock.release_read()
def test_upgrade_read_okay(tmp_path: pathlib.Path):
"""Test the lock read-to-write upgrade operation."""
with working_dir(str(tmp_path)):
lock = lk.Lock("lockfile")
lock.acquire_read()
lock.upgrade_read_to_write()
assert lock._reads == 0
assert lock._writes == 1
lock.release_write()
def test_upgrade_read_fails(tmp_path: pathlib.Path):
"""Test failing the lock read-to-write upgrade operation."""
with working_dir(str(tmp_path)):
lock = lk.Lock("lockfile")
lock.acquire_write()
msg = "Cannot upgrade lock from read to write on file: lockfile"
with pytest.raises(lk.LockUpgradeError, match=msg):
lock.upgrade_read_to_write()
lock.release_write()
| LockDebugOutput |
python | huggingface__transformers | src/transformers/modeling_layers.py | {
"start": 7051,
"end": 9349
} | class ____:
base_model_prefix = "model"
def __init__(self, config):
super().__init__(config)
# Similar to `self.model = AutoModel.from_config(config)` but allows to change the base model name if needed in the child class
setattr(self, self.base_model_prefix, AutoModel.from_config(config))
self.qa_outputs = nn.Linear(config.hidden_size, 2)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return getattr(self, self.base_model_prefix).embed_tokens
def set_input_embeddings(self, value):
getattr(self, self.base_model_prefix).embed_tokens = value
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = 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,
start_positions: Optional[torch.LongTensor] = None,
end_positions: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> QuestionAnsweringModelOutput:
outputs: BaseModelOutputWithPast = getattr(self, self.base_model_prefix)(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
**kwargs,
)
sequence_output = outputs.last_hidden_state
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
loss = None
if start_positions is not None and end_positions is not None:
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
return QuestionAnsweringModelOutput(
loss=loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
| GenericForQuestionAnswering |
python | django__django | tests/test_runner/tests.py | {
"start": 32580,
"end": 33486
} | class ____(TransactionTestCase):
"""
Creating the same models in different test methods receive the same PK
values since the sequences are reset before each test method.
"""
available_apps = ["test_runner"]
reset_sequences = True
def _test(self):
# Regular model
p = Person.objects.create(first_name="Jack", last_name="Smith")
self.assertEqual(p.pk, 1)
# Auto-created many-to-many through model
p.friends.add(Person.objects.create(first_name="Jacky", last_name="Smith"))
self.assertEqual(p.friends.through.objects.first().pk, 1)
# Many-to-many through model
b = B.objects.create()
t = Through.objects.create(person=p, b=b)
self.assertEqual(t.pk, 1)
def test_autoincrement_reset1(self):
self._test()
def test_autoincrement_reset2(self):
self._test()
| AutoIncrementResetTest |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 374255,
"end": 374817
} | class ____:
def test_empty_bstring_array_is_falsey(self):
assert_(not np.array([''], dtype=str))
def test_whitespace_bstring_array_is_truthy(self):
a = np.array(['spam'], dtype=str)
a[0] = ' \0\0'
assert_(a)
def test_all_null_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=str)
a[0] = '\0\0\0\0'
assert_(not a)
def test_null_inside_bstring_array_is_truthy(self):
a = np.array(['spam'], dtype=str)
a[0] = ' \0 \0'
assert_(a)
| TestBytestringArrayNonzero |
python | doocs__leetcode | solution/3300-3399/3367.Maximize Sum of Weights after Edge Removals/Solution.py | {
"start": 0,
"end": 724
} | class ____:
def maximizeSumOfWeights(self, edges: List[List[int]], k: int) -> int:
def dfs(u: int, fa: int) -> Tuple[int, int]:
s = 0
t = []
for v, w in g[u]:
if v == fa:
continue
a, b = dfs(v, u)
s += a
if (d := (w + b - a)) > 0:
t.append(d)
t.sort(reverse=True)
return s + sum(t[:k]), s + sum(t[: k - 1])
n = len(edges) + 1
g: List[List[Tuple[int, int]]] = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
x, y = dfs(0, -1)
return max(x, y)
| Solution |
python | ray-project__ray | python/ray/dashboard/modules/serve/tests/test_serve_dashboard.py | {
"start": 21679,
"end": 21898
} | class ____:
def __init__(self):
pass
def __call__(self):
return "test"
deployment_app = DeploymentClass.bind()
@serve.deployment(name="hello_world", num_replicas=2, version="v2")
| DeploymentClass |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/pairwise.py | {
"start": 2987,
"end": 10044
} | class ____(BaseEvaluator):
"""
Pairwise comparison evaluator.
Evaluates the quality of a response vs. a "reference" response given a question by
having an LLM judge which response is better.
Outputs whether the `response` given is better than the `reference` response.
Args:
eval_template (Optional[Union[str, BasePromptTemplate]]):
The template to use for evaluation.
enforce_consensus (bool): Whether to enforce consensus (consistency if we
flip the order of the answers). Defaults to True.
"""
def __init__(
self,
llm: Optional[LLM] = None,
eval_template: Optional[Union[BasePromptTemplate, str]] = None,
parser_function: Callable[
[str], Tuple[Optional[bool], Optional[float], Optional[str]]
] = _default_parser_function,
enforce_consensus: bool = True,
) -> None:
self._llm = llm or Settings.llm
self._eval_template: BasePromptTemplate
if isinstance(eval_template, str):
self._eval_template = PromptTemplate(eval_template)
else:
self._eval_template = eval_template or DEFAULT_EVAL_TEMPLATE
self._enforce_consensus = enforce_consensus
self._parser_function = parser_function
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
return {
"eval_template": self._eval_template,
}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
if "eval_template" in prompts:
self._eval_template = prompts["eval_template"]
async def _get_eval_result(
self,
query: str,
response: str,
second_response: str,
reference: Optional[str],
) -> EvaluationResult:
"""Get evaluation result."""
eval_response = await self._llm.apredict(
prompt=self._eval_template,
query=query,
answer_1=response,
answer_2=second_response,
reference=reference or "",
)
# Extract from response
passing, score, feedback = self._parser_function(eval_response)
if passing is None and score is None and feedback is None:
return EvaluationResult(
query=query,
invalid_result=True,
invalid_reason="Output cannot be parsed",
feedback=eval_response,
)
else:
return EvaluationResult(
query=query,
response=eval_response,
passing=passing,
score=score,
feedback=eval_response,
pairwise_source=EvaluationSource.ORIGINAL,
)
async def _resolve_results(
self,
eval_result: EvaluationResult,
flipped_eval_result: EvaluationResult,
) -> EvaluationResult:
"""
Resolve eval results from evaluation + flipped evaluation.
Args:
eval_result (EvaluationResult): Result when answer_1 is shown first
flipped_eval_result (EvaluationResult): Result when answer_2 is shown first
Returns:
EvaluationResult: The final evaluation result
"""
# add pairwise_source to eval_result and flipped_eval_result
eval_result.pairwise_source = EvaluationSource.ORIGINAL
flipped_eval_result.pairwise_source = EvaluationSource.FLIPPED
# count the votes for each of the 2 answers
votes_1 = 0.0
votes_2 = 0.0
if eval_result.score is not None and flipped_eval_result.score is not None:
votes_1 = eval_result.score + (1 - flipped_eval_result.score)
votes_2 = (1 - eval_result.score) + flipped_eval_result.score
if votes_1 + votes_2 != 2: # each round, the judge can give a total of 1 vote
raise ValueError("Impossible score results. Total amount of votes is 2.")
# get the judges (original and flipped) who voted for answer_1
voters_1 = [eval_result] * (eval_result.score == 1.0) + [
flipped_eval_result
] * (flipped_eval_result.score == 0.0)
# get the judges (original and flipped) who voted for answer_2
voters_2 = [eval_result] * (eval_result.score == 0.0) + [
flipped_eval_result
] * (flipped_eval_result.score == 1.0)
if votes_1 > votes_2:
return voters_1[0] # return any voter for answer_1
elif votes_2 > votes_1:
return voters_2[0] # return any vote for answer_2
else:
if (
eval_result.score == 0.5
): # votes_1 == votes_2 can only happen if both are 1.0 (so actual tie)
# doesn't matter which one we return here
return eval_result
else: # Inconclusive case!
return EvaluationResult(
query=eval_result.query,
response="",
passing=None,
score=0.5,
feedback="",
pairwise_source=EvaluationSource.NEITHER,
)
async def aevaluate(
self,
query: Optional[str] = None,
response: Optional[str] = None,
contexts: Optional[Sequence[str]] = None,
second_response: Optional[str] = None,
reference: Optional[str] = None,
sleep_time_in_seconds: int = 0,
**kwargs: Any,
) -> EvaluationResult:
del kwargs # Unused
del contexts # Unused
if query is None or response is None or second_response is None:
raise ValueError(
"query, response, second_response, and reference must be provided"
)
await asyncio.sleep(sleep_time_in_seconds)
eval_result = await self._get_eval_result(
query, response, second_response, reference
)
if self._enforce_consensus and not eval_result.invalid_result:
# Flip the order of the answers and see if the answer is consistent
# (which means that the score should flip from 0 to 1 and vice-versa)
# if not, then we return a tie
flipped_eval_result = await self._get_eval_result(
query, second_response, response, reference
)
if not flipped_eval_result.invalid_result:
resolved_eval_result = await self._resolve_results(
eval_result, flipped_eval_result
)
else:
resolved_eval_result = EvaluationResult(
query=eval_result.query,
response=eval_result.response,
feedback=flipped_eval_result.response,
invalid_result=True,
invalid_reason="Output cannot be parsed.",
)
else:
resolved_eval_result = eval_result
return resolved_eval_result
| PairwiseComparisonEvaluator |
python | ray-project__ray | rllib/models/tf/fcnet.py | {
"start": 450,
"end": 5564
} | class ____(TFModelV2):
"""Generic fully connected network implemented in ModelV2 API."""
def __init__(
self,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
num_outputs: int,
model_config: ModelConfigDict,
name: str,
):
super(FullyConnectedNetwork, self).__init__(
obs_space, action_space, num_outputs, model_config, name
)
hiddens = list(model_config.get("fcnet_hiddens", [])) + list(
model_config.get("post_fcnet_hiddens", [])
)
activation = model_config.get("fcnet_activation")
if not model_config.get("fcnet_hiddens", []):
activation = model_config.get("post_fcnet_activation")
activation = get_activation_fn(activation)
no_final_linear = model_config.get("no_final_linear")
vf_share_layers = model_config.get("vf_share_layers")
free_log_std = model_config.get("free_log_std")
# Generate free-floating bias variables for the second half of
# the outputs.
if free_log_std:
assert num_outputs % 2 == 0, (
"num_outputs must be divisible by two",
num_outputs,
)
num_outputs = num_outputs // 2
self.log_std_var = tf.Variable(
[0.0] * num_outputs, dtype=tf.float32, name="log_std"
)
# We are using obs_flat, so take the flattened shape as input.
inputs = tf.keras.layers.Input(
shape=(int(np.prod(obs_space.shape)),), name="observations"
)
# Last hidden layer output (before logits outputs).
last_layer = inputs
# The action distribution outputs.
logits_out = None
i = 1
# Create layers 0 to second-last.
for size in hiddens[:-1]:
last_layer = tf.keras.layers.Dense(
size,
name="fc_{}".format(i),
activation=activation,
kernel_initializer=normc_initializer(1.0),
)(last_layer)
i += 1
# The last layer is adjusted to be of size num_outputs, but it's a
# layer with activation.
if no_final_linear and num_outputs:
logits_out = tf.keras.layers.Dense(
num_outputs,
name="fc_out",
activation=activation,
kernel_initializer=normc_initializer(1.0),
)(last_layer)
# Finish the layers with the provided sizes (`hiddens`), plus -
# iff num_outputs > 0 - a last linear layer of size num_outputs.
else:
if len(hiddens) > 0:
last_layer = tf.keras.layers.Dense(
hiddens[-1],
name="fc_{}".format(i),
activation=activation,
kernel_initializer=normc_initializer(1.0),
)(last_layer)
if num_outputs:
logits_out = tf.keras.layers.Dense(
num_outputs,
name="fc_out",
activation=None,
kernel_initializer=normc_initializer(0.01),
)(last_layer)
# Adjust num_outputs to be the number of nodes in the last layer.
else:
self.num_outputs = ([int(np.prod(obs_space.shape))] + hiddens[-1:])[-1]
# Concat the log std vars to the end of the state-dependent means.
if free_log_std and logits_out is not None:
def tiled_log_std(x):
return tf.tile(tf.expand_dims(self.log_std_var, 0), [tf.shape(x)[0], 1])
log_std_out = tf.keras.layers.Lambda(tiled_log_std)(inputs)
logits_out = tf.keras.layers.Concatenate(axis=1)([logits_out, log_std_out])
last_vf_layer = None
if not vf_share_layers:
# Build a parallel set of hidden layers for the value net.
last_vf_layer = inputs
i = 1
for size in hiddens:
last_vf_layer = tf.keras.layers.Dense(
size,
name="fc_value_{}".format(i),
activation=activation,
kernel_initializer=normc_initializer(1.0),
)(last_vf_layer)
i += 1
value_out = tf.keras.layers.Dense(
1,
name="value_out",
activation=None,
kernel_initializer=normc_initializer(0.01),
)(last_vf_layer if last_vf_layer is not None else last_layer)
self.base_model = tf.keras.Model(
inputs, [(logits_out if logits_out is not None else last_layer), value_out]
)
def forward(
self,
input_dict: Dict[str, TensorType],
state: List[TensorType],
seq_lens: TensorType,
) -> (TensorType, List[TensorType]):
model_out, self._value_out = self.base_model(input_dict["obs_flat"])
return model_out, state
def value_function(self) -> TensorType:
return tf.reshape(self._value_out, [-1])
| FullyConnectedNetwork |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 2860,
"end": 2990
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(hidden=True)
| CustomPollManager |
python | jina-ai__jina | jina/excepts.py | {
"start": 1040,
"end": 1145
} | class ____(Exception, BaseJinaException):
"""A wrongly defined Flow on the server side"""
| BadServerFlow |
python | pyca__cryptography | tests/hazmat/primitives/test_camellia.py | {
"start": 1766,
"end": 2251
} | class ____:
test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "Camellia"),
["camellia-ofb.txt"],
lambda key, **kwargs: Camellia(binascii.unhexlify(key)),
lambda iv, **kwargs: OFB(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
Camellia(b"\x00" * 16), CFB(b"\x00" * 16)
),
skip_message="Does not support Camellia CFB",
)
| TestCamelliaModeOFB |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/unions3.py | {
"start": 633,
"end": 688
} | class ____(metaclass=Metaclass1):
pass
| ClassWithMeta1 |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 146124,
"end": 152493
} | class ____(Request):
"""
Create or update a new model for a task
:param task: Task id
:type task: str
:param uri: URI for the model. Exactly one of uri or override_model_id is a
required.
:type uri: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param override_model_id: Override model ID. If provided, this model is updated
in the task. Exactly one of override_model_id or uri is required.
:type override_model_id: str
:param iteration: Iteration (used to update task statistics)
:type iteration: int
"""
_service = "models"
_action = "update_for_task"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"comment": {"description": "Model comment", "type": "string"},
"iteration": {
"description": "Iteration (used to update task statistics)",
"type": "integer",
},
"name": {
"description": "Model name Unique within the company.",
"type": "string",
},
"override_model_id": {
"description": "Override model ID. If provided, this model is updated in the task. Exactly one of override_model_id or uri is required.",
"type": "string",
},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
"task": {"description": "Task id", "type": "string"},
"uri": {
"description": "URI for the model. Exactly one of uri or override_model_id is a required.",
"type": "string",
},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
uri: Optional[str] = None,
name: Optional[str] = None,
comment: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
override_model_id: Optional[str] = None,
iteration: Optional[int] = None,
**kwargs: Any
) -> None:
super(UpdateForTaskRequest, self).__init__(**kwargs)
self.task = task
self.uri = uri
self.name = name
self.comment = comment
self.tags = tags
self.system_tags = system_tags
self.override_model_id = override_model_id
self.iteration = iteration
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("uri")
def uri(self) -> Optional[str]:
return self._property_uri
@uri.setter
def uri(self, value: Optional[str]) -> None:
if value is None:
self._property_uri = None
return
self.assert_isinstance(value, "uri", six.string_types)
self._property_uri = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("comment")
def comment(self) -> Optional[str]:
return self._property_comment
@comment.setter
def comment(self, value: Optional[str]) -> None:
if value is None:
self._property_comment = None
return
self.assert_isinstance(value, "comment", six.string_types)
self._property_comment = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("override_model_id")
def override_model_id(self) -> Optional[str]:
return self._property_override_model_id
@override_model_id.setter
def override_model_id(self, value: Optional[str]) -> None:
if value is None:
self._property_override_model_id = None
return
self.assert_isinstance(value, "override_model_id", six.string_types)
self._property_override_model_id = value
@schema_property("iteration")
def iteration(self) -> Optional[int]:
return self._property_iteration
@iteration.setter
def iteration(self, value: Optional[int]) -> None:
if value is None:
self._property_iteration = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "iteration", six.integer_types)
self._property_iteration = value
| UpdateForTaskRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1402235,
"end": 1403234
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'renamed' event on a given issue or pull request"""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "current_title", "previous_title", "subject")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifies the date and time when the object was created."""
current_title = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="currentTitle")
"""Identifies the current title of the issue or pull request."""
previous_title = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="previousTitle")
"""Identifies the previous title of the issue or pull request."""
subject = sgqlc.types.Field(sgqlc.types.non_null("RenamedTitleSubject"), graphql_name="subject")
"""Subject that was renamed."""
| RenamedTitleEvent |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 7961,
"end": 8268
} | class ____(graphene.ObjectType):
numMaterialized = graphene.NonNull(graphene.Int)
numPartitions = graphene.NonNull(graphene.Int)
numFailed = graphene.NonNull(graphene.Int)
numMaterializing = graphene.NonNull(graphene.Int)
class Meta:
name = "PartitionStats"
| GraphenePartitionStats |
python | huggingface__transformers | src/transformers/models/vaultgemma/modeling_vaultgemma.py | {
"start": 2140,
"end": 2824
} | class ____(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
# Llama does x.to(float16) * w whilst VaultGemma is (x * w).to(float16)
# See https://github.com/huggingface/transformers/pull/29402
output = output * (1.0 + self.weight.float())
return output.type_as(x)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.eps}"
| VaultGemmaRMSNorm |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 17302,
"end": 17378
} | class ____(Qwen2_5_VisionRotaryEmbedding):
pass
| Glm4vVisionRotaryEmbedding |
python | matplotlib__matplotlib | galleries/examples/animation/strip_chart.py | {
"start": 272,
"end": 1861
} | class ____:
def __init__(self, ax, maxt=2, dt=0.02):
self.ax = ax
self.dt = dt
self.maxt = maxt
self.tdata = [0]
self.ydata = [0]
self.line = Line2D(self.tdata, self.ydata)
self.ax.add_line(self.line)
self.ax.set_ylim(-.1, 1.1)
self.ax.set_xlim(0, self.maxt)
def update(self, y):
lastt = self.tdata[-1]
if lastt >= self.tdata[0] + self.maxt: # reset the arrays
self.tdata = [self.tdata[-1]]
self.ydata = [self.ydata[-1]]
self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
self.ax.figure.canvas.draw()
# This slightly more complex calculation avoids floating-point issues
# from just repeatedly adding `self.dt` to the previous value.
t = self.tdata[0] + len(self.tdata) * self.dt
self.tdata.append(t)
self.ydata.append(y)
self.line.set_data(self.tdata, self.ydata)
return self.line,
def emitter(p=0.1):
"""Return a random value in [0, 1) with probability p, else 0."""
while True:
v = np.random.rand()
if v > p:
yield 0.
else:
yield np.random.rand()
# Fixing random state for reproducibility
np.random.seed(19680801 // 10)
fig, ax = plt.subplots()
scope = Scope(ax)
# pass a generator in "emitter" to produce data for the update func
ani = animation.FuncAnimation(fig, scope.update, emitter, interval=50,
blit=True, save_count=100)
plt.show()
# ..tags:: animation, plot-type: line
| Scope |
python | huggingface__transformers | src/transformers/utils/metrics.py | {
"start": 6291,
"end": 15583
} | class ____:
"""Metrics collection for ContinuousBatchProcessor."""
def __init__(self, max_batch_tokens: int):
"""Initialize metrics for continuous batch processor.
Args:
max_batch_tokens: Maximum number of tokens in a batch
"""
self.max_batch_tokens = max_batch_tokens
self._setup_metrics()
def _setup_metrics(self):
"""Initialize OpenTelemetry metrics and tracing if the library is available."""
if not _has_opentelemetry:
logger.info(
"OpenTelemetry is not installed. Metrics and tracing will not be recorded."
"You can install it with `pip install opentelemetry-api>=1.30.0`"
)
return
self.meter = metrics.get_meter("transformers.generation.continuous_batch_processor")
# Define appropriate buckets for TTFT (typically ranges from ~50ms to several seconds)
ttft_buckets = [10, 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 2000, 5000, 10000]
self.ttft_histogram = self.meter.create_histogram(
name="ttft_milliseconds",
description="Time to first token in milliseconds",
unit="ms",
explicit_bucket_boundaries_advisory=ttft_buckets,
)
self.active_requests_gauge = self.meter.create_gauge(
name="active_requests_count",
description="Number of active requests currently being processed",
unit="requests",
)
self.waiting_requests_gauge = self.meter.create_gauge(
name="waiting_requests_count",
description="Number of requests waiting to be processed",
unit="requests",
)
# Define appropriate buckets for request latency (similar to TTFT but with higher upper bounds)
latency_buckets = [50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000]
self.request_latency_histogram = self.meter.create_histogram(
name="request_latency_milliseconds",
description="End-to-end latency for completed requests in milliseconds",
unit="ms",
explicit_bucket_boundaries_advisory=latency_buckets,
)
self.decode_prefill_ratio_gauge = self.meter.create_gauge(
name="decode_prefill_ratio",
description="Ratio of decode tokens to prefill tokens in a batch",
unit="ratio",
)
self.prefill_tokens_counter = self.meter.create_counter(
name="prefill_tokens_processed",
description="Number of prefill tokens processed",
unit="tokens",
)
self.decode_tokens_counter = self.meter.create_counter(
name="decode_tokens_processed",
description="Number of decode tokens processed",
unit="tokens",
)
# Define appropriate buckets for batch fill percentage (0-100%)
batch_fill_buckets = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100]
self.batch_fill_percentage_histogram = self.meter.create_histogram(
name="batch_fill_percentage",
description="Percentage of max_batch_tokens utilized in each batch",
unit="percent",
explicit_bucket_boundaries_advisory=batch_fill_buckets,
)
self.kv_cache_free_memory_gauge = self.meter.create_gauge(
name="kv_cache_free_memory_bytes",
description="Free memory of the PagedAttentionCache in bytes",
unit="bytes",
)
self.kv_cache_memory_gauge = self.meter.create_gauge(
name="kv_cache_memory_bytes",
description="Memory usage of the PagedAttentionCache in bytes",
unit="bytes",
)
@traced
def record_ttft_metric(self, created_time: float, request_id: str) -> None:
"""Record Time to First Token (TTFT).
Args:
created_time: The time the request was created
request_id: The ID of the request
"""
if not _has_opentelemetry:
return
ttft_ms = (time.time() - created_time) * 1000.0
try:
self.ttft_histogram.record(ttft_ms)
logger.debug(f"Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms")
except Exception as e:
logger.warning(f"Failed to record TTFT metric: {e}")
@traced
def record_batch_metrics(self, requests_in_batch: list) -> None:
"""Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
Args:
requests_in_batch: List of request states in the current batch
"""
if not _has_opentelemetry or not requests_in_batch:
return
decode_tokens = 0
prefill_tokens = 0
for state in requests_in_batch:
if state.status == RequestStatus.DECODING:
decode_tokens += 1
elif state.status in [RequestStatus.PREFILLING, RequestStatus.PREFILLING_SPLIT]:
prefill_tokens += len(state.prompt_ids)
total_batch_tokens = decode_tokens + prefill_tokens
try:
if prefill_tokens > 0:
self.prefill_tokens_counter.add(prefill_tokens)
if decode_tokens > 0:
self.decode_tokens_counter.add(decode_tokens)
if prefill_tokens > 0:
ratio = decode_tokens / prefill_tokens
self.decode_prefill_ratio_gauge.set(ratio)
fill_percentage = (total_batch_tokens / self.max_batch_tokens) * 100.0
self.batch_fill_percentage_histogram.record(fill_percentage)
logger.debug(
f"Batch metrics: {decode_tokens} decode tokens, {prefill_tokens} prefill tokens, "
f"batch fill: {fill_percentage:.2f}% ({total_batch_tokens}/{self.max_batch_tokens})"
)
except Exception as e:
logger.warning(f"Failed to record batch metrics: {e}")
@traced
def record_kv_cache_memory_metrics(self, cache) -> None:
"""Record memory usage of the PagedAttentionCache without GPU synchronization.
This calculates the theoretical memory usage based on cache configuration
and the number of blocks currently in use.
Args:
cache: The PagedAttentionCache object to measure
"""
if not _has_opentelemetry:
return
try:
# Retrieve the memory footprint of the cache
page_size = cache.head_dim * cache.num_key_value_heads
page_mem_in_bytes = page_size * cache.dtype.itemsize
# When a block is allocated, it is for both K and V, so we multiply by 2
# It's also allocated across all cache tensors, so we multiply by the nb of tensors: len(cache.key_cache)
block_mem_in_bytes = 2 * len(cache.key_cache) * cache.block_size * page_mem_in_bytes
# Retrieve the number of used and free blocks
free_blocks = cache.get_num_free_blocks()
used_blocks = cache.num_blocks - free_blocks
# Convert that into used and free memory in bytes
used_memory_bytes = used_blocks * block_mem_in_bytes
free_memory_bytes = free_blocks * block_mem_in_bytes
# Update the telemetry gauges and add a message in the logs
self.kv_cache_memory_gauge.set(used_memory_bytes)
self.kv_cache_free_memory_gauge.set(free_memory_bytes)
logger.debug(
f"KV Cache memory: {used_memory_bytes / (1024 * 1024):.2f}MB, "
f"Used blocks: {used_blocks}/{cache.num_blocks} "
f"({used_blocks / cache.num_blocks * 100:.1f}%)"
)
except Exception as e:
logger.warning(f"Failed to record KV cache memory metrics: {e}")
@traced
def record_queue_metrics(self, active_requests: int, waiting_requests: int) -> None:
"""Record metrics about active and waiting requests.
Args:
active_requests: Number of active requests
waiting_requests: Number of waiting requests
"""
if not _has_opentelemetry:
return
try:
self.active_requests_gauge.set(active_requests)
self.waiting_requests_gauge.set(waiting_requests)
logger.debug(f"Queue metrics: {active_requests} active requests, {waiting_requests} waiting requests")
except Exception as e:
logger.warning(f"Failed to record queue metrics: {e}")
@traced
def record_request_completion(self, created_time: float, request_id: str) -> None:
"""Record metrics about a completed request.
Args:
created_time: The time the request was created
request_id: The ID of the request
"""
if not _has_opentelemetry:
return
latency_ms = (time.time() - created_time) * 1000.0
try:
self.request_latency_histogram.record(latency_ms)
logger.debug(f"Recorded request completion for {request_id}: {latency_ms:.2f}ms")
except Exception as e:
logger.warning(f"Failed to record request completion metric: {e}")
| ContinuousBatchProcessorMetrics |
python | PrefectHQ__prefect | tests/client/test_prefect_client.py | {
"start": 105633,
"end": 106801
} | class ____:
def test_enabled_ephemeral(self, enable_ephemeral_server):
prefect_client = get_client()
assert prefect_client.server_type == ServerType.EPHEMERAL
assert prefect_client._client.enable_csrf_support
async def test_enabled_server_type(self, hosted_api_server):
async with PrefectClient(hosted_api_server) as prefect_client:
assert prefect_client.server_type == ServerType.SERVER
assert prefect_client._client.enable_csrf_support
async def test_not_enabled_server_type_cloud(self):
async with PrefectClient(PREFECT_CLOUD_API_URL.value()) as prefect_client:
assert prefect_client.server_type == ServerType.CLOUD
assert not prefect_client._client.enable_csrf_support
async def test_disabled_setting_disabled(self, hosted_api_server):
with temporary_settings({PREFECT_CLIENT_CSRF_SUPPORT_ENABLED: False}):
async with PrefectClient(hosted_api_server) as prefect_client:
assert prefect_client.server_type == ServerType.SERVER
assert not prefect_client._client.enable_csrf_support
| TestPrefectClientCsrfSupport |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 161123,
"end": 168198
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
@testing.fixture
def t_fixture(self):
m = MetaData()
t = Table(
"tab1",
m,
Column("arrval", ARRAY(Integer)),
Column("arrenum", ARRAY(Enum(MyEnum))),
Column("arrstring", ARRAY(String)),
Column("data", Integer),
)
return t
null_comparisons = testing.combinations(
lambda col: any_(col) == None,
lambda col: col.any_() == None,
lambda col: any_(col) == null(),
lambda col: col.any_() == null(),
lambda col: null() == any_(col),
lambda col: null() == col.any_(),
lambda col: None == any_(col),
lambda col: None == col.any_(),
argnames="expr",
)
@null_comparisons
@testing.combinations("int", "array", argnames="datatype")
def test_any_generic_null(self, datatype, expr, t_fixture):
col = t_fixture.c.data if datatype == "int" else t_fixture.c.arrval
self.assert_compile(expr(col), "NULL = ANY (tab1.%s)" % col.name)
@null_comparisons
@testing.combinations("int", "array", argnames="datatype")
def test_any_generic_null_negate(self, datatype, expr, t_fixture):
col = t_fixture.c.data if datatype == "int" else t_fixture.c.arrval
self.assert_compile(
~expr(col), "NOT (NULL = ANY (tab1.%s))" % col.name
)
@testing.variation("operator", ["any", "all"])
@testing.variation(
"datatype", ["int", "array", "arraystring", "arrayenum"]
)
def test_what_type_is_any_all(
self,
datatype: testing.Variation,
t_fixture,
operator: testing.Variation,
):
"""test for #12874"""
if datatype.int:
col = t_fixture.c.data
value = 5
expected_type_affinity = Integer
elif datatype.array:
col = t_fixture.c.arrval
value = 25
expected_type_affinity = Integer
elif datatype.arraystring:
col = t_fixture.c.arrstring
value = "a string"
expected_type_affinity = String
elif datatype.arrayenum:
col = t_fixture.c.arrenum
value = MyEnum.TWO
expected_type_affinity = Enum
else:
datatype.fail()
if operator.any:
boolean_expr = value == any_(col)
elif operator.all:
boolean_expr = value == all_(col)
else:
operator.fail()
# using isinstance so things work out for Enum which has type affinity
# of String
assert isinstance(boolean_expr.left.type, expected_type_affinity)
@testing.fixture(
params=[
("ANY", any_),
("ANY", lambda x: x.any_()),
("ALL", all_),
("ALL", lambda x: x.all_()),
]
)
def any_all_operators(self, request):
return request.param
def test_array(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 == fn(t.c.arrval),
f":param_1 = {op} (tab1.arrval)",
checkparams={"param_1": 5},
)
def test_comparator_inline_negate(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 != fn(t.c.arrval),
f":param_1 != {op} (tab1.arrval)",
checkparams={"param_1": 5},
)
@testing.combinations(
(operator.eq, "="),
(operator.ne, "!="),
(operator.gt, ">"),
(operator.le, "<="),
argnames="operator,opstring",
)
def test_comparator_outer_negate(
self, t_fixture, any_all_operators, operator, opstring
):
"""test #10817"""
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
~(operator(5, fn(t.c.arrval))),
f"NOT (:param_1 {opstring} {op} (tab1.arrval))",
checkparams={"param_1": 5},
)
def test_comparator_array(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 > fn(t.c.arrval),
f":param_1 > {op} (tab1.arrval)",
checkparams={"param_1": 5},
)
def test_comparator_array_wexpr(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
t.c.data > fn(t.c.arrval),
f"tab1.data > {op} (tab1.arrval)",
checkparams={},
)
def test_illegal_ops(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
assert_raises_message(
exc.ArgumentError,
"Only comparison operators may be used with ANY/ALL",
lambda: 5 + fn(t.c.arrval),
)
# TODO:
# this is invalid but doesn't raise an error,
# as the left-hand side just does its thing. Types
# would need to reject their right-hand side.
self.assert_compile(
t.c.data + fn(t.c.arrval), f"tab1.data + {op} (tab1.arrval)"
)
def test_array_expression(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 == fn(t.c.arrval[5:6] + postgresql.array([3, 4])),
f"%(param_1)s = {op} (tab1.arrval[%(arrval_1)s:%(arrval_2)s] || "
"ARRAY[%(param_2)s, %(param_3)s])",
checkparams={
"arrval_2": 6,
"param_1": 5,
"param_3": 4,
"arrval_1": 5,
"param_2": 3,
},
dialect="postgresql",
)
def test_subq(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 == fn(select(t.c.data).where(t.c.data < 10).scalar_subquery()),
f":param_1 = {op} (SELECT tab1.data "
"FROM tab1 WHERE tab1.data < :data_1)",
checkparams={"data_1": 10, "param_1": 5},
)
def test_scalar_values(self, t_fixture, any_all_operators):
t = t_fixture
op, fn = any_all_operators
self.assert_compile(
5 == fn(values(t.c.data).data([(1,), (42,)]).scalar_values()),
f":param_1 = {op} (VALUES (:param_2), (:param_3))",
checkparams={"param_1": 5, "param_2": 1, "param_3": 42},
)
@testing.combinations(any_, all_, argnames="fn")
def test_values_illegal(self, t_fixture, fn):
t = t_fixture
with expect_raises_message(
exc.ArgumentError,
"SQL expression element expected, got .* "
"To create a column expression from a VALUES clause, "
r"use the .scalar_values\(\) method.",
):
fn(values(t.c.data).data([(1,), (42,)]))
| AnyAllTest |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 11538,
"end": 11717
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
capabilities: ServerCapabilities
server_info: Optional[Info] = None
@dataclasses.dataclass(frozen=True)
| InitializeResult |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 63796,
"end": 72811
} | class ____(Qwen2_5OmniThinkerForConditionalGeneration):
_no_split_modules = [
"Qwen3OmniMoeAudioEncoderLayer",
"Qwen3OmniMoeThinkerTextDecoderLayer",
]
_can_record_outputs = {
"hidden_states": Qwen3OmniMoeThinkerTextDecoderLayer,
"attentions": Qwen3OmniMoeThinkerTextAttention,
"router_logits": OutputRecorder(Qwen3OmniMoeThinkerTextSparseMoeBlock, index=1),
}
def __init__(self, config):
super().__init__(config)
self.num_experts = config.text_config.num_experts
self.num_experts_per_tok = config.text_config.num_experts_per_tok
self.router_aux_loss_coef = config.text_config.router_aux_loss_coef
def get_audio_features(
self,
input_features: torch.FloatTensor,
feature_attention_mask: Optional[torch.LongTensor] = None,
audio_feature_lengths: Optional[torch.LongTensor] = None,
):
"""
Encodes audios into continuous embeddings that can be forwarded to the language model.
Args:
input_features (`torch.FloatTensor`):
The tensors corresponding to the input audios.
feature_attention_mask (`torch.LongTensor`, *optional*):
Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:
audio_feature_lengths (`torch.LongTensor` of shape `(num_audios)`, *optional*):
The length of feature shape of each audio in LLM.
"""
if feature_attention_mask is not None:
audio_feature_lengths = torch.sum(feature_attention_mask, dim=1)
input_features = input_features.permute(0, 2, 1)[feature_attention_mask.bool()].permute(1, 0)
else:
audio_feature_lengths = None
feature_lens = audio_feature_lengths if audio_feature_lengths is not None else feature_attention_mask.sum(-1)
audio_outputs = self.audio_tower(
input_features,
feature_lens=feature_lens,
)
audio_features = audio_outputs.last_hidden_state
return audio_features
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids=None,
input_features=None,
pixel_values=None,
pixel_values_videos=None,
image_grid_thw=None,
video_grid_thw=None,
attention_mask=None,
feature_attention_mask=None,
audio_feature_lengths=None,
position_ids=None,
past_key_values=None,
inputs_embeds=None,
rope_deltas=None,
labels=None,
use_cache=None,
output_router_logits: Optional[bool] = None,
use_audio_in_video=None,
cache_position=None,
video_second_per_grid=None,
**kwargs,
) -> Union[tuple, Qwen3OmniMoeThinkerCausalLMOutputWithPast]:
output_router_logits = (
output_router_logits if output_router_logits is not None else self.config.text_config.output_router_logits
)
if inputs_embeds is None:
# 1. Extract the input embeddings
inputs_embeds = self.get_input_embeddings()(input_ids)
visual_embeds_multiscale = None
visual_pos_masks = None
image_mask, video_mask = None, None
# 2. Merge text , audios , image and video
if input_features is not None:
audio_features = self.get_audio_features(
input_features,
feature_attention_mask=feature_attention_mask,
audio_feature_lengths=audio_feature_lengths,
)
audio_features = audio_features.to(inputs_embeds.device, inputs_embeds.dtype)
_, _, audio_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_features)
if pixel_values is not None:
image_embeds, image_embeds_multiscale = self.get_image_features(pixel_values, image_grid_thw)
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
image_mask, _, _ = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if pixel_values_videos is not None:
video_embeds, video_embeds_multiscale = self.get_video_features(pixel_values_videos, video_grid_thw)
video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
_, video_mask, _ = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
)
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
if image_mask is not None and video_mask is not None:
image_mask = image_mask[..., 0]
video_mask = video_mask[..., 0]
visual_pos_masks = video_mask | image_mask
visual_embeds_multiscale_joint = ()
image_mask_joint = image_mask[visual_pos_masks]
video_mask_joint = video_mask[visual_pos_masks]
for img_embed, vid_embed in zip(image_embeds_multiscale, video_embeds_multiscale):
embed_joint = img_embed.new_zeros(visual_pos_masks.sum(), img_embed.shape[-1])
embed_joint[image_mask_joint, :] = img_embed
embed_joint[video_mask_joint, :] = vid_embed
visual_embeds_multiscale_joint = visual_embeds_multiscale_joint + (embed_joint,)
visual_embeds_multiscale = visual_embeds_multiscale_joint
elif image_mask is not None:
image_mask = image_mask[..., 0]
visual_embeds_multiscale = image_embeds_multiscale
visual_pos_masks = image_mask
elif video_mask is not None:
video_mask = video_mask[..., 0]
visual_embeds_multiscale = video_embeds_multiscale
visual_pos_masks = video_mask
if feature_attention_mask is not None:
audio_feature_lengths = torch.sum(feature_attention_mask, dim=1)
else:
audio_feature_lengths = None
if attention_mask is not None and position_ids is None:
if (
cache_position is None
or (cache_position is not None and cache_position[0] == 0)
or self.rope_deltas is None
):
delta0 = (1 - attention_mask).sum(dim=-1).unsqueeze(1)
position_ids, rope_deltas = self.get_rope_index(
input_ids,
image_grid_thw,
video_grid_thw,
attention_mask,
use_audio_in_video,
audio_feature_lengths,
video_second_per_grid,
)
rope_deltas = rope_deltas - delta0
self.rope_deltas = rope_deltas
else:
batch_size, seq_length = input_ids.shape
delta = cache_position[0] + self.rope_deltas if cache_position is not None else 0
position_ids = torch.arange(seq_length, device=input_ids.device)
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
position_ids = position_ids.add(delta)
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
outputs = self.model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_router_logits=output_router_logits,
cache_position=cache_position,
deepstack_visual_embeds=visual_embeds_multiscale,
visual_pos_masks=visual_pos_masks,
**kwargs,
)
hidden_states = outputs[0]
logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
loss = self.loss_function(
logits=logits, labels=labels, vocab_size=self.config.get_text_config().vocab_size
)
aux_loss = None
if output_router_logits:
aux_loss = load_balancing_loss_func(
outputs.router_logits,
self.num_experts,
self.num_experts_per_tok,
attention_mask,
)
if labels is not None:
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
return Qwen3OmniMoeThinkerCausalLMOutputWithPast(
loss=loss,
logits=logits,
aux_loss=aux_loss,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
past_key_values=outputs.past_key_values,
rope_deltas=self.rope_deltas,
)
| Qwen3OmniMoeThinkerForConditionalGeneration |
python | pandas-dev__pandas | web/pandas_web.py | {
"start": 1423,
"end": 18068
} | class ____:
"""
Built-in context preprocessors.
Context preprocessors are functions that receive the context used to
render the templates, and enriches it with additional information.
The original context is obtained by parsing ``config.yml``, and
anything else needed just be added with context preprocessors.
"""
@staticmethod
def current_year(context):
"""
Add the current year to the context, so it can be used for the copyright
note, or other places where it is needed.
"""
context["current_year"] = datetime.datetime.now().year
return context
@staticmethod
def navbar_add_info(context):
"""
Items in the main navigation bar can be direct links, or dropdowns with
subitems. This context preprocessor adds a boolean field
``has_subitems`` that tells which one of them every element is. It
also adds a ``slug`` field to be used as a CSS id.
"""
for i, item in enumerate(context["navbar"]):
context["navbar"][i] = dict(
item,
has_subitems=isinstance(item["target"], list),
slug=(item["name"].replace(" ", "-").lower()),
)
return context
@staticmethod
def blog_add_posts(context):
"""
Given the blog feed defined in the configuration yaml, this context
preprocessor fetches the posts in the feeds, and returns the relevant
information for them (sorted from newest to oldest).
"""
tag_expr = re.compile("<.*?>")
posts = []
# posts from the file system
if context["blog"]["posts_path"]:
posts_path = context["source_path"] / context["blog"]["posts_path"]
for fname in posts_path.iterdir():
if fname.name.startswith("index."):
continue
link = f"/{context['blog']['posts_path']}/{fname.stem}.html"
md = markdown.Markdown(
extensions=context["main"]["markdown_extensions"]
)
with fname.open(encoding="utf-8") as f:
html = md.convert(f.read())
title = md.Meta["title"][0]
summary = re.sub(tag_expr, "", html)
try:
body_position = summary.index(title) + len(title)
except ValueError as err:
raise ValueError(
f'Blog post "{fname}" should have a markdown header '
f'corresponding to its "Title" element "{title}"'
) from err
summary = " ".join(summary[body_position:].split(" ")[:30])
posts.append(
{
"title": title,
"author": context["blog"]["author"],
"published": datetime.datetime.strptime(
md.Meta["date"][0], "%Y-%m-%d"
),
"feed": context["blog"]["feed_name"],
"link": link,
"description": summary,
"summary": summary,
}
)
# posts from rss feeds
for feed_url in context["blog"]["feed"]:
feed_data = feedparser.parse(feed_url)
for entry in feed_data.entries:
published = datetime.datetime.fromtimestamp(
time.mktime(entry.published_parsed)
)
summary = re.sub(tag_expr, "", entry.summary)
posts.append(
{
"title": entry.title,
"author": entry.author,
"published": published,
"feed": feed_data["feed"]["title"],
"link": entry.link,
"description": entry.description,
"summary": summary,
}
)
posts.sort(key=operator.itemgetter("published"), reverse=True)
context["blog"]["posts"] = posts[: context["blog"]["num_posts"]]
return context
@staticmethod
def maintainers_add_info(context):
"""
Given the active maintainers defined in the yaml file, it fetches
the GitHub user information for them.
"""
repeated = set(context["maintainers"]["active"]) & set(
context["maintainers"]["inactive"]
)
if repeated:
raise ValueError(f"Maintainers {repeated} are both active and inactive")
maintainers_info = {}
for user in (
context["maintainers"]["active"]
+ context["maintainers"]["inactive"]
+ context["maintainers"]["pandasstubs"]
):
resp = requests.get(
f"https://api.github.com/users/{user}",
headers=GITHUB_API_HEADERS,
timeout=5,
)
if resp.status_code == 403:
sys.stderr.write(
"WARN: GitHub API quota exceeded when fetching maintainers\n"
)
# if we exceed github api quota, we use the github info
# of maintainers saved with the website
resp_bkp = requests.get(
context["main"]["production_url"] + "maintainers.json", timeout=5
)
resp_bkp.raise_for_status()
maintainers_info = resp_bkp.json()
break
resp.raise_for_status()
maintainers_info[user] = resp.json()
context["maintainers"]["github_info"] = maintainers_info
# save the data fetched from github to use it in case we exceed
# git github api quota in the future
with open(
pathlib.Path(context["target_path"]) / "maintainers.json",
"w",
encoding="utf-8",
) as f:
json.dump(maintainers_info, f)
return context
@staticmethod
def home_add_releases(context):
context["releases"] = []
github_repo_url = context["main"]["github_repo_url"]
resp = requests.get(
f"https://api.github.com/repos/{github_repo_url}/releases",
headers=GITHUB_API_HEADERS,
timeout=5,
)
if resp.status_code == 403:
sys.stderr.write("WARN: GitHub API quota exceeded when fetching releases\n")
resp_bkp = requests.get(
context["main"]["production_url"] + "releases.json", timeout=5
)
resp_bkp.raise_for_status()
releases = resp_bkp.json()
else:
resp.raise_for_status()
releases = resp.json()
with open(
pathlib.Path(context["target_path"]) / "releases.json",
"w",
encoding="utf-8",
) as f:
json.dump(releases, f, default=datetime.datetime.isoformat)
for release in releases:
if release["prerelease"]:
continue
published = datetime.datetime.strptime(
release["published_at"], "%Y-%m-%dT%H:%M:%SZ"
)
context["releases"].append(
{
"name": release["tag_name"].lstrip("v"),
"parsed_version": version.parse(release["tag_name"].lstrip("v")),
"tag": release["tag_name"],
"published": published,
"url": (
release["assets"][0]["browser_download_url"]
if release["assets"]
else ""
),
}
)
# sorting out obsolete versions
grouped_releases = itertools.groupby(
context["releases"],
key=lambda r: (r["parsed_version"].major, r["parsed_version"].minor),
)
context["releases"] = [
max(release_group, key=lambda r: r["parsed_version"].minor)
for _, release_group in grouped_releases
]
# sorting releases by version number
context["releases"].sort(key=lambda r: r["parsed_version"], reverse=True)
return context
@staticmethod
def roadmap_pdeps(context):
"""
PDEP's (pandas enhancement proposals) are not part of the bar
navigation. They are included as lists in the "Roadmap" page
and linked from there. This preprocessor obtains the list of
PDEP's in different status from the directory tree and GitHub.
"""
KNOWN_STATUS = {
"Draft",
"Under discussion",
"Accepted",
"Implemented",
"Rejected",
"Withdrawn",
}
context["pdeps"] = collections.defaultdict(list)
# accepted, rejected and implemented
pdeps_path = (
pathlib.Path(context["source_path"]) / context["roadmap"]["pdeps_path"]
)
for pdep in sorted(pdeps_path.iterdir()):
if pdep.suffix != ".md":
continue
with pdep.open() as f:
title = f.readline()[2:] # removing markdown title "# "
status = None
for line in f:
if line.startswith("- Status: "):
status = line.strip().split(": ", 1)[1]
break
if status not in KNOWN_STATUS:
raise RuntimeError(
f'PDEP "{pdep}" status "{status}" is unknown. '
f"Should be one of: {KNOWN_STATUS}"
)
html_file = pdep.with_suffix(".html").name
context["pdeps"][status].append(
{
"title": title,
"url": f"pdeps/{html_file}",
}
)
# under discussion
github_repo_url = context["main"]["github_repo_url"]
resp = requests.get(
"https://api.github.com/search/issues?"
f"q=is:pr is:open label:PDEP draft:false repo:{github_repo_url}",
headers=GITHUB_API_HEADERS,
timeout=5,
)
if resp.status_code == 403:
sys.stderr.write("WARN: GitHub API quota exceeded when fetching pdeps\n")
resp_bkp = requests.get(
context["main"]["production_url"] + "pdeps.json", timeout=5
)
resp_bkp.raise_for_status()
pdeps = resp_bkp.json()
else:
resp.raise_for_status()
pdeps = resp.json()
with open(
pathlib.Path(context["target_path"]) / "pdeps.json", "w", encoding="utf-8"
) as f:
json.dump(pdeps, f)
compiled_pattern = re.compile(r"^PDEP-(\d+)")
def sort_pdep(pdep: dict) -> int:
title = pdep["title"]
match = compiled_pattern.match(title)
if not match:
msg = f"""Could not find PDEP number in '{title}'. Please make sure to
write the title as: 'PDEP-num: {title}'."""
raise ValueError(msg)
return int(match[1])
context["pdeps"]["Under discussion"].extend(
{"title": pdep["title"], "url": pdep["html_url"]}
for pdep in sorted(pdeps["items"], key=sort_pdep)
)
return context
def get_callable(obj_as_str: str) -> object:
"""
Get a Python object from its string representation.
For example, for ``sys.stdout.write`` would import the module ``sys``
and return the ``write`` function.
"""
components = obj_as_str.split(".")
attrs = []
while components:
try:
obj = importlib.import_module(".".join(components))
except ImportError:
attrs.insert(0, components.pop())
else:
break
if not obj:
raise ImportError(f'Could not import "{obj_as_str}"')
for attr in attrs:
obj = getattr(obj, attr)
return obj
def get_context(config_fname: pathlib.Path, **kwargs):
"""
Load the config yaml as the base context, and enrich it with the
information added by the context preprocessors defined in the file.
"""
with config_fname.open(encoding="utf-8") as f:
context = yaml.safe_load(f)
context["source_path"] = config_fname.parent
context.update(kwargs)
preprocessors = (
get_callable(context_prep)
for context_prep in context["main"]["context_preprocessors"]
)
for preprocessor in preprocessors:
context = preprocessor(context)
msg = f"{preprocessor.__name__} is missing the return statement"
assert context is not None, msg
return context
def get_source_files(source_path: pathlib.Path) -> typing.Generator[str, None, None]:
"""
Generate the list of files present in the source directory.
"""
for path in source_path.rglob("*"):
if path.is_file():
yield path.relative_to(source_path)
def extend_base_template(content: str, base_template: str) -> str:
"""
Wrap document to extend the base template, before it is rendered with
Jinja2.
"""
result = '{% extends "' + base_template + '" %}'
result += "{% block body %}"
result += content
result += "{% endblock %}"
return result
def main(
source_path: pathlib.Path,
target_path: pathlib.Path,
) -> int:
"""
Copy every file in the source directory to the target directory.
For ``.md`` and ``.html`` files, render them with the context
before copying them. ``.md`` files are transformed to HTML.
"""
# Sanity check: validate that versions.json is valid JSON
versions_path = source_path / "versions.json"
with versions_path.open(encoding="utf-8") as f:
try:
json.load(f)
except json.JSONDecodeError as e:
raise RuntimeError(
f"Invalid versions.json: {e}. Ensure it is valid JSON."
) from e
config_fname = source_path / "config.yml"
shutil.rmtree(target_path, ignore_errors=True)
os.makedirs(target_path, exist_ok=True)
sys.stderr.write("Generating context...\n")
context = get_context(config_fname, target_path=target_path)
sys.stderr.write("Context generated\n")
templates_path = source_path / context["main"]["templates_path"]
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_path))
for fname in get_source_files(source_path):
if fname.as_posix() in context["main"]["ignore"]:
continue
sys.stderr.write(f"Processing {fname}\n")
dirname = fname.parent
(target_path / dirname).mkdir(parents=True, exist_ok=True)
extension = fname.suffix
if extension in (".html", ".md"):
with (source_path / fname).open(encoding="utf-8") as f:
content = f.read()
if extension == ".md":
toc = TocExtension(
title="Table of Contents",
toc_depth="2-3",
permalink=" #",
)
body = markdown.markdown(
content, extensions=context["main"]["markdown_extensions"] + [toc]
)
# Apply Bootstrap's table formatting manually
# Python-Markdown doesn't let us config table attributes by hand
body = body.replace("<table>", '<table class="table table-bordered">')
content = extend_base_template(body, context["main"]["base_template"])
context["base_url"] = "../" * (len(fname.parents) - 1)
content = jinja_env.from_string(content).render(**context)
fname_html = fname.with_suffix(".html").name
with (target_path / dirname / fname_html).open("w", encoding="utf-8") as f:
f.write(content)
else:
shutil.copy(source_path / fname, target_path / fname)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Documentation builder.")
parser.add_argument(
"source_path", help="path to the source directory (must contain config.yml)"
)
parser.add_argument(
"--target-path", default="build", help="directory where to write the output"
)
args = parser.parse_args()
sys.exit(main(pathlib.Path(args.source_path), pathlib.Path(args.target_path)))
| Preprocessors |
python | pennersr__django-allauth | allauth/socialaccount/providers/frontier/views.py | {
"start": 181,
"end": 993
} | class ____(OAuth2Adapter):
provider_id = "frontier"
AUTH_API = "https://auth.frontierstore.net"
access_token_url = AUTH_API + "/token"
authorize_url = AUTH_API + "/auth"
profile_url = AUTH_API + "/me"
def complete_login(self, request, app, token, **kwargs):
resp = (
get_adapter()
.get_requests_session()
.get(
self.profile_url,
headers={"Authorization": "Bearer " + token.token},
)
)
resp.raise_for_status()
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FrontierOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FrontierOAuth2Adapter)
| FrontierOAuth2Adapter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 16388,
"end": 16437
} | class ____(PGCompiler):
pass
| PGCompiler_asyncpg |
python | ray-project__ray | ci/ray_ci/doc/api.py | {
"start": 566,
"end": 647
} | class ____(Enum):
CLASS = "Class"
FUNCTION = "Function"
@dataclass
| CodeType |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_queried_column_list_to_be_unique.py | {
"start": 272,
"end": 4413
} | class ____(QueryExpectation):
"""Expect multiple columns (such as a compound key) to be unique.
Args:
template_dict: dict with the following keys: \
column_list (columns to check uniqueness on separated by comma)
"""
metric_dependencies = ("query.template_values",)
query = """
SELECT COUNT(1) FROM (
SELECT {column_list}, COUNT(1)
FROM {batch}
GROUP BY {column_list}
HAVING count(1) > 1
)
"""
success_keys = (
"template_dict",
"query",
)
domain_keys = (
"query",
"template_dict",
"batch_id",
"row_condition",
"condition_parser",
)
default_kwarg_values = {
"catch_exceptions": False,
"meta": None,
"query": query,
}
def _validate(
self,
metrics: dict,
runtime_configuration: dict = None,
execution_engine: ExecutionEngine = None,
) -> Union[ExpectationValidationResult, dict]:
metrics = convert_to_json_serializable(data=metrics)
num_of_duplicates = list(metrics.get("query.template_values")[0].values())[0]
if not num_of_duplicates:
return {
"info": "The columns are unique - no duplicates found",
"success": True,
}
else:
return {
"success": False,
"result": {
"info": f"{num_of_duplicates} Duplicated keys found",
"observed_value": num_of_duplicates,
},
}
examples = [
{
"data": [
{
"data": {
"unique_num": [1, 2, 3, 4, 5, 6],
"unique_str": ["a", "b", "c", "d", "e", "f"],
"unique_str2": ["a", "b", "c", "d", "e", "f"],
"duplicate_num": [1, 1, 1, 1, 1, 1],
"duplicate_str": ["a", "a", "b", "c", "d", "e"],
"duplicate_str2": ["a", "a", "b", "c", "d", "e"],
},
},
],
"only_for": ["spark", "sqlite", "bigquery", "trino", "redshift"],
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"template_dict": {
"column_list": "unique_num,unique_str,unique_str2",
}
},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"template_dict": {
"column_list": "duplicate_num,duplicate_str,duplicate_str2",
"row_condition": "1=1",
"condition_parser": "great_expectations",
}
},
"out": {"success": False},
},
{
"title": "passing_condition_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"template_dict": {
"column_list": "unique_num,unique_str,duplicate_str2",
"row_condition": 'col("duplicate_str2")!="a"',
"condition_parser": "great_expectations",
}
},
"out": {"success": True},
},
],
}
]
library_metadata = {
"tags": ["query-based"],
"contributors": ["@itaise", "@maayaniti"],
}
if __name__ == "__main__":
ExpectQueriedColumnListToBeUnique().print_diagnostic_checklist()
| ExpectQueriedColumnListToBeUnique |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 72796,
"end": 74101
} | class ____(Response):
"""
Response of queues.move_task_to_front endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_to_front"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"position": {
"description": "The new position of the task entry in the queue (index, -1 represents bottom of queue)",
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, position: Optional[int] = None, **kwargs: Any) -> None:
super(MoveTaskToFrontResponse, self).__init__(**kwargs)
self.position = position
@schema_property("position")
def position(self) -> Optional[int]:
return self._property_position
@position.setter
def position(self, value: Optional[int]) -> None:
if value is None:
self._property_position = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "position", six.integer_types)
self._property_position = value
| MoveTaskToFrontResponse |
python | pandas-dev__pandas | asv_bench/benchmarks/io/stata.py | {
"start": 142,
"end": 1422
} | class ____(BaseIO):
params = ["tc", "td", "tm", "tw", "th", "tq", "ty"]
param_names = ["convert_dates"]
def setup(self, convert_dates):
self.fname = "__test__.dta"
N = self.N = 100000
C = self.C = 5
self.df = DataFrame(
np.random.randn(N, C),
columns=[f"float{i}" for i in range(C)],
index=date_range("20000101", periods=N, freq="h"),
)
self.df["object"] = Index([f"i-{i}" for i in range(self.N)], dtype=object)
self.df["int8_"] = np.random.randint(
np.iinfo(np.int8).min, np.iinfo(np.int8).max - 27, N
)
self.df["int16_"] = np.random.randint(
np.iinfo(np.int16).min, np.iinfo(np.int16).max - 27, N
)
self.df["int32_"] = np.random.randint(
np.iinfo(np.int32).min, np.iinfo(np.int32).max - 27, N
)
self.df["float32_"] = np.array(np.random.randn(N), dtype=np.float32)
self.convert_dates = {"index": convert_dates}
self.df.to_stata(self.fname, convert_dates=self.convert_dates)
def time_read_stata(self, convert_dates):
read_stata(self.fname)
def time_write_stata(self, convert_dates):
self.df.to_stata(self.fname, convert_dates=self.convert_dates)
| Stata |
python | getsentry__sentry | src/sentry/users/api/serializers/identity.py | {
"start": 432,
"end": 604
} | class ____(TypedDict):
id: str
identityProvider: IdentityProviderSerializerResponse
externalId: str
status: int
@register(Identity)
| IdentitySerializerResponse |
python | conda__conda | conda/models/environment.py | {
"start": 1315,
"end": 6996
} | class ____:
"""
**Experimental** While experimental, expect both major and minor changes across minor releases.
Data model for a conda environment config.
"""
aggressive_update_packages: tuple[str, ...] = field(default_factory=tuple)
channel_priority: ChannelPriority | None = None
channels: tuple[str, ...] = field(default_factory=tuple)
channel_settings: tuple[dict[str, str], ...] = field(default_factory=tuple)
deps_modifier: DepsModifier | None = None
disallowed_packages: tuple[str, ...] = field(default_factory=tuple)
pinned_packages: tuple[str, ...] = field(default_factory=tuple)
repodata_fns: tuple[str, ...] = field(default_factory=tuple)
sat_solver: SatSolverChoice | None = None
solver: str | None = None
track_features: tuple[str, ...] = field(default_factory=tuple)
update_modifier: UpdateModifier | None = None
use_only_tar_bz2: bool | None = None
def _append_without_duplicates(
self, first: Iterable[T], second: Iterable[T]
) -> tuple[T, ...]:
return tuple(dict.fromkeys(item for item in chain(first, second)))
def _merge_channel_settings(
self, first: tuple[dict[str, str], ...], second: tuple[dict[str, str], ...]
) -> tuple[dict[str, str], ...]:
"""Merge channel settings.
An individual channel setting is a dict that may have the key "channels". Settings
with matching "channels" should be merged together.
"""
grouped_channel_settings = groupby(
lambda x: x.get("channel"), chain(first, second)
)
return tuple(
{k: v for config in configs for k, v in config.items()}
for channel, configs in grouped_channel_settings.items()
)
def _merge(self, other: EnvironmentConfig) -> EnvironmentConfig:
"""
**Experimental** While experimental, expect both major and minor changes across minor releases.
Merges an EnvironmentConfig into this one. Merging rules are:
* Primitive types get clobbered if subsequent configs have a value, otherwise keep the last set value
* Lists get appended to and deduplicated
* Dicts get updated
* Special cases:
* channel settings is a list of dicts, it merges inner dicts, keyed on "channel"
"""
# Return early if there is nothing to merge
if other is None:
return self
# Ensure that we are merging another EnvironmentConfig
if not isinstance(other, self.__class__):
raise CondaValueError(
"Cannot merge EnvironmentConfig with non-EnvironmentConfig"
)
self.aggressive_update_packages = self._append_without_duplicates(
self.aggressive_update_packages, other.aggressive_update_packages
)
if other.channel_priority is not None:
self.channel_priority = other.channel_priority
self.channels = self._append_without_duplicates(self.channels, other.channels)
self.channel_settings = self._merge_channel_settings(
self.channel_settings, other.channel_settings
)
if other.deps_modifier is not None:
self.deps_modifier = other.deps_modifier
self.disallowed_packages = self._append_without_duplicates(
self.disallowed_packages, other.disallowed_packages
)
self.pinned_packages = self._append_without_duplicates(
self.pinned_packages, other.pinned_packages
)
self.repodata_fns = self._append_without_duplicates(
self.repodata_fns, other.repodata_fns
)
if other.sat_solver is not None:
self.sat_solver = other.sat_solver
if other.solver is not None:
self.solver = other.solver
self.track_features = self._append_without_duplicates(
self.track_features, other.track_features
)
if other.update_modifier is not None:
self.update_modifier = other.update_modifier
if other.use_only_tar_bz2 is not None:
self.use_only_tar_bz2 = other.use_only_tar_bz2
return self
@classmethod
def from_context(cls) -> EnvironmentConfig:
"""
**Experimental** While experimental, expect both major and minor changes across minor releases.
Create an EnvironmentConfig from the current context
"""
field_names = {field.name for field in fields(cls)}
environment_settings = {
key: value
for key, value in context.environment_settings.items()
if key in field_names
}
return cls(**environment_settings)
@classmethod
def merge(cls, *configs: EnvironmentConfig) -> EnvironmentConfig:
"""
**Experimental** While experimental, expect both major and minor changes across minor releases.
Merges a list of EnvironmentConfigs into a single one. Merging rules are:
* Primitive types get clobbered if subsequent configs have a value, otherwise keep the last set value
* Lists get appended to and deduplicated
* Dicts get updated
"""
# Don't try to merge if there is nothing to merge
if not configs:
return
# If there is only one config, there is nothing to merge, return the lone config
if len(configs) == 1:
return configs[0]
# Use reduce to merge all configs into the first one
return reduce(
lambda result, config: result._merge(config), configs[1:], configs[0]
)
@dataclass(kw_only=True)
| EnvironmentConfig |
python | tensorflow__tensorflow | tensorflow/python/tpu/feature_column_test.py | {
"start": 1551,
"end": 6633
} | class ____(test.TestCase):
def test_defaults(self):
categorical_column = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=3)
embedding_dimension = 2
embedding_column = tpu_fc.embedding_column(
categorical_column, dimension=embedding_dimension)
self.assertIs(categorical_column, embedding_column.categorical_column)
self.assertEqual(embedding_dimension, embedding_column.dimension)
self.assertEqual('mean', embedding_column.combiner)
self.assertEqual('aaa_embedding', embedding_column.name)
self.assertEqual('aaa_embedding', embedding_column._var_scope_name)
self.assertEqual((embedding_dimension,), embedding_column._variable_shape)
self.assertEqual({
'aaa': parsing_ops.VarLenFeature(dtypes.int64)
}, embedding_column._parse_example_spec)
def test_denylisted_column(self):
# HashedCategoricalColumn is denylisted and so will raise an exception.
categorical_column = fc_lib.categorical_column_with_hash_bucket(
key='aaa', hash_bucket_size=3)
embedding_dimension = 2
with self.assertRaises(TypeError):
tpu_fc.embedding_column(categorical_column, dimension=embedding_dimension)
def test_custom_column(self):
# This column is not in any allowlist but should succeed because
# it inherits from V2 CategoricalColumn.
categorical_column = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=10)
embedding_dimension = 2
embedding_column = tpu_fc.embedding_column(
categorical_column, dimension=embedding_dimension)
self.assertIs(categorical_column, embedding_column.categorical_column)
self.assertEqual(embedding_dimension, embedding_column.dimension)
self.assertEqual('mean', embedding_column.combiner)
self.assertEqual('aaa_embedding', embedding_column.name)
self.assertEqual('aaa_embedding', embedding_column._var_scope_name)
self.assertEqual((embedding_dimension,), embedding_column._variable_shape)
self.assertEqual({'aaa': parsing_ops.VarLenFeature(dtypes.int64)},
embedding_column._parse_example_spec)
def test_all_constructor_args(self):
categorical_column = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=3)
embedding_dimension = 2
embedding_column = tpu_fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
combiner='my_combiner',
initializer=lambda: 'my_initializer')
self.assertIs(categorical_column, embedding_column.categorical_column)
self.assertEqual(embedding_dimension, embedding_column.dimension)
self.assertEqual('my_combiner', embedding_column.combiner)
self.assertEqual('aaa_embedding', embedding_column.name)
self.assertEqual('aaa_embedding', embedding_column._var_scope_name)
self.assertEqual((embedding_dimension,), embedding_column._variable_shape)
self.assertEqual({
'aaa': parsing_ops.VarLenFeature(dtypes.int64)
}, embedding_column._parse_example_spec)
@test_util.deprecated_graph_mode_only
def test_get_dense_tensor(self):
# Inputs.
vocabulary_size = 3
sparse_input = sparse_tensor.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
# example 2, ids []
# example 3, ids [1]
indices=((0, 0), (1, 0), (1, 4), (3, 0)),
values=(2, 0, 1, 1),
dense_shape=(4, 5))
# Embedding variable.
embedding_dimension = 2
embedding_values = (
(1., 2.), # id 0
(3., 5.), # id 1
(7., 11.) # id 2
)
def _initializer(shape, dtype, partition_info):
self.assertAllEqual((vocabulary_size, embedding_dimension), shape)
self.assertEqual(dtypes.float32, dtype)
self.assertIsNone(partition_info)
return embedding_values
# Expected lookup result, using combiner='mean'.
expected_lookups = (
# example 0, ids [2], embedding = [7, 11]
(7., 11.),
# example 1, ids [0, 1], embedding = mean([1, 2] + [3, 5]) = [2, 3.5]
(2., 3.5),
# example 2, ids [], embedding = [0, 0]
(0., 0.),
# example 3, ids [1], embedding = [3, 5]
(3., 5.),
)
# Build columns.
categorical_column = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=vocabulary_size)
embedding_column = tpu_fc.embedding_column(
categorical_column,
dimension=embedding_dimension,
initializer=_initializer)
# Provide sparse input and get dense result.
embedding_lookup = embedding_column._get_dense_tensor(
fc._LazyBuilder({
'aaa': sparse_input
}))
# Assert expected embedding variable and lookups.
global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
self.assertItemsEqual(('embedding_weights:0',),
tuple([v.name for v in global_vars]))
with _initialized_session():
self.assertAllEqual(embedding_values, global_vars[0])
self.assertAllEqual(expected_lookups, embedding_lookup)
| EmbeddingColumnTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reexecution.py | {
"start": 614,
"end": 6404
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_full_pipeline_reexecution_fs_storage(self, graphql_context, snapshot):
selector = infer_job_selector(graphql_context, "csv_hello_world")
result_one = execute_dagster_graphql(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": csv_hello_world_ops_config(),
"mode": "default",
}
},
)
assert result_one.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess"
run_id = result_one.data["launchPipelineExecution"]["run"]["runId"]
# overwrite run_id for the snapshot
result_one.data["launchPipelineExecution"]["run"]["runId"] = "<runId dummy value>"
result_one.data["launchPipelineExecution"]["run"]["runConfigYaml"] = (
"<runConfigYaml dummy value>"
)
snapshot.assert_match(result_one.data)
# reexecution
result_two = execute_dagster_graphql(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": csv_hello_world_ops_config(),
"executionMetadata": {
"rootRunId": run_id,
"parentRunId": run_id,
},
"mode": "default",
}
},
)
query_result = result_two.data["launchPipelineReexecution"]
assert query_result["__typename"] == "LaunchRunSuccess"
assert query_result["run"]["rootRunId"] == run_id
assert query_result["run"]["parentRunId"] == run_id
def test_full_pipeline_reexecution_in_memory_storage(self, graphql_context, snapshot):
selector = infer_job_selector(graphql_context, "csv_hello_world")
result_one = execute_dagster_graphql(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": csv_hello_world_ops_config(),
"mode": "default",
}
},
)
assert result_one.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess"
run_id = result_one.data["launchPipelineExecution"]["run"]["runId"]
# overwrite run_id for the snapshot
result_one.data["launchPipelineExecution"]["run"]["runId"] = "<runId dummy value>"
result_one.data["launchPipelineExecution"]["run"]["runConfigYaml"] = (
"<runConfigYaml dummy value>"
)
snapshot.assert_match(result_one.data)
# reexecution
result_two = execute_dagster_graphql(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": csv_hello_world_ops_config(),
"executionMetadata": {
"rootRunId": run_id,
"parentRunId": run_id,
},
"mode": "default",
}
},
)
query_result = result_two.data["launchPipelineReexecution"]
assert query_result["__typename"] == "LaunchRunSuccess"
assert query_result["run"]["rootRunId"] == run_id
assert query_result["run"]["parentRunId"] == run_id
def test_pipeline_reexecution_successful_launch(self, graphql_context):
selector = infer_job_selector(graphql_context, "no_config_job")
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"mode": "default",
}
},
)
assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess"
assert result.data["launchPipelineExecution"]["run"]["status"] == "STARTING"
wait_for_runs_to_finish(graphql_context.instance)
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
result = execute_dagster_graphql(
context=graphql_context, query=RUN_QUERY, variables={"runId": run_id}
)
assert result.data["pipelineRunOrError"]["__typename"] == "Run"
assert result.data["pipelineRunOrError"]["status"] == "SUCCESS"
# reexecution
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"executionMetadata": {
"rootRunId": run_id,
"parentRunId": run_id,
},
"mode": "default",
}
},
)
assert result.data["launchPipelineReexecution"]["__typename"] == "LaunchRunSuccess"
wait_for_runs_to_finish(graphql_context.instance)
new_run_id = result.data["launchPipelineReexecution"]["run"]["runId"]
result = execute_dagster_graphql(
context=graphql_context, query=RUN_QUERY, variables={"runId": new_run_id}
)
assert result.data["pipelineRunOrError"]["__typename"] == "Run"
assert result.data["pipelineRunOrError"]["status"] == "SUCCESS"
| TestReexecution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.