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 | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 25210,
"end": 25381
} | class ____(Num):
"""
An integer.
Attributes
----------
value : int
Value of the node, represented as an integer.
"""
__slots__ = ()
| Int |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 10738,
"end": 11028
} | class ____(greentest.TestCase):
N = 1
def test(self):
e = Event()
waiters = [gevent.spawn(e.wait) for i in range(self.N)]
gevent.sleep(0.001)
e.set()
e.clear()
for greenlet in waiters:
greenlet.join()
| TestEvent_SetThenClear |
python | pyqtgraph__pyqtgraph | pyqtgraph/multiprocess/remoteproxy.py | {
"start": 28094,
"end": 30228
} | class ____(object):
"""
Request objects are returned when calling an ObjectProxy in asynchronous mode
or if a synchronous call has timed out. Use hasResult() to ask whether
the result of the call has been returned yet. Use result() to get
the returned value.
"""
def __init__(self, process, reqId, description=None, timeout=10):
self.proc = process
self.description = description
self.reqId = reqId
self.gotResult = False
self._result = None
self.timeout = timeout
def result(self, block=True, timeout=None):
"""
Return the result for this request.
If block is True, wait until the result has arrived or *timeout* seconds passes.
If the timeout is reached, raise NoResultError. (use timeout=None to disable)
If block is False, raise NoResultError immediately if the result has not arrived yet.
If the process's connection has closed before the result arrives, raise ClosedError.
"""
if self.gotResult:
return self._result
if timeout is None:
timeout = self.timeout
if block:
start = time.time()
while not self.hasResult():
if self.proc.exited:
raise ClosedError()
time.sleep(0.005)
if timeout >= 0 and time.time() - start > timeout:
print("Request timed out: %s" % self.description)
import traceback
traceback.print_stack()
raise NoResultError()
return self._result
else:
self._result = self.proc.getResult(self.reqId) ## raises NoResultError if result is not available yet
self.gotResult = True
return self._result
def hasResult(self):
"""Returns True if the result for this request has arrived."""
try:
self.result(block=False)
except NoResultError:
pass
return self.gotResult
| Request |
python | matplotlib__matplotlib | lib/matplotlib/units.py | {
"start": 2366,
"end": 3480
} | class ____:
"""
Information to support default axis labeling, tick labeling, and limits.
An instance of this class must be returned by
`ConversionInterface.axisinfo`.
"""
def __init__(self, majloc=None, minloc=None,
majfmt=None, minfmt=None, label=None,
default_limits=None):
"""
Parameters
----------
majloc, minloc : Locator, optional
Tick locators for the major and minor ticks.
majfmt, minfmt : Formatter, optional
Tick formatters for the major and minor ticks.
label : str, optional
The default axis label.
default_limits : optional
The default min and max limits of the axis if no data has
been plotted.
Notes
-----
If any of the above are ``None``, the axis will simply use the
default value.
"""
self.majloc = majloc
self.minloc = minloc
self.majfmt = majfmt
self.minfmt = minfmt
self.label = label
self.default_limits = default_limits
| AxisInfo |
python | huggingface__transformers | src/transformers/models/glm46v/image_processing_glm46v.py | {
"start": 1856,
"end": 3693
} | class ____(ImagesKwargs, total=False):
"""
patch_size (`int`, *optional*, defaults to 14):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 2):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to 2):
The merge size of the vision encoder to llm encoder.
"""
patch_size: int
temporal_patch_size: int
merge_size: int
def smart_resize(
num_frames: int,
height: int,
width: int,
temporal_factor: int = 2,
factor: int = 28,
min_pixels: int = 112 * 112,
max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144,
):
if num_frames < temporal_factor:
raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")
if height < factor or width < factor:
raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
elif max(height, width) / min(height, width) > 200:
raise ValueError(
f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
)
h_bar = round(height / factor) * factor
w_bar = round(width / factor) * factor
t_bar = round(num_frames / temporal_factor) * temporal_factor
if t_bar * h_bar * w_bar > max_pixels:
beta = math.sqrt((num_frames * height * width) / max_pixels)
h_bar = max(factor, math.floor(height / beta / factor) * factor)
w_bar = max(factor, math.floor(width / beta / factor) * factor)
elif t_bar * h_bar * w_bar < min_pixels:
beta = math.sqrt(min_pixels / (num_frames * height * width))
h_bar = math.ceil(height * beta / factor) * factor
w_bar = math.ceil(width * beta / factor) * factor
return h_bar, w_bar
| Glm46VImageProcessorKwargs |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 1032,
"end": 1866
} | class ____(models.CharField):
def pre_save(self, model_instance, add):
secret = getattr(model_instance, self.attname)
should_be_hashed = getattr(model_instance, "hash_client_secret", True)
if not should_be_hashed:
return super().pre_save(model_instance, add)
try:
hasher = identify_hasher(secret)
logger.debug(f"{model_instance}: {self.attname} is already hashed with {hasher}.")
except ValueError:
logger.debug(f"{model_instance}: {self.attname} is not hashed; hashing it now.")
hashed_secret = make_password(secret, hasher=oauth2_settings.CLIENT_SECRET_HASHER)
setattr(model_instance, self.attname, hashed_secret)
return hashed_secret
return super().pre_save(model_instance, add)
| ClientSecretField |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 13713,
"end": 14413
} | class ____(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create(
name="obj_1 v1"
)
obj_2 = TestModel.objects.create(
name="obj_2 v1"
)
with reversion.create_revision():
obj_1.name = "obj_1 v2"
obj_1.save()
obj_2.name = "obj_2 v2"
obj_2.save()
Version.objects.get_for_object(obj_1)[1].revision.revert()
obj_1.refresh_from_db()
self.assertEqual(obj_1.name, "obj_1 v1")
obj_2.refresh_from_db()
self.assertEqual(obj_2.name, "obj_2 v1")
| RevisionRevertTest |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/_base.py | {
"start": 163,
"end": 1911
} | class ____:
"""Base Solr client for shared functionality."""
def __init__(
self,
base_url: str,
request_timeout_sec: int = SolrConstants.DEFAULT_TIMEOUT_SEC,
headers: Optional[dict[str, str]] = None,
**client_kwargs: Any,
) -> None:
"""
Initialize the client.
Args:
base_url:
The base URL of the target Solr collection or core.
request_timeout_sec: The timeout for requests to Solr.
headers: Additional headers to include in all requests.
**client_kwargs:
Additional keyword arguments to pass to the internal client
constructor.
"""
if not base_url.strip():
raise ValueError(
f"Parameter 'base_url' cannot be empty, input='{base_url}'"
)
if request_timeout_sec < 0:
raise ValueError(
f"Parameter 'request_timeout_sec' cannot be negative, "
f"input='{request_timeout_sec}'"
)
self._base_url = base_url.rstrip("/")
self._request_timeout_sec = request_timeout_sec
self._headers = headers or {}
self._client_kwargs = client_kwargs
# client will be created in implementations
self._client: Any = None
def __str__(self) -> str:
"""String representation of the client."""
return f"{self.__class__.__name__}(base_url='{self.base_url}')"
def __repr__(self) -> str:
"""String representation of the client."""
return str(self)
@property
def base_url(self) -> str:
"""The base URL of the target Solr collection."""
return self._base_url
| _BaseSolrClient |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/client.py | {
"start": 902,
"end": 983
} | class ____(Enum):
Ready = "READY"
Terminated = "TERMINATED"
| WaitForPodState |
python | scikit-learn__scikit-learn | sklearn/linear_model/_stochastic_gradient.py | {
"start": 61783,
"end": 75040
} | class ____(BaseSGDRegressor):
"""Linear model fitted by minimizing a regularized empirical loss with SGD.
SGD stands for Stochastic Gradient Descent: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a decreasing strength schedule (aka learning rate).
The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.
This implementation works with data represented as dense numpy arrays of
floating point values for the features.
Read more in the :ref:`User Guide <sgd>`.
Parameters
----------
loss : str, default='squared_error'
The loss function to be used. The possible values are 'squared_error',
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'
The 'squared_error' refers to the ordinary least squares fit.
'huber' modifies 'squared_error' to focus less on getting outliers
correct by switching from squared to linear loss past a distance of
epsilon. 'epsilon_insensitive' ignores errors less than epsilon and is
linear past that; this is the loss function used in SVR.
'squared_epsilon_insensitive' is the same but becomes squared loss past
a tolerance of epsilon.
More details about the losses formulas can be found in the
:ref:`User Guide <sgd_mathematical_formulation>`.
penalty : {'l2', 'l1', 'elasticnet', None}, default='l2'
The penalty (aka regularization term) to be used. Defaults to 'l2'
which is the standard regularizer for linear SVM models. 'l1' and
'elasticnet' might bring sparsity to the model (feature selection)
not achievable with 'l2'. No penalty is added when set to `None`.
You can see a visualisation of the penalties in
:ref:`sphx_glr_auto_examples_linear_model_plot_sgd_penalties.py`.
alpha : float, default=0.0001
Constant that multiplies the regularization term. The higher the
value, the stronger the regularization. Also used to compute the
learning rate when `learning_rate` is set to 'optimal'.
Values must be in the range `[0.0, inf)`.
l1_ratio : float, default=0.15
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
Only used if `penalty` is 'elasticnet'.
Values must be in the range `[0.0, 1.0]` or can be `None` if
`penalty` is not `elasticnet`.
.. versionchanged:: 1.7
`l1_ratio` can be `None` when `penalty` is not "elasticnet".
fit_intercept : bool, default=True
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered.
max_iter : int, default=1000
The maximum number of passes over the training data (aka epochs).
It only impacts the behavior in the ``fit`` method, and not the
:meth:`partial_fit` method.
Values must be in the range `[1, inf)`.
.. versionadded:: 0.19
tol : float or None, default=1e-3
The stopping criterion. If it is not None, training will stop
when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive
epochs.
Convergence is checked against the training loss or the
validation loss depending on the `early_stopping` parameter.
Values must be in the range `[0.0, inf)`.
.. versionadded:: 0.19
shuffle : bool, default=True
Whether or not the training data should be shuffled after each epoch.
verbose : int, default=0
The verbosity level.
Values must be in the range `[0, inf)`.
epsilon : float, default=0.1
Epsilon in the epsilon-insensitive loss functions; only if `loss` is
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
For 'huber', determines the threshold at which it becomes less
important to get the prediction exactly right.
For epsilon-insensitive, any differences between the current prediction
and the correct label are ignored if they are less than this threshold.
Values must be in the range `[0.0, inf)`.
random_state : int, RandomState instance, default=None
Used for shuffling the data, when ``shuffle`` is set to ``True``.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
learning_rate : str, default='invscaling'
The learning rate schedule:
- 'constant': `eta = eta0`
- 'optimal': `eta = 1.0 / (alpha * (t + t0))`
where t0 is chosen by a heuristic proposed by Leon Bottou.
- 'invscaling': `eta = eta0 / pow(t, power_t)`
- 'adaptive': eta = eta0, as long as the training keeps decreasing.
Each time n_iter_no_change consecutive epochs fail to decrease the
training loss by tol or fail to increase validation score by tol if
early_stopping is True, the current learning rate is divided by 5.
- 'pa1': passive-aggressive algorithm 1, see [1]_. Only with
`loss='epsilon_insensitive'`.
Update is `w += eta y x` with `eta = min(eta0, loss/||x||**2)`.
- 'pa2': passive-aggressive algorithm 2, see [1]_. Only with
`loss='epsilon_insensitive'`.
Update is `w += eta y x` with `eta = hinge_loss / (||x||**2 + 1/(2 eta0))`.
.. versionadded:: 0.20
Added 'adaptive' option.
.. versionadded:: 1.8
Added options 'pa1' and 'pa2'
eta0 : float, default=0.01
The initial learning rate for the 'constant', 'invscaling' or
'adaptive' schedules. The default value is 0.01.
Values must be in the range `(0.0, inf)`.
For PA-1 (`learning_rate=pa1`) and PA-II (`pa2`), it specifies the
aggressiveness parameter for the passive-agressive algorithm, see [1] where it
is called C:
- For PA-I it is the maximum step size.
- For PA-II it regularizes the step size (the smaller `eta0` the more it
regularizes).
As a general rule-of-thumb for PA, `eta0` should be small when the data is
noisy.
power_t : float, default=0.25
The exponent for inverse scaling learning rate.
Values must be in the range `[0.0, inf)`.
.. deprecated:: 1.8
Negative values for `power_t` are deprecated in version 1.8 and will raise
an error in 1.10. Use values in the range [0.0, inf) instead.
early_stopping : bool, default=False
Whether to use early stopping to terminate training when validation
score is not improving. If set to True, it will automatically set aside
a fraction of training data as validation and terminate
training when validation score returned by the `score` method is not
improving by at least `tol` for `n_iter_no_change` consecutive
epochs.
See :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_early_stopping.py` for an
example of the effects of early stopping.
.. versionadded:: 0.20
Added 'early_stopping' option
validation_fraction : float, default=0.1
The proportion of training data to set aside as validation set for
early stopping. Must be between 0 and 1.
Only used if `early_stopping` is True.
Values must be in the range `(0.0, 1.0)`.
.. versionadded:: 0.20
Added 'validation_fraction' option
n_iter_no_change : int, default=5
Number of iterations with no improvement to wait before stopping
fitting.
Convergence is checked against the training loss or the
validation loss depending on the `early_stopping` parameter.
Integer values must be in the range `[1, max_iter)`.
.. versionadded:: 0.20
Added 'n_iter_no_change' option
warm_start : bool, default=False
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
See :term:`the Glossary <warm_start>`.
Repeatedly calling fit or partial_fit when warm_start is True can
result in a different solution than when calling fit a single time
because of the way the data is shuffled.
If a dynamic learning rate is used, the learning rate is adapted
depending on the number of samples already seen. Calling ``fit`` resets
this counter, while ``partial_fit`` will result in increasing the
existing counter.
average : bool or int, default=False
When set to True, computes the averaged SGD weights across all
updates and stores the result in the ``coef_`` attribute. If set to
an int greater than 1, averaging will begin once the total number of
samples seen reaches `average`. So ``average=10`` will begin
averaging after seeing 10 samples.
Attributes
----------
coef_ : ndarray of shape (n_features,)
Weights assigned to the features.
intercept_ : ndarray of shape (1,)
The intercept term.
n_iter_ : int
The actual number of iterations before reaching the stopping criterion.
t_ : int
Number of weight updates performed during training.
Same as ``(n_iter_ * n_samples + 1)``.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
HuberRegressor : Linear regression model that is robust to outliers.
Lars : Least Angle Regression model.
Lasso : Linear Model trained with L1 prior as regularizer.
RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm.
Ridge : Linear least squares with l2 regularization.
sklearn.svm.SVR : Epsilon-Support Vector Regression.
TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model.
References
----------
.. [1] Online Passive-Aggressive Algorithms
<http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf>
K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006)
Examples
--------
>>> import numpy as np
>>> from sklearn.linear_model import SGDRegressor
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import StandardScaler
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> # Always scale the input. The most convenient way is to use a pipeline.
>>> reg = make_pipeline(StandardScaler(),
... SGDRegressor(max_iter=1000, tol=1e-3))
>>> reg.fit(X, y)
Pipeline(steps=[('standardscaler', StandardScaler()),
('sgdregressor', SGDRegressor())])
"""
_parameter_constraints: dict = {
**BaseSGDRegressor._parameter_constraints,
"penalty": [StrOptions({"l2", "l1", "elasticnet"}), None],
"alpha": [Interval(Real, 0, None, closed="left")],
"l1_ratio": [Interval(Real, 0, 1, closed="both"), None],
"power_t": [Interval(Real, None, None, closed="neither")],
"learning_rate": [
StrOptions({"constant", "optimal", "invscaling", "adaptive", "pa1", "pa2"}),
],
"epsilon": [Interval(Real, 0, None, closed="left")],
}
def __init__(
self,
loss="squared_error",
*,
penalty="l2",
alpha=0.0001,
l1_ratio=0.15,
fit_intercept=True,
max_iter=1000,
tol=1e-3,
shuffle=True,
verbose=0,
epsilon=DEFAULT_EPSILON,
random_state=None,
learning_rate="invscaling",
eta0=0.01,
power_t=0.25,
early_stopping=False,
validation_fraction=0.1,
n_iter_no_change=5,
warm_start=False,
average=False,
):
super().__init__(
loss=loss,
penalty=penalty,
alpha=alpha,
l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
max_iter=max_iter,
tol=tol,
shuffle=shuffle,
verbose=verbose,
epsilon=epsilon,
random_state=random_state,
learning_rate=learning_rate,
eta0=eta0,
power_t=power_t,
early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
warm_start=warm_start,
average=average,
)
| SGDRegressor |
python | huggingface__transformers | src/transformers/models/aya_vision/modeling_aya_vision.py | {
"start": 14914,
"end": 21802
} | class ____(AyaVisionPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {
r"^language_model.model": "model.language_model",
r"^vision_tower": "model.vision_tower",
r"^multi_modal_projector": "model.multi_modal_projector",
r"^language_model.lm_head": "lm_head",
}
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
def __init__(self, config: AyaVisionConfig):
super().__init__(config)
self.model = AyaVisionModel(config)
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def get_output_embeddings(self) -> nn.Module:
return self.lm_head
def get_image_features(
self,
pixel_values: torch.FloatTensor,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
**kwargs,
):
return self.model.get_image_features(
pixel_values=pixel_values,
vision_feature_layer=vision_feature_layer,
vision_feature_select_strategy=vision_feature_select_strategy,
**kwargs,
)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
labels: Optional[torch.LongTensor] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
image_sizes: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, AyaVisionCausalLMOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from transformers import AutoProcessor, AyaVisionForConditionalGeneration
>>> import torch
>>> torch_device = "cuda:0"
>>> processor = AutoProcessor.from_pretrained("CohereForAI/aya-vision-8b", use_fast=True)
>>> model = AyaVisionForConditionalGeneration.from_pretrained("CohereForAI/aya-vision-8b", device_map=torch_device)
>>> messages = [
... {
... "role": "user",
... "content": [
... {
... "type": "image",
... "url": "https://pbs.twimg.com/media/Fx7YvfQWYAIp6rZ?format=jpg&name=medium",
... },
... {"type": "text", "text": "चित्र में लिखा पाठ क्या कहता है?"},
... ],
... }
... ]
>>> inputs = processor.apply_chat_template(
... messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", device=torch_device
... ).to(model.device)
>>> gen_tokens = model.generate(**inputs, max_new_tokens=300, do_sample=True, temperature=0.3)
>>> processor.tokenizer.decode(gen_tokens[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
```"""
vision_feature_layer = (
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
)
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_feature_select_strategy
)
outputs = self.model(
input_ids=input_ids,
pixel_values=pixel_values,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
vision_feature_layer=vision_feature_layer,
vision_feature_select_strategy=vision_feature_select_strategy,
cache_position=cache_position,
image_sizes=image_sizes,
**kwargs,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
)
return AyaVisionCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
image_hidden_states=outputs.image_hidden_states,
)
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
inputs_embeds=None,
pixel_values=None,
attention_mask=None,
cache_position=None,
logits_to_keep=None,
**kwargs,
):
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
model_inputs = super().prepare_inputs_for_generation(
input_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
logits_to_keep=logits_to_keep,
**kwargs,
)
if cache_position[0] == 0:
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
# Otherwise we need pixel values to be passed to model
model_inputs["pixel_values"] = pixel_values
return model_inputs
__all__ = ["AyaVisionForConditionalGeneration", "AyaVisionPreTrainedModel", "AyaVisionModel"]
| AyaVisionForConditionalGeneration |
python | apache__airflow | airflow-core/src/airflow/utils/log/log_reader.py | {
"start": 1781,
"end": 8320
} | class ____:
"""Task log reader."""
STREAM_LOOP_SLEEP_SECONDS = 1
"""Time to sleep between loops while waiting for more logs"""
STREAM_LOOP_STOP_AFTER_EMPTY_ITERATIONS = 10
"""Number of empty loop iterations before stopping the stream"""
@staticmethod
def get_no_log_state_message(ti: TaskInstance | TaskInstanceHistory) -> Iterator[StructuredLogMessage]:
"""Yield standardized no-log messages for a given TI state."""
if ti.state == TaskInstanceState.SKIPPED:
msg = "Task was skipped — no logs available."
elif ti.state == TaskInstanceState.UPSTREAM_FAILED:
msg = "Task did not run because upstream task(s) failed."
else:
msg = "No logs available for this task."
yield StructuredLogMessage(
timestamp=None,
event="::group::Log message source details",
)
yield StructuredLogMessage(timestamp=None, event="::endgroup::")
yield StructuredLogMessage(
timestamp=ti.updated_at or datetime.now(timezone.utc),
event=msg,
)
def read_log_chunks(
self,
ti: TaskInstance | TaskInstanceHistory,
try_number: int | None,
metadata: LogMetadata,
) -> tuple[LogHandlerOutputStream, LogMetadata]:
"""
Read chunks of Task Instance logs.
:param ti: The taskInstance
:param try_number:
:param metadata: A dictionary containing information about how to read the task log
The following is an example of how to use this method to read log:
.. code-block:: python
logs, metadata = task_log_reader.read_log_chunks(ti, try_number, metadata)
logs = logs[0] if try_number is not None else logs
where task_log_reader is an instance of TaskLogReader. The metadata will always
contain information about the task log which can enable you read logs to the
end.
"""
if try_number == 0:
msg = self.get_no_log_state_message(ti) # returns StructuredLogMessage
# one message + tell the caller it's the end so stream stops
return msg, {"end_of_log": True}
return self.log_handler.read(ti, try_number, metadata=metadata)
def read_log_stream(
self,
ti: TaskInstance | TaskInstanceHistory,
try_number: int | None,
metadata: LogMetadata,
) -> Iterator[str]:
"""
Continuously read log to the end.
:param ti: The Task Instance
:param try_number: the task try number
:param metadata: A dictionary containing information about how to read the task log
"""
if try_number is None:
try_number = ti.try_number
# Handle skipped / upstream_failed case directly
if try_number == 0:
for msg in self.get_no_log_state_message(ti):
yield f"{msg.model_dump_json()}\n"
return
for key in ("end_of_log", "max_offset", "offset", "log_pos"):
# https://mypy.readthedocs.io/en/stable/typed_dict.html#supported-operations
metadata.pop(key, None) # type: ignore[misc]
empty_iterations = 0
while True:
log_stream, out_metadata = self.read_log_chunks(ti, try_number, metadata)
yield from (f"{log.model_dump_json()}\n" for log in log_stream)
if not out_metadata.get("end_of_log", False) and ti.state not in (
TaskInstanceState.RUNNING,
TaskInstanceState.DEFERRED,
):
if log_stream:
empty_iterations = 0
else:
# we did not receive any logs in this loop
# sleeping to conserve resources / limit requests on external services
time.sleep(self.STREAM_LOOP_SLEEP_SECONDS)
empty_iterations += 1
if empty_iterations >= self.STREAM_LOOP_STOP_AFTER_EMPTY_ITERATIONS:
# we have not received any logs for a while, so we stop the stream
# this is emitted as json to avoid breaking the ndjson stream format
yield '{"event": "Log stream stopped - End of log marker not found; logs may be incomplete."}\n'
return
else:
# https://mypy.readthedocs.io/en/stable/typed_dict.html#supported-operations
metadata.clear() # type: ignore[attr-defined]
metadata.update(out_metadata)
return
@cached_property
def log_handler(self):
"""Get the log handler which is configured to read logs."""
task_log_reader = conf.get("logging", "task_log_reader")
def handlers():
"""
Yield all handlers first from airflow.task logger then root logger.
Depending on whether we're in a running task, it could be in either of these locations.
"""
yield from logging.getLogger("airflow.task").handlers
yield from logging.getLogger().handlers
fallback = FileTaskHandler(os.devnull)
fallback.name = task_log_reader
yield fallback
return next((h for h in handlers() if h.name == task_log_reader), None)
@property
def supports_read(self):
"""Checks if a read operation is supported by a current log handler."""
return hasattr(self.log_handler, "read")
@property
def supports_external_link(self) -> bool:
"""Check if the logging handler supports external links (e.g. to Elasticsearch, Stackdriver, etc)."""
if not isinstance(self.log_handler, ExternalLoggingMixin):
return False
return self.log_handler.supports_external_link
@provide_session
def render_log_filename(
self,
ti: TaskInstance | TaskInstanceHistory,
try_number: int | None = None,
*,
session: Session = NEW_SESSION,
) -> str:
"""
Render the log attachment filename.
:param ti: The task instance
:param try_number: The task try number
"""
dagrun = ti.get_dagrun(session=session)
attachment_filename = render_log_filename(
ti=ti,
try_number="all" if try_number is None else try_number,
filename_template=dagrun.get_log_template(session=session).filename,
)
return attachment_filename
| TaskLogReader |
python | donnemartin__interactive-coding-challenges | sorting_searching/selection_sort/test_selection_sort.py | {
"start": 18,
"end": 932
} | class ____(unittest.TestCase):
def test_selection_sort(self, func):
print('None input')
self.assertRaises(TypeError, func, None)
print('Empty input')
self.assertEqual(func([]), [])
print('One element')
self.assertEqual(func([5]), [5])
print('Two or more elements')
data = [5, 1, 7, 2, 6, -3, 5, 7, -10]
self.assertEqual(func(data), sorted(data))
print('Success: test_selection_sort\n')
def main():
test = TestSelectionSort()
selection_sort = SelectionSort()
test.test_selection_sort(selection_sort.sort)
try:
test.test_selection_sort(selection_sort.sort_recursive)
test.test_selection_sort(selection_sort.sor_iterative_alt)
except NameError:
# Alternate solutions are only defined
# in the solutions file
pass
if __name__ == '__main__':
main()
| TestSelectionSort |
python | pandas-dev__pandas | pandas/util/version/__init__.py | {
"start": 611,
"end": 1227
} | class ____:
def __repr__(self) -> str:
return "Infinity"
def __hash__(self) -> int:
return hash(repr(self))
def __lt__(self, other: object) -> bool:
return False
def __le__(self, other: object) -> bool:
return False
def __eq__(self, other: object) -> bool:
return isinstance(other, type(self))
def __gt__(self, other: object) -> bool:
return True
def __ge__(self, other: object) -> bool:
return True
def __neg__(self: object) -> NegativeInfinityType:
return NegativeInfinity
Infinity = InfinityType()
| InfinityType |
python | google__jax | tests/shard_map_test.py | {
"start": 2413,
"end": 158053
} | class ____(jtu.JaxTestCase):
def test_identity(self):
mesh, a, _ = create_inputs(P('z', ('x', 'y')), P(None, None))
assert a.addressable_data(0).shape == (4, 2)
def identity(x):
return x
@jax.jit
def fwd(a):
c = shard_map(
identity,
mesh=mesh,
in_specs=(P('z', ('x', 'y')),),
out_specs=P('z', ('x', 'y')))(a)
return c
c = fwd(a)
self.assertEqual(c.addressable_data(0).shape, (4, 2))
def test_all_gather(self):
mesh, a, _ = create_inputs(P('z', ('x', 'y')), P(None, None))
assert a.addressable_data(0).shape == (4, 2)
@jax.jit
@partial(shard_map, mesh=mesh,
in_specs=(P('z', ('x', 'y')),), out_specs=P('z', ('x', 'y')))
def fwd(a):
return (lax.all_gather(a, 'z', axis=0, tiled=True),
lax.all_gather(a, ('x', 'y'), axis=-1, tiled=True))
c, d = fwd(a)
self.assertEqual(c.addressable_data(0).shape, (8, 2))
for i, a_shard in enumerate(np.split(a, 4, axis=1)):
self.assertAllClose(c.addressable_data(2 * i), a_shard)
self.assertEqual(d.addressable_data(0).shape, (4, 8))
for i, a_shard in enumerate(np.split(a, 2, axis=0)):
self.assertAllClose(d.addressable_data(i), a_shard)
def test_all_gather_invariant_basic(self):
mesh = jtu.create_mesh((4,), 'x')
arr = jnp.arange(8.)
@jax.jit
@shard_map(mesh=mesh, in_specs=P('x'), out_specs=P())
def f(a):
out = all_gather_invariant(a, 'x', tiled=True)
self.assertEqual(out.aval.vma, set())
return out
out = f(arr)
self.assertArraysEqual(out, arr)
jtu.check_grads(f, (arr,), order=2)
def g(x):
return f(x).sum()
out = jax.jit(jax.grad(g))(arr)
self.assertEqual(out.shape, (8,))
self.assertEqual(out.sharding, NamedSharding(mesh, P('x')))
def test_all_gather_invariant_complex(self):
mesh, a, _ = create_inputs(P('z', ('x', 'y')), P(None, None),
dtype=np.float32)
assert a.addressable_data(0).shape == (4, 2)
@jax.jit
@shard_map(mesh=mesh, in_specs=(P('z', ('x', 'y')),),
out_specs=(P(None, ('x', 'y')), P('z')))
def f(a):
c = all_gather_invariant(a, 'z', axis=0, tiled=True)
self.assertEqual(jax.typeof(c).vma, {'x', 'y'})
d = all_gather_invariant(a, ('x', 'y'), axis=-1, tiled=True)
self.assertEqual(jax.typeof(d).vma, {'z'})
return c, d
c, d = f(a)
self.assertEqual(c.addressable_data(0).shape, (8, 2))
for i, a_shard in enumerate(np.split(a, 4, axis=1)):
self.assertAllClose(c.addressable_data(2 * i), a_shard)
self.assertEqual(d.addressable_data(0).shape, (4, 8))
for i, a_shard in enumerate(np.split(a, 2, axis=0)):
self.assertAllClose(d.addressable_data(i), a_shard)
def g(x):
return f(x)[0].sum()
out1 = jax.jit(jax.grad(g))(a)
self.assertEqual(out1.shape, (8, 8))
self.assertEqual(out1.sharding, NamedSharding(mesh, P('z', ('x', 'y'))))
out2 = jax.grad(g)(a)
self.assertEqual(out2.shape, (8, 8))
self.assertEqual(out2.sharding, NamedSharding(mesh, P('z', ('x', 'y'))))
def test_all_gather_with_axis_index_groups(self):
mesh, a, _ = create_inputs(P('x', ('y', 'z')), P(None, None))
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(P('x', ('y', 'z')),),
out_specs=P('x', ('y', 'z')),
)
def fwd(a):
return lax.all_gather(
a, ('y', 'z'), axis_index_groups=((0, 1), (2, 3)), axis=-1, tiled=True
)
c = fwd(a)
self.assertEqual(c.addressable_data(0).shape, (4, 4))
for i, row_block in enumerate(np.split(a, 2, axis=0)):
for j, block in enumerate(np.split(row_block, 2, axis=-1)):
self.assertAllClose(c.addressable_data(4 * i + 2 * j), block)
self.assertAllClose(c.addressable_data(4 * i + 2 * j + 1), block)
def test_with_static_arg(self):
mesh, a, _ = create_inputs(P('x', 'y'), P(None, None))
assert a.addressable_data(0).shape == (4, 4)
def add_one(x, static_shape):
return x + jnp.ones(static_shape, dtype=x.dtype)
@jax.jit(static_argnums=(1,))
def fun(a, static_shape):
return shard_map(
add_one,
mesh=mesh,
in_specs=(P('x', 'y'), None),
out_specs=P('x', 'y'))(a, static_shape)
self.assertAllClose(a + 1, fun(a, a.addressable_data(0).shape))
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_matmul_unreduced(self, mesh):
np_inp1 = np.arange(8.).reshape(2, 4)
np_inp2 = np.arange(8.).reshape(4, 2)
arr1 = jax.device_put(np_inp1, P('x', 'y'))
arr2 = jax.device_put(np_inp2, P('y', None))
@jax.jit
@shard_map(in_specs=(P('x', 'y'), P('y', None)),
out_specs=P('x', None, unreduced={'y'}))
def f(a, b):
c = jnp.einsum('ab,bc->ac', a, b)
self.assertEqual(c.aval.vma, {'x', 'y'})
return c
out = f(arr1, arr2)
self.assertEqual(out.shape, (2, 2))
self.assertEqual(out.sharding,
NamedSharding(mesh, P('x', None, unreduced={'y'})))
expected_shards = [np.array([[2., 3.]]), np.array([[26., 31.]]),
np.array([[10., 19.]]), np.array([[66., 79.]])]
for s, es in zip(out.addressable_shards, expected_shards):
self.assertEqual(s.data.shape, (1, 2))
self.assertArraysEqual(s.data, es)
resharded_out = jax.sharding.reshard(out, P('x', None))
self.assertArraysEqual(resharded_out, np_inp1 @ np_inp2)
def g(x, y):
out = f(x, y)
return jax.sharding.reshard(out, P('x', None)).sum()
out1, out2 = jax.jit(jax.grad(g, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('x', 'y')))
self.assertEqual(out2.sharding, NamedSharding(mesh, P('y', None)))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: (x @ y).sum(),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_matmul_unreduced_error(self, mesh):
np_inp1 = np.arange(8.).reshape(2, 4)
np_inp2 = np.arange(8.).reshape(4, 2)
arr1 = jax.device_put(np_inp1, P('x', 'y'))
arr2 = jax.device_put(np_inp2, P('y', None))
@jax.jit
@shard_map(in_specs=(P('x', None), P(None, None)),
out_specs=P('x', None, unreduced={'y'}))
def f(a, b):
c = jnp.einsum('ab,bc->ac', a, b)
self.assertEqual(c.aval.vma, {'x'})
return c
with self.assertRaisesRegex(
ValueError,
"vary_unreduced_cast is a Varying->Unreduced collective"):
f(arr1, arr2)
def test_matmul_reduce_scatter(self):
mesh, a, b = create_inputs(P('z', 'y'), P('y', None))
assert a.addressable_data(0).shape == (4, 4)
@jax.jit
@partial(shard_map, mesh=mesh,
in_specs=(P('z', 'y'), P('y', None)),
out_specs=P(('z', 'y'), None))
def fwd(a, b):
c = jnp.matmul(a, b) # [B.z, F] {y.unreduced}
return (
lax.psum_scatter(c, 'y', scatter_dimension=0, tiled=True),
lax.psum_scatter(c, ('z', 'y'), scatter_dimension=0, tiled=True),
)
expected = jnp.matmul(a, b)
c, d = fwd(a, b)
self.assertEqual(c.addressable_data(0).shape, (2, 8))
self.assertAllClose(expected, c)
self.assertEqual(d.addressable_data(0).shape, (1, 8))
self.assertAllClose(expected[:4] + expected[4:], d)
def test_reduce_scatter_with_axis_index_groups(self):
axis_index_groups = ((0, 2, 4, 6), (1, 3, 5, 7))
mesh, a, _ = create_inputs(P(None, ('x', 'y', 'z')), P(None, None))
assert a.addressable_data(0).shape == (8, 1)
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(P(None, ('x', 'y', 'z')),),
out_specs=P(None, ('x', 'y', 'z')),
)
def fwd(a):
return lax.psum_scatter(
a,
('x', 'y', 'z'),
scatter_dimension=0,
axis_index_groups=axis_index_groups,
tiled=True,
)
c = fwd(a)
self.assertEqual(c.addressable_data(0).shape, (2, 1))
sum_of_even_columns = np.sum(a[..., axis_index_groups[0]], -1)
for i, sums in enumerate(np.split(sum_of_even_columns, 4, 0)):
self.assertAllClose(np.squeeze(c.addressable_data(2 * i), -1), sums)
sum_of_odd_columns = np.sum(a[..., axis_index_groups[1]], -1)
for i, sums in enumerate(np.split(sum_of_odd_columns, 4, 0)):
self.assertAllClose(np.squeeze(c.addressable_data(2 * i + 1), -1), sums)
def test_collective_permute(self):
mesh = jtu.create_mesh((8,), 'x')
a = jax.device_put(
jnp.arange(8 * 8).reshape((8, 8)),
jax.sharding.NamedSharding(mesh, P('x', None)))
@jax.jit
@partial(
shard_map, mesh=mesh, in_specs=(P('x', None),), out_specs=P('x', None)
)
def fwd(a):
axis_size = lax.axis_size('x')
perm = [(j, (j + 1) % axis_size) for j in range(axis_size)]
return lax.ppermute(a, 'x', perm=perm)
c = fwd(a)
self.assertAllClose(c[1, :], a[0, :])
@jtu.run_on_devices("gpu")
def test_psend_precv_basic_two_gpus(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)))
weights = jax.random.uniform(
key=jax.random.key(0), shape=(2, 1), dtype=jnp.float32)
@jax.jit
@partial(
shard_map, mesh=mesh, in_specs=(P('x', None),), out_specs=P('x', None)
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
fwd_token = jax.lax.psend(a, 'x', [(0, 1)])
data = jax.lax.precv(
fwd_token, return_dtype_and_shape, 'x', [(0, 1)])
# Here we use an optimization barrier to enforce an arbitrary ordering of
# operations. This makes sure the mat mul only happens after the recv is
# complete.
weights_, _ = (
jax.lax.optimization_barrier(
(weights, data)
)
)
res = jnp.dot(weights_, data)
# send the compute result back to the first device
bwd_token = jax.lax.psend(
res,
axis_name='x',
perm=[(1, 0)],
)
bwd_data = jax.lax.precv(
bwd_token,
out_shape=return_dtype_and_shape,
axis_name='x',
perm=[(1, 0)]
)
return bwd_data
c = fwd(a)
self.assertEqual(c.shape, a.shape)
@jtu.run_on_devices("gpu")
def test_psend_precv_basic_with_no_deadlock_cycle(self):
mesh = jtu.create_mesh((8,), 'x')
a = jax.device_put(
jnp.arange(8 * 8, dtype=jnp.float32).reshape((8, 8)),
jax.sharding.NamedSharding(mesh, P('x', None)))
weights = jax.random.uniform(
key=jax.random.key(0), shape=(8, 1), dtype=jnp.float32)
@jax.jit
@partial(
jax.shard_map, mesh=mesh, in_specs=(P('x', None),), out_specs=P('x', None)
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
# We define the "forward edge" to be the device-to-device communication
# originating from device 0 in increasing indices.
fwd_token = jax.lax.psend(
a,
axis_name="x",
perm=[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)],
)
data = jax.lax.precv(
fwd_token,
out_shape=return_dtype_and_shape,
axis_name="x",
perm=[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)],
)
# Here we use an optimization barrier to enforce an arbitrary ordering of
# collectives. This will make sure compute happens after recv on the forward
# edge, and by extension will make sure the send on the back edge happens
# after the recv on the forward edge. Without this optimization barrier, the
# send on the backward edge might slip before the forward edge recv ops are
# completed, and will cause a deadlock.
weights_, _ = (
jax.lax.optimization_barrier(
(weights, data)
)
)
res = jnp.dot(weights_, data)
# send the compute result back to the first device
bwd_token = jax.lax.psend(
res,
axis_name="x",
perm=[(7, 0)],
)
bwd_data = jax.lax.precv(
bwd_token,
out_shape=return_dtype_and_shape,
axis_name="x",
perm=[(7, 0)]
)
return bwd_data
c = fwd(a)
self.assertEqual(c.shape, a.shape)
@jtu.run_on_devices('gpu')
def test_psend_precv_basic_with_deadlock_cycle(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
@jax.jit
@partial(
jax.shard_map,
mesh=mesh,
in_specs=P('x', None),
out_specs=P('x', None),
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
fwd_token = jax.lax.psend(
a,
axis_name='x',
perm=[(0, 1), (1, 0)],
)
data = jax.lax.precv(
fwd_token,
out_shape=return_dtype_and_shape,
axis_name='x',
perm=[(0, 1), (1, 0)],
)
return data
expected_error_message = (
'Expected send and recv instructions to have non-cyclical'
' source-target pairs'
)
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError, expected_error_message
):
fwd(a)
@jtu.run_on_devices('gpu')
def test_psend_precv_basic_with_dangling_recv(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
@jax.jit
@partial(
jax.shard_map,
mesh=mesh,
in_specs=P('x', None),
out_specs=P('x', None),
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
data = jax.lax.precv(
jax.lax.create_token(),
out_shape=return_dtype_and_shape,
axis_name='x',
perm=[(0, 1)],
)
return data
expected_error_message = 'Expected send to match recv'
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError, expected_error_message
):
fwd(a)
@jtu.run_on_devices('gpu')
def test_psend_precv_basic_with_non_matching_source_target_pairs(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
@jax.jit
@partial(
jax.shard_map,
mesh=mesh,
in_specs=P('x', None),
out_specs=P('x', None),
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
fwd_token = jax.lax.psend(
a,
axis_name='x',
perm=[(0, 1)],
)
data = jax.lax.precv(
fwd_token,
out_shape=return_dtype_and_shape,
axis_name='x',
perm=[(1, 0)],
)
return data
expected_error_message = (
'Deadlock detected. Last checked instructions: %psend'
)
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError, expected_error_message
):
fwd(a)
@jtu.run_on_devices('gpu')
def test_psend_precv_basic_with_duplicate_source_target_pairs(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
@jax.jit
@partial(
jax.shard_map,
mesh=mesh,
in_specs=P('x', None),
out_specs=P('x', None),
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
fwd_token = jax.lax.psend(
a,
axis_name='x',
perm=[(0, 1), (0, 1)],
)
data = jax.lax.precv(
fwd_token,
out_shape=return_dtype_and_shape,
axis_name='x',
perm=[(1, 0)],
)
return data
expected_error_message = (
'psend sources and destinations must be unique'
)
with self.assertRaisesRegex(
ValueError, expected_error_message
):
fwd(a)
@jtu.run_on_devices("gpu")
def test_psend_precv_reverse_two_gpus(self):
mesh = jtu.create_mesh((2,), 'x')
a = jax.device_put(
jnp.arange(2 * 2, dtype=jnp.float32).reshape((2, 2)),
jax.sharding.NamedSharding(mesh, P('x', None)))
@jax.jit
@partial(
jax.shard_map, mesh=mesh, in_specs=(P('x', None),), out_specs=P('x', None)
)
def fwd(a):
return_dtype_and_shape = jax.ShapeDtypeStruct(a.shape, a.dtype)
dummy_data = jax.lax.precv(
jax.lax.create_token(),
out_shape=return_dtype_and_shape,
axis_name="x",
perm=[(0, 1)],
)
_ = jax.lax.psend(
dummy_data,
axis_name="x",
perm=[(0, 1)],
)
return dummy_data
c = fwd(a)
self.assertAllClose(c, jnp.zeros_like(a))
def test_collective_permute_with_multiple_axis_names(self):
mesh = jtu.create_mesh((2, 2, 2), ('x', 'y', 'z'))
a = jax.device_put(
jnp.arange(8 * 8).reshape((4, 16)),
jax.sharding.NamedSharding(mesh, P('x', ('y', 'z'))),
)
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(P('x', ('y', 'z')),),
out_specs=P('x', ('y', 'z')),
)
def fwd(a):
xy_axis_size = lax.axis_size(('x', 'y'))
yz_axis_size = lax.axis_size(('y', 'z'))
xy_perm = [(j, (j + 1) % xy_axis_size) for j in range(xy_axis_size)]
yz_perm = [(j, (j + 1) % yz_axis_size) for j in range(yz_axis_size)]
return (
lax.ppermute(a, ('x', 'y'), perm=xy_perm),
lax.ppermute(a, ('y', 'z'), perm=yz_perm),
)
c, d = fwd(a)
for i in range(8):
self.assertAllClose(
a.addressable_data(i), c.addressable_data((i + 2) % 8)
)
self.assertAllClose(
a.addressable_data(i), d.addressable_data(4 * (i // 4) + (i + 1) % 4)
)
@parameterized.named_parameters(
dict(
testcase_name='_single_axis_name', axis_name='x', mesh_axes=dict(x=8)
),
dict(
testcase_name='_multiple_axis_names',
axis_name=('x', 'y'),
mesh_axes=dict(x=4, y=2),
),
)
def test_all_to_all(self, axis_name, mesh_axes):
mesh = jtu.create_mesh(tuple(mesh_axes.values()), tuple(mesh_axes.keys()))
a = jax.device_put(
jnp.arange(8 * 8).reshape((8, 8)),
jax.sharding.NamedSharding(mesh, P(axis_name, None)),
)
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(P(axis_name, None),),
out_specs=P(None, axis_name),
)
def fwd(a):
return lax.all_to_all(
a, axis_name, split_axis=1, concat_axis=1, tiled=True
)
c = fwd(a)
assert (c == jnp.reshape(a.T, (1, 64))).all()
@parameterized.named_parameters(
dict(
testcase_name='_partial_replicated', replicate_on_axes='x',
),
dict(
testcase_name='_fully_replicated',
replicate_on_axes=('x', 'y'),
),
)
@jtu.run_on_devices("gpu")
def test_pbroadcast(self, replicate_on_axes):
mesh = jtu.create_mesh((4, 2), ('x', 'y'))
sharded_axes = set(mesh.axis_names) - set(replicate_on_axes)
sharded_axes = None if not sharded_axes else list(sharded_axes)
in_out_sharding = jax.sharding.NamedSharding(mesh, P(sharded_axes, None))
a = jax.device_put(jnp.arange(16).reshape((4, 4)), in_out_sharding)
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(in_out_sharding.spec,),
out_specs=in_out_sharding.spec,
check_vma=False,
)
def fwd(x):
axis_index = lax.axis_index(replicate_on_axes)
x = jnp.where(axis_index == 0, x + 1, x)
return lax.pbroadcast(x, replicate_on_axes, source=0)
c = fwd(a) # Don't crash
self.assertAllClose(c, a + 1)
def test_all_to_all_with_axis_index_groups(self):
mesh = jtu.create_mesh((4,), ('x',))
a = jax.device_put(
jnp.arange(4 * 4).reshape((4, 4)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
self.assertEqual(a.addressable_data(0).shape, (1, 4))
@jax.jit
@partial(
shard_map,
mesh=mesh,
in_specs=(P('x', None),),
out_specs=P(None, 'x'),
)
def fwd(a):
return lax.all_to_all(
a,
'x',
split_axis=1,
concat_axis=0,
axis_index_groups=((0, 1), (2, 3)),
tiled=True,
)
c = fwd(a)
# Each shard corresponds to a quadrant rather than a row.
self.assertEqual(c.addressable_data(0).shape, (2, 2))
for i, row_block in enumerate(np.split(a, 2, axis=0)):
for j, block in enumerate(np.split(row_block, 2, axis=-1)):
self.assertAllClose(block, c.addressable_data(2 * i + j))
def test_all_to_all_grad(self):
mesh = jtu.create_mesh((4,), 'x')
a = jax.device_put(
jnp.arange(8 * 8, dtype=jnp.float32).reshape((8, 8)),
jax.sharding.NamedSharding(mesh, P('x', None)),
)
self.assertEqual(a.addressable_data(0).shape, (2, 8))
@jax.jit
@partial(
shard_map, mesh=mesh, in_specs=(P('x', None),), out_specs=P(None, 'x')
)
def fwd(x):
return lax.all_to_all(x, 'x', split_axis=1, concat_axis=0, tiled=True)
c = fwd(a)
self.assertEqual(c.addressable_data(0).shape, (8, 2))
self.assertAllClose(a, c)
@jax.jit
@partial(jax.grad, has_aux=True)
def loss_and_grad(x):
loss = fwd(x).sum() * 2
return loss, loss
grad, loss = loss_and_grad(a)
self.assertEqual(loss, 2 * sum(range(64)))
self.assertAllClose(grad, 2 * np.ones_like(a))
def test_eager_repr(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
s = None
@partial(shard_map, mesh=mesh, in_specs=P('x', 'y'), out_specs=P('x', 'y'))
def f(x):
nonlocal s
s = str(x)
return x
_ = f(np.arange(8 * 8.).reshape(8, 8))
self.assertIsInstance(s, str)
self.assertIn('at mesh coordinates', s)
def test_jvp_basic(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
g = shard_map(lambda x: jnp.sin(jnp.cos(x)), mesh=mesh,
in_specs=(P('x', 'y'),), out_specs=P('x', 'y'))
args = np.arange(4 * 4.).reshape(4, 4),
jtu.check_grads(g, args, 2, ['fwd'])
jtu.check_grads(jax.jit(g), args, 2, ['fwd'])
def test_linearize_basic(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
g = shard_map(lambda x: jnp.sin(jnp.cos(x)), mesh=mesh,
in_specs=(P('x', 'y'),), out_specs=P('x', 'y'))
x = np.arange(4 * 4.).reshape(4, 4)
y, y_dot = jax.jvp(g, [x], [x])
y_, g_lin = jax.linearize(g, x)
y_dot_ = g_lin(x)
self.assertAllClose(y, y_, check_dtypes=False)
self.assertAllClose(y_dot, y_dot_, check_dtypes=False)
def test_linearize_basic_repres(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
g = shard_map(lambda x: jax.lax.sin(jax.lax.cos(x)), mesh=mesh,
in_specs=(P('x',),), out_specs=P('x',))
x = np.arange(4.)
y, y_dot = jax.jvp(g, [x], [x])
y_, g_lin = jax.linearize(g, x)
y_dot_ = g_lin(x)
self.assertAllClose(y, y_, check_dtypes=False)
self.assertAllClose(y_dot, y_dot_, check_dtypes=False)
def test_linearize_basic_repres_jit(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
g = shard_map(lambda x: jnp.sin(jnp.cos(x)), mesh=mesh,
in_specs=(P('x',),), out_specs=P('x',))
x = np.arange(4.)
y, y_dot = jax.jvp(g, [x], [x])
y_, g_lin = jax.linearize(g, x)
y_dot_ = g_lin(x)
self.assertAllClose(y, y_, check_dtypes=False)
self.assertAllClose(y_dot, y_dot_, check_dtypes=False)
def test_replication_checker_eager(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = np.arange(8 * 8.).reshape(8, 8)
def f(x):
return 2 * x
def g(x):
return shard_map(f, mesh=mesh, in_specs=(P('x', 'y'),), out_specs=P(None, 'y'))(x)
with self.assertRaisesRegex(ValueError, 'statically inferred'):
g(x)
def f2(x):
return jax.lax.psum(x, 'x')
def g2(x):
return shard_map(f2, mesh=mesh, in_specs=(P('x', 'y'),), out_specs=P(None, 'y'))(x)
_ = g2(x) # doesn't crash
def test_replication_checker_jit(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = np.arange(8 * 8.).reshape(8, 8)
def g(x):
return shard_map(lambda x: x * 2, mesh=mesh, in_specs=P('x', 'y'),
out_specs=P(None, 'y'))(x)
with self.assertRaisesRegex(ValueError, 'statically inferred'):
jax.jit(g)(x)
def g2(x):
return shard_map(lambda x: jax.lax.psum(x, 'x'), mesh=mesh,
in_specs=P('x', 'y'), out_specs=P(None, 'y'))(x)
jax.jit(g2)(x) # doesn't crash
def test_process_env_traces(self):
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
x = np.arange(8.)
def g(x):
y = (3. * x).sum()
z = shard_map(lambda x: 2 * x * y, mesh=mesh,
in_specs=(P('x'),), out_specs=P('x'))(np.arange(8.))
return z
jtu.check_grads(g, (x,), modes=['fwd'], order=2)
def test_eager_control_flow(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = jnp.arange(2 * 2.).reshape(2, 2)
def f(x):
y = jax.lax.psum(x, ('x', 'y'))
if y < 0:
return x
else:
return -x
def g(x):
return shard_map(f, mesh=mesh, in_specs=(P('x', 'y'),), out_specs=P('x', 'y'))(x)
y = g(x)
self.assertAllClose(y, -x, check_dtypes=False)
def test_outer_jit_detects_shard_map_mesh(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
f = shard_map(lambda x: x.reshape(1, *x.shape), mesh=mesh, in_specs=P(),
out_specs=P('x'))
_ = jax.jit(f)(jnp.array(2.0)) # doesn't crash
def test_vmap_basic(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = jnp.arange(8 * 8.).reshape(8, 8)
def g(x):
return shard_map(lambda x: 2. * x, mesh=mesh,
in_specs=P('y'), out_specs=P('y'))(x)
y = jax.vmap(g)(x)
self.assertAllClose(y, 2 * x, check_dtypes=False)
def test_vmap_basic_axis_name(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = jnp.arange(8 * 8.).reshape(8, 8)
def g(x):
return shard_map(lambda x: 2. * x, mesh=mesh,
in_specs=P('y'), out_specs=P('y'))(x)
y = jax.vmap(g, axis_name='i')(x)
self.assertAllClose(y, 2 * x, check_dtypes=False)
def test_vmap_basic_axis_name_reuse_mesh_name(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = jnp.arange(8 * 8.).reshape(8, 8)
def g(x):
return shard_map(lambda x: 2. * x, mesh=mesh,
in_specs=P('y'), out_specs=P('y'))(x)
y = jax.vmap(g, axis_name='x')(x) # NOTE reuse same 'x' as on mesh
self.assertAllClose(y, 2 * x, check_dtypes=False)
def test_tree_prefix_error(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@partial(shard_map, mesh=mesh, in_specs=([P('x', 'y')],), out_specs=P('x', 'y'))
def f(x):
return x
x = jnp.arange(8 * 8.).reshape(8, 8)
with self.assertRaisesRegex(ValueError, r'shard_map in_specs\[0\]'):
f([x, x])
def test_rank_errors(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
def foo():
return {'hi': [3.]}
with self.assertRaisesRegex(ValueError, 'which has length 1'):
shard_map(foo, mesh=mesh, in_specs=(), out_specs={'hi': P('x')})()
with self.assertRaisesRegex(ValueError, 'which has length 1'):
jax.jit(lambda: shard_map(foo, mesh=mesh,
in_specs=(), out_specs={'hi': P('x')})())()
with self.assertRaisesRegex(ValueError, 'which has rank 0'):
shard_map(foo, mesh=mesh, in_specs=({'hi': P('x')},), out_specs=())(
{'hi': [jnp.array(3.)]})
with self.assertRaisesRegex(ValueError,
r'consider using an in_specs entry of `P\(\)`'):
shard_map(foo, mesh=mesh, in_specs=P(None), out_specs=())(3.)
def test_reverse_mode_ad(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@jax.jit
@partial(shard_map, mesh=mesh,
in_specs=(P('x',), P(None)), out_specs=P('x',))
def f(x, y):
return jnp.sin(x) + 3 + jnp.tan(2.) * jnp.cos(x) + y
x = jnp.arange(8.) / 10.
y = jnp.arange(4.) / 10.
jtu.check_grads(f, (x, y), modes=['fwd', 'rev'], order=2)
def test_post_process(self):
# JVPTrace.post_process_shard_map and JaxprTrace.post_process_shard_map
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
def f(x):
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def g(y):
return jnp.sin(y) * jnp.sin(x).sum()
return g(jnp.arange(8.))
x = jnp.arange(8.)
_, f_lin = jax.linearize(f, x)
y_dot = f_lin(x)
y_dot_expected = jnp.sin(jnp.arange(8.)) * (jnp.cos(x) * x).sum()
self.assertAllClose(y_dot, y_dot_expected, check_dtypes=False)
@jtu.run_on_devices('gpu', 'tpu')
def test_axis_index(self):
mesh = jtu.create_mesh((4,), 'x')
@jax.jit
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=P('x'))
def f():
return jax.lax.axis_index('x')[None]
x = f()
self.assertAllClose(x, jnp.arange(4), check_dtypes=False)
def test_optimize_remat(self):
mesh = jtu.create_mesh((4,), 'x')
@jax.custom_vjp
def f(x):
return jnp.tan(x)
def f_fwd(x):
return jax.lax.psum(x, 'x'), (x,)
def f_bwd(res, g):
x, = res
cos_x = jnp.cos(x)
return (cos_x * g,)
f.defvjp(f_fwd, f_bwd, optimize_remat=True)
@jax.jit
@jax.shard_map(mesh=mesh, in_specs=P(), out_specs=P())
def temp(x):
out = jax.remat(f)(x)
out = out ** 2
return out
jax.grad(lambda x: temp(x).sum())(jnp.arange(4.))
def test_remat_basic(self):
# this tests remat-of-shmap
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
# check param updating is handled
@jax.remat
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return jnp.sin(jnp.sin(x))
x = jnp.arange(4.)
g = jax.grad(lambda x: f(x).sum())(x) # doesn't crash
self.assertAllClose(g, jnp.cos(jnp.sin(x)) * jnp.cos(x), check_dtypes=False,
atol=1e-3, rtol=1e-3)
saved_res = saved_residuals(f, x)
self.assertLen(saved_res, 1)
# also check residuals are handled correctly
@partial(jax.remat, policy=jax.checkpoint_policies.everything_saveable)
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f2(x):
return jnp.sin(jnp.sin(x))
g2 = jax.grad(lambda x: f2(x).sum())(x) # doesn't crash
self.assertAllClose(g2, jnp.cos(jnp.sin(x)) * jnp.cos(x),
check_dtypes=False, atol=1e-3, rtol=1e-3)
saved_res = saved_residuals(f2, x)
self.assertLen(saved_res, 2)
def test_shmap_of_remat_basic(self):
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
x = jnp.arange(4.)
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
@partial(jax.remat, policy=jax.checkpoint_policies.everything_saveable)
def f2(x):
return jnp.sin(x)
g2 = jax.grad(lambda x: f2(x).sum())(x) # doesn't crash
self.assertAllClose(g2, jnp.cos(x), check_dtypes=False)
@jtu.skip_on_flag("jax_skip_slow_tests", True)
def test_remat_scalar_residuals(self):
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
@partial(jax.remat, policy=jax.checkpoint_policies.everything_saveable)
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return jnp.sin(jnp.sin(jnp.sin(x.sum()))[None])
x = jnp.arange(8.)
_ = jax.grad(lambda x: f(x).sum())(x) # doesn't crash
jtu.check_grads(f, (x,), modes=['rev'], order=2, atol=1e-2, rtol=1e-2)
def test_collectives_not_saved(self):
# regression test for bug in cl/612416803
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
@jax.remat
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return jax.lax.all_gather(x, 'x') * jax.lax.all_gather(x, 'x')
saved_res = saved_residuals(f, jnp.ones(4))
self.assertLen(saved_res, 1)
def test_check_rep_false_doesnt_hit_rep_rules(self):
mesh = Mesh(np.array(jax.devices()[:4]), ('x',))
prim = core.Primitive('prim') # no rep rule here!
prim.multiple_results = True
prim.def_impl(lambda: [])
prim.def_abstract_eval(lambda: [])
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_vma=True)
def f():
prim.bind()
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_vma=False)
def f2():
prim.bind()
f2()
jax.jit(f2)()
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=None, check_vma=False)
def f3():
jax.jit(prim.bind)()
f3()
jax.jit(f3)()
def test_multiple_result_primitive_with_none_sharding(self):
# https://github.com/jax-ml/jax/issues/27673
xs = jnp.arange(20).reshape(2, 10)
mesh = jtu.create_mesh((2,), ("i",))
y = shard_map(
lambda x: jnp.split(x.squeeze(), 2),
mesh=mesh,
in_specs=(None,),
out_specs=P("i"),
)(xs)
expected = jnp.repeat(xs, 2, axis=0).reshape(2, 2, 10)
self.assertArraysEqual(y, expected)
def test_vmap_spmd_axis_name(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return x
x = jnp.arange(4 * 4).reshape(4, 4)
jaxpr = jax.make_jaxpr(jax.vmap(f, spmd_axis_name='y'))(x).jaxpr
e, = jaxpr.eqns
self.assertIn('in_specs', e.params)
self.assertEqual(e.params['in_specs'], (P('y', 'x'),))
self.assertIn('out_specs', e.params)
self.assertEqual(e.params['out_specs'], (P('y', 'x'),))
def test_vmap_explicit_mesh_axis(self):
mesh = jtu.create_mesh(
(1, 2, 2), ('z', 'x', 'y'), axis_types=(AxisType.Explicit,) * 3)
@shard_map(mesh=mesh, in_specs=P('y'), out_specs=P('y'))
def f(x):
return x
s = NamedSharding(mesh, P(('z', 'x'), 'y'))
x = jax.device_put(jnp.arange(4 * 4).reshape(4, 4), s)
f = jax.jit(jax.vmap(f))
out = f(x)
self.assertEqual(out.sharding, s)
@jtu.with_explicit_mesh((2, 2), ('data', 'model'))
def test_vmap_explicit_mesh_axis_single_axis(self, mesh):
x = jax.device_put(jnp.arange(4 * 4).reshape(4, 4), P('data', 'model'))
@shard_map(in_specs=P('model'), out_specs=P('model'))
def f(x):
return x
f = jax.jit(jax.vmap(f))
out = f(x)
self.assertEqual(out.sharding, NamedSharding(mesh, P('data', 'model')))
def test_vmap_explicit_mesh_axis_error(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Explicit,) * 2)
@shard_map(mesh=mesh, in_specs=P('x'), out_specs=P('x'),
axis_names={'x', 'y'})
def f(x):
return x
x = jnp.arange(4 * 4).reshape(4, 4)
s = NamedSharding(mesh, P('x', 'y'))
x = jax.device_put(x, s)
f = jax.jit(jax.vmap(f))
with self.assertRaisesRegex(
ValueError, "jax.shard_map requires axis_names.*subset of"):
f(x)
f = jax.jit(jax.vmap(f, spmd_axis_name='y'))
with self.assertRaisesRegex(
ValueError,
'Only one of spmd_axis_name or arrays sharded on `Explicit` mesh axis'
' type is allowed'):
f(x)
def test_vmap_of_grad_spmd_axis_name(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@partial(
shard_map, mesh=mesh, in_specs=P('y'), out_specs=P(), check_vma=False
)
def f(x):
return jnp.sin(jnp.sum(x))
x = jnp.arange(4 * 4, dtype=jnp.float32).reshape(4, 4)
put_x = jax.device_put(
x,
jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec('x', 'y')),
)
vmap_spmd_axisname_result = jax.vmap(jax.grad(f), spmd_axis_name='x')(put_x)
vmap_no_spmd_axisname_result = jax.vmap(jax.grad(f))(put_x)
self.assertArraysEqual(
vmap_spmd_axisname_result, vmap_no_spmd_axisname_result
)
def test_vmap_spmd_axis_name_pair(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
@partial(shard_map, mesh=mesh, in_specs=P(), out_specs=P())
def f(x):
return x
x = jnp.arange(4 * 4).reshape(4, 4)
jaxpr = jax.make_jaxpr(jax.vmap(f, spmd_axis_name=('x', 'y')))(x).jaxpr
e, = jaxpr.eqns
self.assertIn('in_specs', e.params)
self.assertEqual(e.params['in_specs'][0], P(('x', 'y')))
self.assertIn('out_specs', e.params)
self.assertEqual(e.params['out_specs'][0], P(('x', 'y')))
def test_nested_vmap_with_capture_spmd_axis_name(self):
self.skipTest('https://github.com/jax-ml/jax/issues/23476')
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
def to_map_with_capture(x, y):
# We capture x from `to_map_with_capture`'s parameters.
def with_capture(y_slice):
# Inside of all the maps, we have 'mapped everything away'--we are just
# adding two scalars, but one by fully mapping across each of the two
# dimensions, the other by mapping across one and capturing the
# resulting scalar.
self.assertEqual(x.shape, ())
self.assertEqual(y_slice.shape, ())
return x + y_slice
# This vmap i will refer to as 'inner vmap'.
vmap_with_capture = jax.vmap(with_capture)
shmap_vmap_capture = shard_map(
vmap_with_capture, mesh=mesh, in_specs=P('y'), out_specs=P('y')
)
return shmap_vmap_capture(y)
# And this one is the outer vmap.
mapped = jax.vmap(to_map_with_capture, spmd_axis_name='x')
x = jnp.arange(2).reshape(2)
y = jnp.arange(2 * 2).reshape(2, 2)
# Inner vmap inside of shard-map will be over an axis of size 1. Outer vmap
# is over an axis of size 2. This is a problem at the moment.
jax.make_jaxpr(mapped)(x, y).jaxpr
def test_shard_map_abstract_mesh(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, NamedSharding(mesh, P('x', 'y')))
def f(x):
return shard_map(lambda x: x, mesh=mesh.abstract_mesh, in_specs=P('x'),
out_specs=P('x'))(x)
out1 = jax.jit(f)(arr)
self.assertArraysEqual(out1, np_inp)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('x')))
out_eager = f(arr)
self.assertArraysEqual(out_eager, np_inp)
self.assertEqual(out_eager.sharding, NamedSharding(mesh, P('x')))
out1, out2 = shard_map(lambda x, y: (x, y), mesh=mesh.abstract_mesh,
in_specs=P('x'), out_specs=P('x'))(np_inp, arr)
self.assertArraysEqual(out1, np_inp)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('x')))
self.assertArraysEqual(out2, np_inp)
self.assertEqual(out2.sharding, NamedSharding(mesh, P('x')))
def test_different_devices_shmap_abstract_mesh_cache_hit(self):
if jax.device_count() < 4:
self.skipTest('Requires >=4 devices')
mesh1 = jax.sharding.Mesh(jax.devices()[:2], 'i')
mesh2 = jax.sharding.Mesh(jax.devices()[2:4], 'i')
abstract_mesh = mesh1.abstract_mesh
@jax.jit
def f(x):
x = shard_map(lambda x: x, mesh=abstract_mesh, in_specs=P('i'),
out_specs=P('i'))(x)
return jax.lax.sin(x)
with (
jtu.count_jit_tracing_cache_miss() as tracing_count,
jtu.count_jit_and_pmap_lowerings() as lowering_count,
jtu.count_jit_compilation_cache_miss() as compilation_count,
):
a = jax.device_put(np.arange(8.), NamedSharding(mesh1, P()))
out_a = f(a) # tracing and lowering cached
# same num_devices but different devices.
b = jax.device_put(out_a, NamedSharding(mesh2, P()))
f(b) # tracing and lowering cache *hit*
self.assertEqual(tracing_count(), 1)
self.assertEqual(lowering_count(), 1)
self.assertEqual(compilation_count(), 2) # 2 misses since devices differ.
def test_shmap_abstract_mesh_errors(self):
mesh = jtu.create_mesh((2,), ('x',))
np_inp = np.arange(8)
abstract_mesh = mesh.abstract_mesh
with self.assertRaisesRegex(
ValueError,
"Please pass `jax.Array`s with a `NamedSharding` as input to"
" `shard_map` when passing `AbstractMesh` to the mesh argument"):
shard_map(lambda x: x, mesh=abstract_mesh, in_specs=P('x'),
out_specs=P('x'))(jnp.arange(8))
arr = jax.device_put(np_inp, NamedSharding(mesh, P('x')))
mesh2 = jtu.create_mesh((2,), 'y')
abs_mesh2 = mesh2.abstract_mesh
with self.assertRaisesRegex(
ValueError,
'Mesh shape of the input.*does not match the mesh shape passed to'
' shard_map'):
shard_map(lambda x: x, mesh=abs_mesh2, in_specs=P('y'),
out_specs=P('y'))(arr)
with self.assertRaisesRegex(
ValueError,
'Please pass `jax.Array`s with a `NamedSharding` as input to'
' `shard_map` when passing `AbstractMesh` to the mesh argument.'):
shard_map(lambda x: x, mesh=abstract_mesh, in_specs=P('x'),
out_specs=P('x'))(np_inp)
arr_mesh2 = jax.device_put(np_inp, NamedSharding(mesh2, P('y')))
with self.assertRaisesRegex(
ValueError,
'Mesh shape of the input.*does not match the mesh shape passed to'
' shard_map'):
shard_map(lambda x, y: (x, y), mesh=abstract_mesh, in_specs=P('x'),
out_specs=P('x'))(arr, arr_mesh2)
@parameterized.parameters([True, False])
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
@jtu.thread_unsafe_test()
def test_debug_print_jit(self, jit):
mesh = Mesh(jax.devices(), ('i',))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
idx = jax.lax.axis_index('i')
jax.debug.print("instance {i} has value x={x}", i=idx, x=x)
y = jnp.cos(x)
jax.debug.print("instance {i} has value y={y}", i=idx, y=y)
return y
if jit:
f = jax.jit(f)
x = jnp.arange(2 * len(jax.devices()))
with jtu.capture_stdout() as output:
f(x)
jax.effects_barrier()
for i in range(len(jax.devices())):
self.assertIn(f'instance {i} has value', output())
@jtu.with_explicit_mesh((2,), ('x'))
def test_pure_callback_return_multiple_arrays(self, mesh):
def host_kernel(arr: np.ndarray):
return arr + 1, arr * 2.0
@jax.shard_map(in_specs=P('x'), out_specs=(P('x'), P('x')))
def per_shard(x_shard):
spec = jax.ShapeDtypeStruct(x_shard.shape, x_shard.dtype)
return jax.pure_callback(host_kernel, (spec, spec), x_shard)
x = np.arange(32, dtype=np.float32).reshape(16, 2)
per_shard(x) # doesn't crash
def test_psum_transpose_non_zero_cts(self):
mesh = jtu.create_mesh((8,), 'x')
@shard_map(mesh=mesh, in_specs=P('x'), out_specs=(P('x'), P()))
def f1(x_block):
return x_block, jax.lax.psum(x_block, axis_name='x')
x1 = jnp.arange(16.)
f1(x1) # doesn't crash
def f2(x_block):
y, _ = f1(x_block)
return y.sum()
jax.jit(jax.grad(f2))(x1) # doesn't crash
jax.grad(f2)(x1) # doesn't crash
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
@jtu.thread_unsafe_test()
def test_debug_print_jit_partial_auto(self):
mesh = jtu.create_mesh((2,2), ('x', 'y'))
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'),
axis_names=frozenset({'x'}))
def f(x):
idx = jax.lax.axis_index('x')
jax.debug.print("instance {i} has value x={x}", i=idx, x=x)
y = jnp.cos(x)
return y
f = jax.jit(f)
x = jnp.arange(2 * len(jax.devices()))
f(x) # don't crash!
def test_debug_print_eager(self):
mesh = Mesh(jax.devices(), ('i',))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
jax.debug.print("x={x}", x=x)
y = jnp.cos(x)
jax.debug.print("y={y}", y=y)
return y
x = jnp.arange(2 * len(jax.devices()))
with jtu.capture_stdout() as output:
f(x)
jax.effects_barrier()
for i in range(len(jax.devices())):
self.assertIn(f'x=[{2*i} {2*i+1}]', output())
def test_partial_auto_axis_index_eager(self):
mesh = jtu.create_mesh((2, 2, 1), ('i', 'j', 'k'))
def f():
return jax.lax.axis_index('i').reshape((1,))
def g():
return jax.shard_map(f, mesh=mesh, in_specs=(), out_specs=P('i'),
axis_names={'i'}, check_vma=False)()
out = g()
expected_out = jax.jit(g)()
self.assertArraysEqual(out, expected_out)
def test_partial_eval_custom_axis_env(self):
mesh = Mesh(jax.devices(), ('i',))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(_):
_, idx = jax.lax.scan(lambda _, __: (None, jax.lax.axis_index('i')),
None, None, length=1)
return idx
xs = jnp.arange(16.)
jax.eval_shape(jax.grad(lambda x: jax.remat(f)(x).sum().astype('float32')),
xs)
@jax.legacy_prng_key('allow')
def test_prngkeyarray_eager(self):
# https://github.com/jax-ml/jax/issues/15398
mesh = jtu.create_mesh((4,), ('x',))
sharding = jax.sharding.NamedSharding(mesh, P('x'))
rng = jax.random.PRNGKey(0)
sharded_rng = jax.random.split(rng, num=4)
sharded_rng = jax.device_put(sharded_rng, sharding)
def f(key):
return jax.random.randint(key[0], shape=(1, 16), minval=0, maxval=16,
dtype=jnp.int32)
pspec = P('x') if config.enable_custom_prng.value else P('x', None)
g = shard_map(f, mesh=mesh, in_specs=(pspec,), out_specs=pspec)
_ = g(sharded_rng) # don't crash!
@parameterized.parameters(['threefry2x32', 'rbg', 'unsafe_rbg'])
def test_sharded_random_bits(self, prng_impl):
mesh = jtu.create_mesh((4,), ('x',))
sharding = jax.sharding.NamedSharding(mesh, P('x'))
rng = jax.random.key(0, impl=prng_impl)
sharded_rng = jax.random.split(rng, num=4)
sharded_rng = jax.device_put(sharded_rng, sharding)
def f(key):
return jax.random.bits(key[0], shape=(4,), dtype=jnp.uint8)
g = shard_map(f, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
g(sharded_rng) # don't crash!
def test_vma_out_specs_error_check(self):
mesh = jtu.create_mesh((2, 2, 2), ('x', 'y', 'z'))
@shard_map(mesh=mesh, in_specs=P('x', 'y', 'z'), out_specs=P('x'))
def f(x):
return x * 2
with self.assertRaisesRegex(
ValueError,
r".*out_specs is PartitionSpec\('x',\) which implies that the.*"
r' output value is only varying across mesh axes \{x\} and not \{y,z\},'
r' but it was inferred to be possibly varying over \{x,y,z\}.*'):
f(np.arange(16).reshape(4, 2, 2))
def test_functools_partial_rank_error(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial
def f(x):
return x
g = shard_map(f, mesh=mesh, in_specs=(P('x', None),), out_specs=P('x',))
x = jnp.arange(4)
with self.assertRaises(ValueError):
g(x)
def test_in_specs_none_error(self):
mesh = jtu.create_mesh((4,), ('x',))
def f(x): return x
shard_map(f, mesh=mesh, in_specs=None, out_specs=P())(3.) # doesn't crash
shard_map(f, mesh=mesh, in_specs=(None,), out_specs=P())(3.) # doesn't crash
shard_map(f, mesh=mesh, in_specs=P(), out_specs=P())(3.) # doesn't crash
def test_scan_rep_rule(self):
mesh = jtu.create_mesh((2, 2,), ('x', 'y'))
def f(x, y, z):
x, y, z = x.sum(), y.sum(), z.sum()
def body(c, _):
c, *cs = c
return (*cs, c), None
x = lax.pvary(x, ('x', 'y'))
y = lax.pvary(y, 'y')
out, _ = jax.lax.scan(body, (x, y, z), None, length=3)
return [jnp.expand_dims(a, 0) for a in out]
x = jnp.arange(4)
# doesn't crash, because out_spec assumes no replication (and there is none)
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P(('x', 'y')))(x, x, x)
# does crash, because output incorrectly promises replication
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P('x'))(x, x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P('y'))(x, x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P(None))(x, x, x)
def g(x, y, z):
x, y, z = x.sum(), y.sum(), z.sum()
def body(c, _):
return c, None
out, _ = jax.lax.scan(body, (x, y, z), None, length=1)
return [jnp.expand_dims(a, 0) for a in out]
# doesn't crash, because everything matches
shard_map(g, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=[P(None), P('x'), P(('x', 'y'))])(x, x, x)
# does crash, because the second guy is wrong
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(g, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=[P(None), P(None), P(('x', 'y'))])(x, x, x)
def test_while_rep_rule(self):
mesh = jtu.create_mesh((2, 2,), ('x', 'y'))
def f(x, y, z):
x, y, z = x.sum(), y.sum(), z.sum()
def cond(c):
i, *_ = c
return i < 5
def body(c):
i, c, *cs = c
return (i + 1, *cs, c)
x = lax.pvary(x, ('x', 'y'))
y = lax.pvary(y, 'y')
_, *out = jax.lax.while_loop(cond, body, (0, x, y, z))
return [jnp.expand_dims(a, 0) for a in out]
x = jnp.arange(4)
# doesn't crash, because out_spec assumes no replication (and there is none)
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P(('x', 'y')))(x, x, x)
# does crash, because output incorrectly promises replication
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P('x'))(x, x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P('y'))(x, x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=P(None))(x, x, x)
def g(x, y, z):
x, y, z = x.sum(), y.sum(), z.sum()
def cond(c):
i, *_ = c
return i < 1
def body(c):
i, *cs = c
return (i + 1, *cs)
_, *out = jax.lax.while_loop(cond, body, (0, x, y, z))
return [jnp.expand_dims(a, 0) for a in out]
# doesn't crash, because everything matches
shard_map(g, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=[P(None), P('x'), P(('x', 'y'))])(x, x, x)
# does crash, because the second guy is wrong
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(g, mesh=mesh, in_specs=(P(None), P('x'), P(('x', 'y'))),
out_specs=[P(None), P(None), P(('x', 'y'))])(x, x, x)
def test_cond_rep_rule(self):
mesh = jtu.create_mesh((2, 2,), ('x', 'y'))
x = jnp.arange(4)
def f(x, y):
def true_fn(x, y):
return x
def false_fun(x, y):
return x + 1
return jax.lax.cond(True, true_fn, false_fun, x, y)
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P('x'))(x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(None))(x, x)
def f(x, y):
def true_fn(x, y):
return lax.pvary(x, 'y')
def false_fun(x, y):
return lax.pvary(y, 'x')
return jax.lax.cond(True, true_fn, false_fun, x, y)
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(('x', 'y')))(x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P('x'))(x, x)
def f(x, y):
def true_fn(x, y):
return x
def false_fun(x, y):
return x + 1
return jax.lax.cond(jnp.any(x > 0), true_fn, false_fun, x, y)
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P('x'))(x, x)
with self.assertRaisesRegex(ValueError, "require replication"):
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(None))(x, x)
def f(x, y):
def true_fn(x, y):
return x
def false_fun(x, y):
return x + 1
return jax.lax.cond(jnp.any(y > 0), true_fn, false_fun, x, y)
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(('x', 'y')))(x, x)
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P('x'))(x, x)
# https://github.com/jax-ml/jax/issues/24418
def f(a):
c = jax.lax.cond(jnp.any(a), lambda: 1, lambda: 0)
return jnp.reshape(c, a.shape)
mesh = jtu.create_mesh((2,), ('x',))
a = jnp.array([True, False])
shard_map(f, mesh=mesh, in_specs=P('x'), out_specs=P('x'))(a)
def test_switch_rep_rule(self):
mesh = jtu.create_mesh((2, 2,), ('x', 'y'))
x = jnp.arange(4)
def f(n, x, y):
return jax.lax.switch(
n, [lambda x, _: x, lambda x, _: x + 1, lambda x, _: x + 2], x, y)
shard_map(f, mesh=mesh, in_specs=(P(), P('x'), P('y')), out_specs=P('x'))(1, x, x)
def test_eager_custom_jvp_basic(self):
@jax.custom_jvp
def foo(x):
return 2. * x
@foo.defjvp
def foo_jvp(primals, tangents):
(x,), (x_dot,) = primals, tangents
return foo(x), 3. * x_dot
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(foo, mesh=mesh, in_specs=(P('x'),), out_specs=P('x'))
y, x_bar = jax.value_and_grad(lambda x: g(x).sum())(jnp.arange(4.))
self.assertAllClose(y, (2. * jnp.arange(4.)).sum())
self.assertAllClose(x_bar, 3. * jnp.ones(4), check_dtypes=False)
def test_eager_custom_vjp_basic(self):
@jax.custom_vjp
def foo(x):
return 2. * x
def foo_fwd(x):
return foo(x), None
def foo_bwd(_, y_bar):
return 3. * y_bar,
foo.defvjp(foo_fwd, foo_bwd)
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(foo, mesh=mesh, in_specs=(P('x'),), out_specs=P('x'))
y, x_bar = jax.value_and_grad(lambda x: g(x).sum())(jnp.arange(4.))
self.assertAllClose(y, (2. * jnp.arange(4.)).sum())
self.assertAllClose(x_bar, 3. * jnp.ones(4), check_dtypes=False)
@parameterized.parameters([True, False])
def test_axis_index_basic(self, jit):
def foo():
return jax.lax.axis_index('x')[None]
if jit:
foo = jax.jit(foo)
mesh = jtu.create_mesh((4,), ('x',))
ans = shard_map(foo, mesh=mesh, in_specs=(), out_specs=P('x'))()
expected = jnp.arange(4.)
self.assertAllClose(ans, expected, check_dtypes=False)
@parameterized.parameters([True, False])
def test_axis_index_twoaxes(self, jit):
def foo():
out1 = jax.lax.axis_index('i')[None, None]
out2 = jax.lax.axis_index('j')[None, None]
out3 = jax.lax.axis_index(('i', 'j'))[None, None]
return out1, out2, out3
if jit:
foo = jax.jit(foo)
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
ans1, ans2, ans3 = shard_map(foo, mesh=mesh, in_specs=(),
out_specs=P('i', 'j'))()
expected1 = jnp.arange(4.)[:, None] + jnp.zeros((4, 2))
expected2 = jnp.arange(2.)[None, :] + jnp.zeros((4, 2))
expected3 = jnp.arange(8.).reshape(4, 2)
self.assertAllClose(ans1, expected1, check_dtypes=False)
self.assertAllClose(ans2, expected2, check_dtypes=False)
self.assertAllClose(ans3, expected3, check_dtypes=False)
def test_axis_index_eager(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=P())
def foo():
val = jax.lax.psum(jax.lax.axis_index('x'), 'x')
return 1. if val > 0 else -1.
out = foo() # doesn't crash
self.assertEqual(out, 1.)
def test_jaxpr_shardings_with_no_outputs(self):
# https://github.com/jax-ml/jax/issues/15385
mesh = jtu.create_mesh((4,), ('i',))
@jax.jit
@partial(shard_map, mesh=mesh, in_specs=(), out_specs=P('i'))
def f():
return jax.lax.iota(jnp.dtype('int32'), 4)
f() # don't crash
@partial(shard_map, mesh=mesh, in_specs=(P('i'),), out_specs=P('i'))
def g(a_block):
i = jnp.arange(a_block.shape[0])
return i + a_block
g(np.arange(32)) # don't crash
def test_device_put(self):
mesh = jtu.create_mesh((4,), ('i',))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
return x + jax.device_put(1)
x = jnp.arange(32.)
f(x) # doesn't crash
jax.jit(f)(x) # doesn't crash
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def g(x):
return x + jax.device_put(1, jax.devices()[0])
with self.assertRaisesRegex(ValueError, "got device"):
g(x)
# jit means device_puts are ignored, even those within shmap bodies, so no
# error!
jax.jit(g)(x) # doesn't crash
@jtu.run_on_devices('cpu', 'gpu', 'tpu')
def test_key_array_with_replicated_last_tile_dim(self):
# See https://github.com/jax-ml/jax/issues/16137
mesh = jtu.create_mesh((2, 4), ('i', 'j'))
def f(rng):
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'),
check_vma=False)
def g(rng):
return jnp.array([jax.random.normal(rng[0])])
return g(jax.random.split(rng, 4))
jax.jit(f)(jax.random.key(0)) # doesn't crash
# same method appears in api_test.py:DCETest
# TODO(mattjj): consider moving this method to be a helper in jtu
def assert_dce_result(self, jaxpr: core.Jaxpr, used_outputs: list[bool],
expected_used_inputs: list[bool],
expected_num_eqns: int | None = None,
check_diff: bool = True):
jaxpr_dce, used_inputs = pe.dce_jaxpr(jaxpr, used_outputs)
core.check_jaxpr(jaxpr_dce)
self.assertEqual(used_inputs, expected_used_inputs)
if expected_num_eqns is not None:
all_jaxprs = it.chain([jaxpr_dce], core.subjaxprs(jaxpr_dce))
num_eqns = sum(len(subjaxpr.eqns) for subjaxpr in all_jaxprs)
self.assertEqual(num_eqns, expected_num_eqns, msg=str(jaxpr_dce))
rand_ = jtu.rand_small(np.random.RandomState(0))
rand = lambda v: rand_(v.aval.shape, v.aval.dtype)
consts = [rand(v) for v in jaxpr.constvars]
inputs = [rand(v) for v in jaxpr.invars ]
inputs_dce = [x for x, used in zip(inputs, used_inputs) if used]
full_outs = core.eval_jaxpr(jaxpr , consts, *inputs)
expected_outs_dce = [y for y, used in zip(full_outs, used_outputs) if used]
outs = core.eval_jaxpr(jaxpr_dce, consts, *inputs_dce)
self.assertAllClose(outs, expected_outs_dce)
if check_diff and expected_num_eqns != 0:
f = lambda *args: core.eval_jaxpr(jaxpr_dce, consts, *args)
jtu.check_grads(f, inputs_dce, order=2, modes=['rev'])
def test_returned_out_sharding(self):
mesh = jtu.create_mesh((1, 2), ('x', 'y'))
s = NamedSharding(mesh, P('x', 'y'))
inp = jax.device_put(jnp.zeros((2, 2)), s)
out = shard_map(lambda x: x, mesh=mesh, in_specs=P('x', 'y'),
out_specs=P('x', 'y'))(inp)
self.assertEqual(out.sharding, s)
self.assertArraysEqual(out, inp)
def test_dce(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
def f(x, y, z):
@partial(shard_map, mesh=mesh, in_specs=(P('i', 'j'), P(None, 'i')),
out_specs=(P(None, None), P(None, 'i'), P('i', 'j')))
def g(y, z):
return jnp.sin(x), jnp.cos(z), jnp.tan(y)
return g(y, z)
x = jnp.zeros((4, 4))
y = jnp.zeros((8, 8))
z = jnp.zeros((16, 16))
jaxpr = jax.make_jaxpr(f)(x, y, z).jaxpr
self.assertLen(jaxpr.eqns, 1)
self.assertLen(jaxpr.eqns[0].params['jaxpr'].eqns, 3)
# If we use all outputs, nothing should be deleted.
self.assert_dce_result(
jaxpr, used_outputs=[True, True, True],
expected_used_inputs=[True, True, True],
expected_num_eqns=1 + 3, # one outer eqn, three remain in body
check_diff=False)
# If we drop the last output, the second input should be dropped.
self.assert_dce_result(
jaxpr, used_outputs=[True, True, False],
expected_used_inputs=[True, False, True],
expected_num_eqns=1 + 2, # one outer eqn, two remain in body
check_diff=False)
# If we drop the second output, the last input should be dropped.
self.assert_dce_result(
jaxpr, used_outputs=[True, False, True],
expected_used_inputs=[True, True, False],
expected_num_eqns=1 + 2, # one outer eqn, two remain in body
check_diff=False)
# If we drop the latter two outputs, the latter two inputs should be dropped
self.assert_dce_result(
jaxpr, used_outputs=[True, False, False],
expected_used_inputs=[True, False, False],
expected_num_eqns=1 + 1, # one outer eqn, two remain in body
check_diff=False)
# Finally, try dropping the closed-over value.
self.assert_dce_result(
jaxpr, used_outputs=[False, True, False],
expected_used_inputs=[False, False, True],
expected_num_eqns=1 + 1, # one outer eqn, two remain in body
check_diff=False)
def test_post_process_partial_eval_with_scalar_res(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
g = jax.grad(lambda x: shard_map(lambda: jnp.sin(x), mesh=mesh,
in_specs=P(), out_specs=P())())(2.0)
self.assertAllClose(g, jnp.cos(2.0), check_dtypes=False)
def test_sharding_metadata_in_hlo_attrs(self):
mesh = Mesh(jax.devices(), ('i',))
x = jnp.arange(len(jax.devices()), dtype='float32')
y = jnp.array([3.], dtype='float32')
def foo(x):
x = jnp.sin(x)
x = shard_map(lambda x: jnp.cos(x * y), mesh=mesh,
in_specs=P('i'), out_specs=P('i'))(x)
x = shard_map(lambda x: jnp.cos(x * y), mesh=mesh,
in_specs=P('i'), out_specs=P('i'))(x)
return x
hlo_str = jax.jit(foo).lower(x).as_text("stablehlo", debug_info=True)
if config.use_shardy_partitioner.value:
if len(jax.devices()) > 1:
self.assertEqual(2, hlo_str.count('sdy.manual_computation'))
else:
# When devices == 1, the `sdy.manual_computation` is inlined.
self.assertEqual(0, hlo_str.count('sdy.manual_computation'))
else:
self.assertIn('call @shmap_body(', hlo_str)
self.assertIn('call @shmap_body_', hlo_str)
self.assertIn('%arg0: tensor<1xf32>', hlo_str)
if not config.use_simplified_jaxpr_constants.value:
# A constvar is turned into an argument with location None in @shmap_body
self.assertIn('"[None]"', hlo_str)
self.assertIn('%arg1: tensor<1xf32>', hlo_str)
self.assertIn('"[(\'i\',)]"', hlo_str)
self.assertIn(
'-> (tensor<1xf32> {jax.result_info = "[(\'i\',)]"})', hlo_str
)
def test_rewrite_process_call(self):
def f(x):
return core.call_p.bind(
lu.wrap_init(lambda x: [2. * x],
debug_info=api_util.debug_info("test", lambda x: [2. * x],
(x,), {})),
x)[0] * x
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(f, mesh=mesh, in_specs=(P('x'),), out_specs=P('x'))
x = jnp.arange(4.)
y = jax.jit(g)(x) # eager requires shmap to have ShardMapTrace.process_call
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
def test_rewrite_post_process_call(self):
# We shouldn't hit post_process_call here because of RewriteTrace's dynamic
# behavior (i.e. no data dependence).
mesh = jtu.create_mesh((4,), ('x',))
@jax.jit
@partial(shard_map, mesh=mesh, in_specs=(P('x'),), out_specs=P('x'))
def f(x):
return core.call_p.bind(
lu.wrap_init(lambda: [2. * x],
debug_info=api_util.debug_info("test", lambda: [2. * x],
(), {})))[0] * x
x = jnp.arange(4.)
y = f(x)
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
@parameterized.parameters([True, False])
def test_rewrite_process_custom_jvp_call(self, jit):
@jax.custom_jvp
def foo(x):
return 2. * x
@foo.defjvp
def foo_jvp(primals, tangents):
(x,), (x_dot,) = primals, tangents
return foo(x), 2. * x_dot
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(lambda x: foo(x) * x, mesh=mesh,
in_specs=(P('x'),), out_specs=P('x'))
if jit:
g = jax.jit(g)
x = jnp.arange(4.)
y = g(x)
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
y2, y_dot = jax.jvp(g, (x,), (3 * x,))
self.assertAllClose(y2, 2 * x * x, check_dtypes=True)
self.assertAllClose(y_dot, 2 * 2 * 3 * x * x, check_dtypes=True)
@parameterized.parameters([True, False])
def test_rewrite_process_custom_vjp_call(self, jit):
@jax.custom_vjp
def foo(x):
return 2. * x
def foo_fwd(x):
return foo(x), None
def foo_bwd(_, y_bar):
return 2. * y_bar,
foo.defvjp(foo_fwd, foo_bwd)
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(lambda x: foo(x) * x, mesh=mesh,
in_specs=(P('x'),), out_specs=P('x'))
if jit:
g = jax.jit(g)
x = jnp.arange(4.)
y = g(x)
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
y_, x_bar = jax.value_and_grad(lambda x: g(x).sum())(x)
self.assertAllClose(y_, (2 * x * x).sum(), check_dtypes=True)
self.assertAllClose(x_bar, 2 * 2 * x, check_dtypes=True)
@parameterized.parameters([True, False])
def test_rewrite_process_custom_vjp_call_match_more_replicated(self, jit):
@jax.custom_vjp
def foo(x):
return 2. * x
def foo_fwd(x):
return foo(x), None
def foo_bwd(_, y_bar):
return jnp.ones_like(y_bar), # diff! more replicated than primal/tangent
foo.defvjp(foo_fwd, foo_bwd)
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(lambda x: foo(x) * x, mesh=mesh,
in_specs=(P('x'),), out_specs=P('x'))
if jit:
g = jax.jit(g)
x = jnp.arange(4.)
y = g(x)
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
y_, x_bar = jax.value_and_grad(lambda x: g(x).sum())(x)
self.assertAllClose(y_, (2 * x * x).sum(), check_dtypes=True)
self.assertAllClose(x_bar, jnp.ones_like(x) + 2 * x, check_dtypes=True)
def test_same_pspec_eager_shard_map(self):
# This behavior is not guaranteed by JAX and this test can be changed if
# the behavior changes.
mesh = jtu.create_mesh((1, 4, 1), ('data', 'seq', 'model'))
def f(x):
return x * x + 2
x = jnp.ones([2, 16, 4])
x_spec = jax.sharding.PartitionSpec("data", "seq", "model")
x = jax.device_put(x, jax.sharding.NamedSharding(mesh, x_spec))
shard_f = shard_map(f, mesh=mesh, in_specs=x_spec, out_specs=x_spec)
y = shard_f(x)
self.assertEqual(x_spec, y.sharding.spec)
@parameterized.parameters([True, False])
def test_rewrite_custom_vjp_call_jaxpr(self, jit):
@jax.custom_vjp
def foo(x):
return 2. * x
def foo_fwd(x):
return foo(x), None
def foo_bwd(_, y_bar):
return 2. * y_bar,
foo.defvjp(foo_fwd, foo_bwd)
def foo_scan(x):
y, _ = jax.lax.scan(lambda x, _: (foo(x), None), x, None, length=1)
return y
mesh = jtu.create_mesh((4,), ('x',))
g = shard_map(lambda x: foo_scan(x) * x, mesh=mesh,
in_specs=(P('x'),), out_specs=P('x'))
if jit:
g = jax.jit(g)
x = jnp.arange(4.)
y = g(x)
self.assertAllClose(y, 2 * x * x, check_dtypes=True)
y_, x_bar = jax.value_and_grad(lambda x: g(x).sum())(x)
self.assertAllClose(y_, (2 * x * x).sum(), check_dtypes=True)
self.assertAllClose(x_bar, 2 * 2 * x, check_dtypes=True)
def test_transpose_identity(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P(), out_specs=P())
def f(x):
return x
jaxpr = jax.make_jaxpr(jax.vjp(f, 1.)[1])(1.)
e, = jaxpr.jaxpr.eqns
self.assertEmpty(e.params['jaxpr'].eqns)
jaxpr = jax.make_jaxpr(jax.vjp(jax.vjp(f, 1.)[1], 1.)[1])((1.,))
e, = jaxpr.jaxpr.eqns
self.assertEmpty(e.params['jaxpr'].eqns)
@partial(shard_map, mesh=mesh, in_specs=P(), out_specs=P())
def g(x):
return jax.jit(lambda x: 1. * x)(x)
jaxpr = jax.make_jaxpr(jax.vjp(g, 1.)[1])(1.)
e, = jaxpr.jaxpr.eqns
e1, e2 = e.params['jaxpr'].eqns
self.assertEmpty(e1.outvars)
self.assertLen(e2.params['jaxpr'].eqns, 1)
def test_fanout_specs_transpose_to_psum(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P(), out_specs=P('x'))
def f(x):
return x
jaxpr = jax.make_jaxpr(jax.vjp(f, jnp.arange(1.))[1])(jnp.arange(4.))
e, = jaxpr.jaxpr.eqns
e2, = e.params['jaxpr'].eqns
self.assertEqual(str(e2.primitive), 'psum_invariant')
self.assertEqual(e2.params['axes'], ('x',))
def test_fanin_psum_transposes_to_fanout(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P())
def f(x):
return jax.lax.psum(x, 'x')
jaxpr = jax.make_jaxpr(jax.vjp(f, jnp.arange(4.))[1])(jnp.array([1.]))
e, = jaxpr.jaxpr.eqns
e1, = e.params['jaxpr'].eqns
self.assertEqual(str(e1.primitive), 'pvary')
def test_psum_with_implicit_fanout_self_transposes(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return jax.lax.psum(x, 'x')
jaxpr = jax.make_jaxpr(jax.vjp(f, jnp.arange(4.))[1])(jnp.arange(4.))
e, = jaxpr.jaxpr.eqns
e1, e2 = e.params['jaxpr'].eqns
self.assertEqual(str(e1.primitive), 'psum_invariant')
self.assertEqual(str(e2.primitive), 'pvary')
def test_transpose_float0(self):
mesh = jtu.create_mesh((4,), ('x',))
s = jax.sharding.NamedSharding(mesh, P(None, 'x'))
# vjp that triggers float0
@jax.custom_vjp
def f(x, _):
return x
def f_fwd(x, y):
return x, jnp.zeros(shape=y.shape, dtype=np.int32)
def f_rev(tmp, g):
return (g, tmp)
f.defvjp(f_fwd, f_rev)
# trivial vjp that consumes float0
@jax.custom_vjp
def g(x, y):
return x, y
def g_fwd(x, y):
return jax.vjp(lambda x, y: (x, y), x, y)
def g_bwd(vjp_fn, result):
return vjp_fn(result)
g.defvjp(g_fwd, g_bwd)
@partial(shard_map, mesh=mesh, in_specs=(P('x'), P()), out_specs=P())
def f_shmapped(x, y):
return jax.lax.psum(f(x, y).sum(), axis_name=('x'))
@partial(shard_map, mesh=mesh, check_vma=False,
in_specs=P('x'), out_specs=(P('x'), P()))
def f_shmapped2(x, y):
return g(x, y)
def f_wrapper(x, y):
x, y = jax.lax.map(lambda xs: f_shmapped2(xs[0], xs[1]), (x, y))
return jax.lax.map(lambda xs: f_shmapped(xs[0], xs[1]), (x, y)).sum()
@jax.jit(in_shardings=s,
out_shardings=jax.sharding.NamedSharding(mesh, P()))
def example(x, y):
return jax.grad(f_wrapper, allow_int=True, argnums=(0, 1))(x, y)
x = np.zeros(shape=(8,16), dtype=np.float32)
y = np.zeros(shape=(8,16), dtype=np.int32)
# Doesn't crash.
dx, dy = example(x, y)
self.assertEqual(dy.dtype, jax.dtypes.float0)
def test_pvary(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P(), out_specs=P('x'))
def f(x):
y = jax.lax.pvary(x, 'x')
self.assertEqual(y.aval.vma, {'x'})
return y
f(jnp.arange(8.))
jax.grad(lambda x: f(x).sum())(jnp.arange(8.))
def test_rewrite_binops(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=(P(), P('x')), out_specs=P('x'))
def f(x, y):
return x * y
jaxpr = jax.make_jaxpr(f)(jnp.arange(1.), jnp.arange(4.))
e, = jaxpr.jaxpr.eqns
e = e.params['jaxpr'].eqns[0]
self.assertEqual(e.primitive.name, 'pvary')
self.assertEqual(e.params['axes'], ('x',))
def test_rewrite_scan(self):
mesh = jtu.create_mesh((4,), ('x',))
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
def g(x, _):
return lax.pvary(jax.lax.psum(x, 'x'), 'x'), None
x, _ = jax.lax.scan(g, x, None, length=2)
return x
jaxpr = jax.make_jaxpr(f)(jnp.arange(4.))
e, = jaxpr.jaxpr.eqns
e, = e.params['jaxpr'].eqns
e1, e2 = e.params['jaxpr'].eqns
self.assertEqual(e1.primitive.name, 'psum_invariant')
self.assertEqual(e2.primitive.name, 'pvary')
def test_check_rep_false_grads(self):
if jtu.is_device_tpu(5, 'e'):
self.skipTest('TODO(b/307508823): Test currently fails on TPU v5e')
# This test is redundant with the systematic tests below, but it serves as a
# direct regression test for a bug.
mesh = jtu.create_mesh((4,), ('heads',))
def f(q, k, v):
def body(q, k, v):
return q * k[None, :] + v[None, :]
out = shard_map(body, mesh=mesh, check_vma=False,
in_specs=(q_spec, kv_spec, kv_spec,),
out_specs=q_spec)(q, k, v)
return out.sum()
q_spec = P('heads', None)
kv_spec = P(None)
q = jax.device_put(jnp.arange(32.).reshape(4, 8), jax.sharding.NamedSharding(mesh, q_spec))
k = jax.device_put(jnp.arange(8.), jax.sharding.NamedSharding(mesh, kv_spec))
v = jax.device_put(jnp.arange(8.), jax.sharding.NamedSharding(mesh, kv_spec))
if jtu.device_under_test() == 'tpu':
rtol = 2e-2
else:
rtol = 1e-2
jtu.check_grads(f, (q, k, v), order=1, modes=['rev'], rtol=rtol)
def test_axis_env_extension_regression(self):
def foo(x):
i = jax.lax.axis_index('x')
return jnp.exp(x) + i.astype(x.dtype)
@partial(jax.remat, policy=lambda *args, **kwargs: True)
def bar(x):
return shard_map(foo, mesh=Mesh(jax.devices(), ['x']), in_specs=(P('x'),),
out_specs=P('x'), check_vma=False)(x)
jax.jit(jax.grad(lambda x: bar(x).sum()))(jnp.arange(8.)) # doesn't crash
@parameterized.parameters(it.product([True, False], repeat=2))
def test_res_forwarding_optimization(self, jit, remat):
mesh = jtu.create_mesh((4,), ('i',))
@shard_map(mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
return jax.lax.exp(x)
if jit:
f = jax.jit(f)
if remat:
policy = jax.ad_checkpoint.checkpoint_policies.everything_saveable
f = jax.remat(f, policy=policy)
g = lambda x: f(x).sum()
x = jnp.arange(16.)
jaxpr_ = jax.make_jaxpr(jax.grad(g))(x)
jaxpr, _ = pe.dce_jaxpr(jaxpr_.jaxpr, [True] * len(jaxpr_.out_avals))
e1, *_, e2 = jaxpr.eqns
self.assertLen(e1.outvars, 1) # only primal output
self.assertLen(e2.invars, 2) # res and cotangent inputs
self.assertEqual(sum(e1.outvars[0] is v for v in e2.invars), 1)
@parameterized.parameters(it.product([True, False], repeat=2))
def test_res_forwarding_optimization_complex(self, jit, remat):
# like the above test, but a different function `f`
mesh = jtu.create_mesh((4,), ('i',))
@shard_map(mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
return jax.lax.exp(x.sum()) + x, jax.lax.exp(x)
if jit:
f = jax.jit(f)
if remat:
policy = jax.ad_checkpoint.checkpoint_policies.everything_saveable
f = jax.remat(f, policy=policy)
g = lambda x: sum(f(x)).sum()
x = jnp.arange(16.)
jaxpr_ = jax.make_jaxpr(jax.grad(g))(x)
jaxpr, _ = pe.dce_jaxpr(jaxpr_.jaxpr, [True] * len(jaxpr_.out_avals))
e1, *_, e2 = jaxpr.eqns
self.assertLen(e1.outvars, 2) # one primal and one res output
self.assertLen(e2.invars, 4) # two res and two cotangent inputs
self.assertEqual(sum(e1.outvars[-1] is v for v in e2.invars), 1)
@parameterized.parameters([True, False])
def test_check_rep_failure_inside_rule(self, jit):
mesh = jtu.create_mesh((4,), ('i',))
def loss(w, x):
@shard_map(mesh=mesh, in_specs=P('i'), out_specs=P())
def f(x):
return jax.lax.psum(((w * x) ** 2).sum(), 'i')
return f(x)
if jit:
loss = jax.jit(loss)
jax.grad(loss)(3.0, jnp.arange(8.)) # don't crash
def test_conv_general_dilated(self):
mesh = jtu.create_mesh((4,), ('i',))
dot = partial(lax.conv_general_dilated, window_strides=(),
padding='VALID', dimension_numbers=('NC', 'IO', 'NC'))
@shard_map(mesh=mesh, in_specs=(P(None, 'i'), P('i', None)),
out_specs=P(None, None))
def f(x, y):
return lax.psum(dot(x, y), 'i')
a = jnp.ones((16, 32))
b = jnp.ones((32, 8))
y = f(a, b) # don't crash
self.assertAllClose(y, a @ b, check_dtypes=False, atol=1e-2, rtol=1e-2)
def test_cumsum(self):
mesh = jtu.create_mesh((4,), ('i',))
x = jnp.arange(8.)
shard_map(jnp.cumsum, mesh=mesh, in_specs=P('i'), out_specs=P('i')
)(x) # don't crash
def test_custom_jvp_inside_jit(self):
mesh = jtu.create_mesh((4,), ('batch',))
x = shard_map(jax.jit(jax.nn.relu),
mesh=mesh, in_specs=P('batch'),
out_specs=P('batch'))(jnp.arange(16.)) # don't crash
def test_random_normal_rules(self):
mesh = jtu.create_mesh((4,), ('i',))
keys = jax.random.split(jax.random.key(0), 4)
shard_map(lambda k: jax.random.normal(k[0], (1,)),
mesh=mesh, in_specs=P('i'), out_specs=P('i'))(keys) # don't crash
def test_erf_rules(self):
mesh = jtu.create_mesh((4,), ('i',))
x = jnp.arange(16.)
shard_map(jax.lax.erf,
mesh=mesh, in_specs=P('i'), out_specs=P('i'))(x) # don't crash
def test_error_for_variable_num_args(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
def f(*args):
return args[0] @ args[1]
shard_f = shard_map(
f, mesh=mesh, in_specs=(P('x', 'y', None), P('x', 'y', None)), out_specs=P('x', 'y'))
with self.assertRaisesRegex(ValueError, "shard_map applied to the function 'f'"):
shard_f(jnp.ones((8, 8)), jnp.ones((8, 8)))
def test_custom_vjp_replication_error_message_hint(self):
mesh = jtu.create_mesh((4,), 'i')
@jax.custom_vjp
def f(x):
return jax.lax.psum(x, 'i')
def f_fwd(x):
return f(x), None
def f_bwd(_, g):
return jax.lax.psum(g, 'i'),
f.defvjp(f_fwd, f_bwd)
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P())
def g(x):
return f(f(x))
y, grad = jax.value_and_grad(lambda x: g(x).sum())(jnp.ones(4))
# first psum sums, second psum multiplies by 4
self.assertAllClose(y, (jnp.ones(4) * 4).sum(), check_dtypes=False)
# two psums on the backward pass, each one multiplies by 4
self.assertAllClose(grad, jnp.ones(4) * 4 * 4, check_dtypes=False)
def test_repeated_psum_allowed(self):
# https://github.com/jax-ml/jax/issues/19175
mesh = jtu.create_mesh((4,), 'i')
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P())
def g(x):
return jax.lax.psum(jax.lax.psum(x, 'i'), 'i')
y = g(jnp.arange(4.))
self.assertAllClose(y, jnp.arange(4.).sum(keepdims=True) * 4,
check_dtypes=False)
def test_approx_top_k(self):
mesh = Mesh(np.array(jax.devices()[:2]), ('i',))
x = jnp.array([3.0, 1.0, 4.0, 2.0])
_ = shard_map(lambda x: lax.approx_max_k(x, 2), mesh=mesh, in_specs=P('i'),
out_specs=P('i'))(x)
def test_disable_jit(self):
mesh = Mesh(np.array(jax.devices()[:2]), ('i',))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
return x
x = jnp.arange(8.)
with jax.disable_jit():
f(x) # don't crash
@jtu.with_explicit_mesh((2,), 'x')
def test_jacrev_explicit(self, mesh):
B, N, H = 20, 6, 8
w = jnp.arange(N * H).reshape(N, H).astype(jnp.float32)
x = jnp.arange(B * N).reshape(B, N).astype(jnp.float32)
def f(w, x):
return jnp.sum(x @ w, axis=-1)
@jax.jit
@shard_map(in_specs=(P(), P('x', None)), out_specs=P('x', None))
def f_jac_sharded(w, x):
return jax.jacrev(f, argnums=1)(w, x)
f_jac_sharded(w, x) # doesn't crash
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_jacrev_explicit_complex(self, mesh):
B, N, H = 20, 6, 8
w = jnp.arange(N * H).reshape(N, H).astype(jnp.float32)
x = jnp.arange(B * N).reshape(B, N).astype(jnp.float32)
def f(w, xs):
return jax.tree.map(lambda z: jnp.sum(z @ w, axis=-1), xs)
@jax.jit
@shard_map(in_specs=(P(), P('x'), P('y')),
out_specs=(P('x'), P('y'), P('x'), P('y')))
def f_jac_sharded(w, x, y):
ret = jax.jacrev(f, argnums=1)(w, (x, y))
self.assertEqual(ret[0][0].aval.vma, {'x'})
self.assertEqual(ret[0][1].aval.vma, {'y'})
self.assertEqual(ret[1][0].aval.vma, {'x'})
self.assertEqual(ret[1][1].aval.vma, {'y'})
return ret[0][0], ret[0][1], ret[1][0], ret[1][1]
f_jac_sharded(w, x, x) # doesn't crash
@jtu.with_explicit_mesh((2,), 'x')
def test_random_choice_pvary(self, mesh):
B, C = 8, 3
key = jax.random.key(0)
keys = jax.random.split(key, B)
hoppable_clusters = jax.random.randint(key, (B, C), minval=0, maxval=2) == 1
@jax.vmap
def _update_samples(key, hoppable_clusters):
return jax.random.choice(key, a=jnp.arange(C), p=hoppable_clusters,
replace=True)
shard_map(_update_samples, in_specs=(P('x'), P('x')),
out_specs=P('x'))(keys, hoppable_clusters) # doesn't crash
@parameterized.parameters(it.product(range(4), repeat=3))
@jtu.run_on_devices("cpu")
def test_forwarding_correctness(self, seed, num_input_fwd, num_output_fwd):
num_args = 3
rng = np.random.RandomState(seed)
mesh = Mesh(np.array(jax.devices()[:1]), ('i',))
in_perm = rng.permutation(num_args)
out_perm = rng.permutation(num_args)
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(inputs):
inputs = [inputs[i] for i in in_perm]
outputs = inputs[:num_input_fwd] + [
jnp.exp(inputs[i]) if i < num_output_fwd else jnp.sin(inputs[i])
for i in range(num_args - num_input_fwd)]
return [outputs[i] for i in out_perm]
jtu.check_grads(f, (list(jnp.arange(float(num_args))[:,None]),), order=1,
modes=['rev'], atol=1e-3, rtol=1e-3)
@jtu.with_explicit_mesh((2, 2), ('data', 'seq'))
def test_shmap_unreduced_fsdp_custom_vjp_bwd(self, mesh):
np_inp1 = np.arange(64.).reshape(8, 4, 2)
np_inp2 = np.arange(12.).reshape(2, 6)
arr1 = jax.device_put(np_inp1, P('data', 'seq', None))
arr2 = jax.device_put(np_inp2, P('seq', None))
@jax.custom_vjp
def f(x, y):
@shard_map(in_specs=P('seq', None),
out_specs=P(None, None, reduced={'seq'}))
def ag(a):
self.assertEqual(a.aval.vma, {'seq'})
self.assertEqual(a.aval.sharding.spec.unreduced, frozenset())
out = lax.all_gather_reduced(a, axis_name='seq', tiled=True)
self.assertEqual(out.aval.vma, frozenset())
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(out.aval.sharding.spec.reduced, {'seq'})
return out
y2 = ag(y)
return jnp.einsum('btd,df->btf', x, y2)
def f_fwd(x, y):
return f(x, y), (x, y)
def f_bwd(res, g):
x, y = res
@shard_map(in_specs=P(unreduced={'data', 'seq'}),
out_specs=P('seq', None, unreduced={'data'}))
def rs(a):
self.assertEqual(a.aval.vma, frozenset())
self.assertEqual(a.aval.sharding.spec.unreduced, {'data', 'seq'})
out = lax.unreduced_psum_scatter(a, axis_name='seq', tiled=True)
self.assertEqual(out.aval.vma, {'seq'})
self.assertEqual(out.aval.sharding.spec.unreduced, {'data'})
return out
@shard_map(in_specs=P('seq', None, unreduced={'data'}),
out_specs=P('seq', None))
def ar(a):
self.assertEqual(a.aval.vma, {'seq'})
self.assertEqual(a.aval.sharding.spec.unreduced, {'data'})
out = lax.unreduced_psum(a, axis_name='data')
self.assertEqual(out.aval.vma, {'seq'})
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
return out
x_bar = jnp.einsum('btf,df->btd', g, y, out_sharding=P('data', 'seq', None))
y_bar_ = jnp.einsum('btd,btf->df', x, g,
out_sharding=P(None, None, unreduced={'data', 'seq'}))
self.assertEqual(y_bar_.aval.sharding.spec.unreduced, {'data', 'seq'})
y_bar = rs(y_bar_)
self.assertEqual(y_bar.aval.sharding.spec.unreduced, {'data'})
y_bar = ar(y_bar)
self.assertEqual(y_bar.aval.sharding.spec.unreduced, frozenset())
return (x_bar, y_bar)
f.defvjp(f_fwd, f_bwd)
f = jax.jit(f)
f(arr1, arr2) # doesn't crash
out1, out2 = jax.jit(jax.grad(lambda x, y: jnp.sin(f(x, y).sum()),
argnums=(0, 1)))(arr1, arr2)
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: jnp.sin((x @ y).sum()),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
@jtu.with_explicit_mesh((2, 2), ('data', 'seq'))
def test_shmap_unreduced_fsdp_grad(self, mesh):
np_inp1 = np.arange(64.).reshape(8, 4, 2)
np_inp2 = np.arange(12.).reshape(2, 6)
arr1 = jax.device_put(np_inp1, P('data', 'seq', None))
arr2 = jax.device_put(np_inp2, P('seq', None))
@shard_map(in_specs=P('seq', None),
out_specs=P('seq', None, reduced={'data'}))
def preduced(a):
self.assertEqual(a.aval.vma, {'seq'})
self.assertEqual(a.aval.sharding.spec.unreduced, frozenset())
out = lax.preduced(a, axis_name='data')
self.assertEqual(out.aval.vma, {'seq'})
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(out.aval.sharding.spec.reduced, {'data'})
return out
@shard_map(in_specs=P('seq', None, reduced={'data'}),
out_specs=P(None, None, reduced={'seq', 'data'}))
def ag(a):
self.assertEqual(a.aval.vma, {'seq'})
self.assertEqual(a.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(a.aval.sharding.spec.reduced, {'data'})
out = lax.all_gather_reduced(a, axis_name='seq', tiled=True)
self.assertEqual(out.aval.vma, frozenset())
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(out.aval.sharding.spec.reduced, {'seq', 'data'})
return out
@jax.jit
def f(x, y):
y2 = preduced(y)
y3 = ag(y2)
self.assertEqual(y3.aval.sharding.spec.reduced, {'seq', 'data'})
return jnp.einsum('btd,df->btf', x, y3)
out = f(arr1, arr2) # doesn't crash
self.assertEqual(out.sharding, NamedSharding(mesh, P('data', 'seq', None)))
out1, out2 = jax.jit(jax.grad(lambda x, y: jnp.sin(f(x, y).sum()),
argnums=(0, 1)))(arr1, arr2)
jaxpr = jax.jit(jax.grad(lambda x, y: jnp.sin(f(x, y).sum()),
argnums=(0, 1))).trace(arr1, arr2).jaxpr
self.assertIn('unreduced_reduce_scatter', str(jaxpr))
self.assertIn('unreduced_psum', str(jaxpr))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: jnp.sin((x @ y).sum()),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('data', 'seq', None)))
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
self.assertEqual(out2.sharding, NamedSharding(mesh, P('seq', None)))
@jtu.with_explicit_mesh((2,), 'x')
def test_unreduced_psum_fwd_preduced_bwd(self, mesh):
np_inp1 = np.arange(8.).reshape(2, 4)
np_inp2 = np.arange(24.).reshape(4, 6)
arr1 = jax.device_put(np_inp1, P(None, 'x'))
arr2 = jax.device_put(np_inp2, P('x', None))
@shard_map(in_specs=P(unreduced={'x'}), out_specs=P())
def ar(x):
self.assertEqual(x.aval.vma, frozenset())
self.assertEqual(x.aval.sharding.spec.unreduced, {'x'})
out = jax.lax.unreduced_psum(x, 'x')
self.assertEqual(out.aval.vma, frozenset())
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
return out
@jax.jit
def f(x, y):
z = jnp.einsum('ab,bc->ac', x, y, out_sharding=P(unreduced={'x'}))
return ar(z).sum()
out = f(arr1, arr2)
self.assertArraysEqual(out, np.sum(np_inp1 @ np_inp2))
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
out1, out2 = jax.jit(jax.grad(f, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P(None, 'x')))
self.assertEqual(out2.sharding, NamedSharding(mesh, P('x', None)))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: (x @ y).sum(),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
@jtu.with_explicit_mesh((2,), 'x')
def test_preduced_fwd_unreduced_psum_bwd(self, mesh):
np_inp1 = np.arange(8.).reshape(2, 4)
np_inp2 = np.arange(24.).reshape(4, 6)
arr1 = jax.device_put(np_inp1, P(None, None))
arr2 = jax.device_put(np_inp2, P(None, 'x'))
@shard_map(in_specs=P(), out_specs=P(reduced={'x'}))
def pr(x):
self.assertEqual(x.aval.vma, frozenset())
self.assertEqual(x.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(x.aval.sharding.spec.reduced, frozenset())
out = jax.lax.preduced(x, 'x')
self.assertEqual(out.aval.vma, frozenset())
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(out.aval.sharding.spec.reduced, {'x'})
return out
@jax.jit
def f(x, y):
x = pr(x)
z = jnp.einsum('ab,bc->ac', x, y)
return z.sum()
out = f(arr1, arr2)
self.assertArraysEqual(out, np.sum(np_inp1 @ np_inp2))
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
out = jax.jit(jax.grad(f))(arr1, arr2)
self.assertEqual(out.sharding, NamedSharding(mesh, P(None, None)))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out = jax.jit(jax.grad(lambda x, y: (x @ y).sum()))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out, out, rtol=2e-4)
@jtu.with_explicit_mesh((2, 2), ('data', 'seq'))
def test_all_gather_reduced_fwd_unreduced_psum_scatter_bwd(self, mesh):
np_inp1 = np.arange(8.).reshape(4, 2)
np_inp2 = np.arange(12.).reshape(2, 6)
arr1 = jax.device_put(np_inp1, P('seq', None))
arr2 = jax.device_put(np_inp2, P('seq', None))
@shard_map(in_specs=P('seq', None), out_specs=P(None, None, reduced={'seq'}))
def ag(a):
self.assertEqual(a.aval.vma, {'seq'})
self.assertEqual(a.aval.sharding.spec.unreduced, frozenset())
out = lax.all_gather_reduced(a, axis_name='seq', tiled=True)
self.assertEqual(out.aval.vma, frozenset())
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
self.assertEqual(out.aval.sharding.spec.reduced, {'seq'})
return out
@jax.jit
def f(x, y):
y2 = ag(y)
z = jnp.einsum('td,df->tf', x, y2)
return z.sum()
out = f(arr1, arr2)
self.assertArraysEqual(out, np.sum(np_inp1 @ np_inp2))
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
out1, out2 = jax.jit(jax.grad(f, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('seq', None)))
self.assertEqual(out2.sharding, NamedSharding(mesh, P('seq', None)))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: (x @ y).sum(),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
@jtu.with_explicit_mesh((2,), ('x',))
def test_unreduced_psum_scatter_fwd_all_gather_reduced_bwd(self, mesh):
np_inp1 = np.arange(8.).reshape(4, 2)
np_inp2 = np.arange(12.).reshape(2, 6)
arr1 = jax.device_put(np_inp1, P(None, 'x'))
arr2 = jax.device_put(np_inp2, P('x', None))
@shard_map(in_specs=P(unreduced={'x'}), out_specs=P('x', None))
def rs(a):
self.assertEqual(a.aval.vma, frozenset())
self.assertEqual(a.aval.sharding.spec.unreduced, {'x'})
out = lax.unreduced_psum_scatter(a, axis_name='x', tiled=True)
self.assertEqual(out.aval.vma, {'x'})
self.assertEqual(out.aval.sharding.spec.unreduced, frozenset())
return out
@jax.jit
def f(x, y):
z = jnp.einsum('ab,bc->ac', x, y, out_sharding=P(unreduced={'x'}))
return rs(z).sum()
out = f(arr1, arr2)
self.assertArraysEqual(out, np.sum(np_inp1 @ np_inp2))
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
out1, out2 = jax.jit(jax.grad(f, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P(None, 'x')))
self.assertEqual(out2.sharding, NamedSharding(mesh, P('x', None)))
with jax.set_mesh(jtu.create_mesh((1,), 'x')):
ex_out1, ex_out2 = jax.jit(jax.grad(lambda x, y: (x @ y).sum(),
argnums=(0, 1)))(np_inp1, np_inp2)
self.assertArraysAllClose(ex_out1, out1, rtol=2e-4)
self.assertArraysAllClose(ex_out2, out2, rtol=2e-4)
@jtu.with_explicit_mesh((2,), 'x')
def test_sin_unreduced_error(self, mesh):
np_inp1 = np.arange(8.).reshape(4, 2)
np_inp2 = np.arange(12.).reshape(2, 6)
arr1 = jax.device_put(np_inp1, P(None, 'x'))
arr2 = jax.device_put(np_inp2, P('x', None))
@jax.jit
def f(x, y):
z = jnp.einsum('ab,bc->ac', x, y, out_sharding=P(unreduced={'x'}))
return shard_map(lambda x: jnp.sin(x), out_specs=P())(z)
with self.assertRaisesRegex(NotImplementedError, "unreduced rule for sin"):
f(arr1, arr2)
@jtu.with_explicit_mesh((2,), 'x')
def test_eval_shape_vma(self, mesh):
k1, k2 = jax.random.split(jax.random.key(123))
p = jax.random.uniform(k1, shape=5, out_sharding=P())
x = jax.random.uniform(k2, shape=(1024, 5), out_sharding=P('x'))
def f(p, x):
return jnp.einsum('i, i->', x, p)
@shard_map(in_specs=(P(), P('x')), out_specs=P('x'))
def g(p, x):
def _grad(f, p, x):
_, vjp_fun = jax.vjp(f, p, x)
y_eval_shape = jax.eval_shape(f, p, x)
self.assertEqual(core.typeof(y_eval_shape).vma, frozenset('x'))
one = jax.lax.full_like(y_eval_shape, 1)
self.assertEqual(core.typeof(one).vma, frozenset('x'))
return vjp_fun(one)
return jax.lax.map(partial(_grad, f, p), x)
g(p, x) # doesn't crash
jax.jit(g)(p, x) # doesn't crash
def test_psum_not_under_shmap_error(self):
mesh = jtu.create_mesh((2,), 'x')
@jax.jit
def f(x):
return jax.lax.psum(x, 'x')
with self.assertRaisesRegex(
NameError,
'Found an unbound axis name: x. To fix this, please call psum under'
' `jax.shard_map`'):
f(jnp.arange(8.))
# fixes the above error
shard_map(f, mesh=mesh, in_specs=P('x'), out_specs=P()) # doesn't crash
def test_shmap_auto_unreduced_error(self):
mesh = jtu.create_mesh((2, 1), ('x', 'y'))
with self.assertRaisesRegex(
ValueError,
'unreduced.*can only be used when the mesh passed to shard_map contains'
' axis names all of type `Explicit`'):
shard_map(lambda x: x, mesh=mesh, in_specs=P(unreduced={'x'}),
out_specs=P())(np.arange(8))
with self.assertRaisesRegex(
NotImplementedError,
'unreduced.*can only be passed to in_specs when shard_map is in full'
' manual mode'):
shard_map(lambda x: x, mesh=mesh, in_specs=P(unreduced={'x'}),
out_specs=P(), axis_names={'x'})(np.arange(8))
def test_partial_auto(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
self.assertTupleEqual(x.aval.sharding.mesh.axis_types,
(AxisType.Manual, AxisType.Auto))
x = jax.lax.with_sharding_constraint(x, P(None, 'j'))
return x * x
@jax.jit
def f(x):
x = shard_map(g, mesh=mesh,
in_specs=P('i', None),
out_specs=P('i', None),
axis_names=frozenset({'i'}))(x)
return jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
if config.use_shardy_partitioner.value:
self.assertIn(
'in_shardings=[<@mesh, [{"i", ?}, {?}]>]'
' out_shardings=[<@mesh, [{"i", ?}, {?}]>] manual_axes={"i"}',
f.lower(v).as_text(),
)
else:
self.assertIn(
'sharding={devices=[1,1,2,2]<=[4] last_tile_dims={manual,'
' replicated}}',
f.lower(v).as_text('hlo'),
)
self.assertAllClose(v * v, f(v), check_dtypes=False)
def test_partial_auto_explicit_no_set_mesh(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'),
axis_types=(AxisType.Explicit,) * 2)
def g(x):
self.assertTupleEqual(x.aval.sharding.mesh.axis_types,
(AxisType.Manual, AxisType.Explicit))
self.assertEqual(x.aval.sharding.spec, P(None, 'j'))
out = x * x
self.assertEqual(out.aval.sharding.spec, P(None, 'j'))
return out
@jax.jit
def f(x):
x = shard_map(g, mesh=mesh,
in_specs=P('i', None),
out_specs=P('i', None),
axis_names=frozenset({'i'}))(x)
self.assertEqual(x.aval.sharding.spec, P('i', 'j'))
return x
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
out = f(v)
self.assertEqual(out.sharding, NamedSharding(mesh, P('i', 'j')))
self.assertAllClose(v * v, out, check_dtypes=False)
@jtu.with_explicit_mesh((2, 2), ('i', 'j'))
def test_partial_auto_explicit(self, mesh):
def g(x):
self.assertTupleEqual(x.aval.sharding.mesh.axis_types,
(AxisType.Manual, AxisType.Explicit))
self.assertEqual(x.aval.sharding.spec, P(None, 'j'))
out = x * x
self.assertEqual(out.aval.sharding.spec, P(None, 'j'))
return out
@jax.jit
def f(x):
x = jax.shard_map(g, out_specs=P('i', None), axis_names=frozenset({'i'}))(x)
self.assertEqual(x.aval.sharding.spec, P('i', 'j'))
return x
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
out = f(v)
self.assertEqual(out.sharding, NamedSharding(mesh, P('i', 'j')))
self.assertAllClose(v * v, out, check_dtypes=False)
if config.use_shardy_partitioner.value:
self.assertIn(
'sdy.sharding_constraint %1 <@mesh, [{}, {"j"}]>',
f.lower(v).as_text(),
)
else:
self.assertIn(
'mhlo.sharding = "{devices=[1,2,2]<=[2,2]T(1,0) last_tile_dims={manual}}"}',
f.lower(v).as_text(),
)
@jax.jit
def h(x):
return jnp.sum(f(x))
jax.grad(h)(v) # doesn't crash
jax.jit(jax.grad(h))(v) # doesn't crash
@jtu.with_explicit_mesh((2, 1, 2, 2), ('i', 'j', 'k', 'l'))
def test_partial_auto_explicit_multi_explicit(self, mesh):
def g(x):
self.assertTupleEqual(x.aval.sharding.mesh.axis_types,
(AxisType.Manual, AxisType.Manual,
AxisType.Explicit, AxisType.Explicit))
self.assertEqual(x.aval.sharding.spec, P(None, None, 'k', 'l'))
out = x.T
self.assertEqual(out.aval.sharding.spec, P('l', 'k', None, None))
return out
@jax.jit
def f(x):
x = jax.shard_map(g, out_specs=P('i', 'j', None, None),
axis_names=frozenset({'i', 'j'}))(x)
self.assertEqual(x.aval.sharding.spec, P(('i', 'l'), ('j', 'k'), None, None))
return x
v = jnp.arange(64.).reshape(4, 2, 2, 4)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j', 'k', 'l')))
out = f(v)
self.assertEqual(
out.sharding, NamedSharding(mesh, P(('i', 'l'), ('j', 'k'), None, None)))
def test_partial_auto_propagate_through(self):
mesh = jtu.create_mesh((2, 2, 2), ('i', 'j', 'k'))
sharding = jax.sharding.NamedSharding(mesh, P('i'))
def g(x):
return jax.lax.with_sharding_constraint(x * x, sharding)
@jax.jit
def f(x):
return shard_map(
g,
mesh=mesh,
in_specs=P(),
out_specs=P(),
check_vma=False,
axis_names=frozenset({'j', 'k'}),
)(x)
v = jnp.arange(32.0).reshape(4, 8)
v = jax.device_put(v, sharding)
if config.use_shardy_partitioner.value:
self.assertIn(
'in_shardings=[<@mesh, [{?}, {?}]>]'
' out_shardings=[<@mesh, [{?}, {?}]>] manual_axes={"j", "k"}',
f.lower(v).as_text(),
)
else:
self.assertIn(
'sharding={devices=[1,1,4,2]<=[2,4]T(1,0) last_tile_dims={manual,'
' replicated}}',
f.lower(v).as_text('hlo'),
)
actual = f(v)
self.assertAllClose(v * v, actual, check_dtypes=False)
self.assertEqual(actual.sharding, sharding)
def test_shmap_close_over_unused_params(self):
mesh = jtu.create_mesh((2,), ("data",))
def loss_fn(_, batch):
return jnp.sum(batch)
@jax.jit
def update_fn(params, batch):
def grad_fn(batch):
return jax.value_and_grad(loss_fn)(params, batch)
return shard_map(grad_fn, mesh=mesh, in_specs=P("data"), out_specs=P(),
check_vma=False)(batch)
arr_sharded = jax.device_put(jnp.arange(32.0).reshape(4, 8),
NamedSharding(mesh, P()))
params = jnp.copy(arr_sharded)
update_fn(params, arr_sharded) # doesn't crash
@jtu.with_explicit_mesh((2,), ('x',))
def test_close_over_explicit_sharded_input_error(self, mesh):
def simple_func(w, x):
return jnp.sum(w * x, axis=-1)
w = jnp.ones((2, 4), dtype=np.float32)
x = jnp.ones((4, 4), dtype=np.float32)
shard_map(simple_func, in_specs=(P(), P('x')), out_specs=P('x'))(w, x)
with self.assertRaisesRegex(
NotImplementedError,
'Closing over inputs to shard_map where the input is sharded on'
' `Explicit` axes is not implemented'):
shard_map(lambda xi: simple_func(w, xi),
in_specs=P('x'), out_specs=P('x'))(x)
def test_close_over_input_explict_ctx_mesh(self):
mesh = jtu.create_mesh((2,), 'x', axis_types=(AxisType.Explicit,))
w = jnp.ones((2, 4), dtype=np.float32)
x = jnp.ones((4, 4), dtype=np.float32)
def simple_func(w, x):
return jnp.sum(w * x, axis=-1)
shard_map(simple_func, mesh=mesh, in_specs=(P(), P('x')),
out_specs=P('x'))(w, x)
shard_map(lambda xi: simple_func(w, xi), mesh=mesh,
in_specs=P('x'), out_specs=P('x'))(x)
def test_shmap_close_over_unused_params_vmap(self):
mesh = jtu.create_mesh((2,), ("data",))
def loss_fn(params, batch):
return jnp.sum(params) + jnp.sum(batch)
@jax.jit
def update_fn(params, batch):
def grad_fn(batch):
return jax.value_and_grad(loss_fn)(params, batch)
return shard_map(jax.vmap(grad_fn), mesh=mesh, in_specs=P("data"),
out_specs=P("data"), check_vma=False)(batch)
arr_sharded = jax.device_put(jnp.arange(32.0).reshape(4, 8),
NamedSharding(mesh, P()))
params = jnp.copy(arr_sharded)
update_fn(params, arr_sharded) # doesn't crash
def test_sharded_prng_with_abstract_mesh(self):
shape = (8, 2, 2)
mesh = jtu.create_mesh((2, 2, 2), ('x', 'y', 'z'))
np_inp = np.arange(math.prod(shape), dtype=np.uint32).reshape(shape)
key = prng.random_seed(np_inp, impl=prng.threefry_prng_impl)
key = jax.device_put(key, NamedSharding(mesh, P()))
@jax.jit
def shard_key(key):
return shard_map(
lambda x: x, mesh=mesh.abstract_mesh, in_specs=P(), out_specs=P())(key)
out = shard_key(key)
self.assertTrue(out.sharding.is_equivalent_to(NamedSharding(mesh, P()),
out.ndim))
def test_partial_auto_error_wsc_manual(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
x = jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
return x * x
@jax.jit
def f(x):
x = shard_map(g, mesh=mesh,
in_specs=P('i', None),
out_specs=P('i', None),
check_vma=False,
axis_names=frozenset({'i'}))(x)
return jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
with self.assertRaisesRegex(ValueError, "manual"):
f(v)
def test_partial_auto_error_invalid_auto(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
x = jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
return x * x
@jax.jit
def f(x):
x = shard_map(g, mesh=mesh,
in_specs=P('i', None),
out_specs=P('i', None),
check_vma=False,
axis_names=frozenset({'i', 'j'}))(x)
return jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
with self.assertRaisesRegex(ValueError, "contains a manual axes.*of mesh"):
f(v)
def test_partial_auto_error_wrong_in_specs(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
x = jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
return x * x
@jax.jit
def f(x):
x = shard_map(g, mesh=mesh,
in_specs=P('i', 'j'),
out_specs=P('i', None),
check_vma=False,
axis_names=frozenset({'i'}))(x)
return jax.lax.with_sharding_constraint(
x, jax.sharding.NamedSharding(mesh, P('i', 'j')))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
with self.assertRaisesRegex(ValueError, "in_specs refers to 'j'"):
f(v)
def test_partial_auto_mismatch_mesh_error(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
def g(x):
return x * x
def h(x):
return shard_map(g, mesh=mesh, in_specs=P(None, 'j'),
out_specs=P(None, 'j'))(x)
@jax.jit
def f(x):
return shard_map(h, mesh=mesh, in_specs=P('i', None),
out_specs=P('i', None), check_vma=False,
axis_names=frozenset({'i'}))(x)
with self.assertRaisesRegex(
ValueError, r"context mesh.*should match the mesh passed to shard_map"):
self.assertAllClose(v*v, f(v), check_dtypes=False)
def test_nested_partial_auto(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
def g(x):
return x * x
def h(x):
return shard_map(g, in_specs=P(None, 'j'), out_specs=P(None, 'j'))(x)
@jax.jit
def f(x):
return shard_map(h, in_specs=P('i', None), out_specs=P('i', None),
check_vma=False, axis_names=frozenset({'i'}))(x)
with jax.set_mesh(mesh):
self.assertAllClose(v*v, f(v), check_dtypes=False)
@parameterized.named_parameters(
('0', 'x', 'y', {'x'}, {'x', 'y'}),
('1', None, 'y', frozenset(), {'y'}),
('2', 'x', None, {'x'}, {'x'}),
('3', None, None, frozenset(), frozenset()),
)
def test_nested_partial_auto_1d(self, dim1, dim2, outer_vma, inner_vma):
mesh = jtu.create_mesh((2, 2, 2), ('x', 'y', 'z'))
np_inp = np.arange(32.).reshape(4, 8)
arr = jax.device_put(np_inp, NamedSharding(mesh, P(dim1, dim2)))
def g(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x', 'y'))
self.assertEqual(get_abstract_mesh().auto_axes, ('z',))
self.assertEqual(x.aval.vma, inner_vma)
out = x * x
self.assertEqual(out.aval.vma, inner_vma)
return out
def h(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x',))
self.assertEqual(get_abstract_mesh().auto_axes, ('y', 'z'))
self.assertEqual(x.aval.vma, outer_vma)
out = shard_map(g, in_specs=P(None, dim2),
out_specs=P(None, dim2), axis_names={'y'})(x)
self.assertEqual(out.aval.vma, outer_vma)
return out
@jax.jit
def f(x):
return shard_map(h, in_specs=P(dim1, None),
out_specs=P(dim1, None), axis_names={'x'})(x)
with jax.set_mesh(mesh):
out = f(arr)
self.assertArraysEqual(out, np_inp * np_inp)
def test_grad_nested_partial_auto(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
# manual: 'i', 'j'
return x * x
def h(x):
# auto: 'j', manual: 'i'
return shard_map(g, in_specs=P(None, 'j'), out_specs=P(None, 'j'))(x)
@jax.jit
def f(x):
# auto: 'i', 'j'
return shard_map(h, in_specs=P('i', None), out_specs=P('i', None),
check_vma=False, axis_names=frozenset({'i'}))(x).sum()
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
with jax.set_mesh(mesh):
out = jax.grad(f)(v)
self.assertAllClose(out, v * 2, check_dtypes=False)
def test_grad_nested_partial_auto_with_residuals(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def g(x):
return x * x * x
def h(x):
return shard_map(g, in_specs=P(None, 'j'), out_specs=P(None, 'j'))(x)
@jax.jit
def f(x):
return shard_map(h, in_specs=P('i', None), out_specs=P('i', None),
check_vma=False, axis_names=frozenset({'i'}))(x).sum()
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
with jax.set_mesh(mesh):
out = jax.grad(f)(v)
self.assertAllClose(out, v * v * 3, check_dtypes=False)
def test_axis_size_1_partial_auto(self):
mesh = jtu.create_mesh((1, 2, 2), ('i', 'j', 'k'))
def h(x):
return x * x
@jax.jit
def f(x):
return shard_map(h, mesh=mesh,
in_specs=P('i', None),
out_specs=P('i', None),
check_vma=False,
axis_names=frozenset({'i'}))(x)
v = jnp.arange(32.).reshape(4, 8)
v = jax.device_put(v, jax.sharding.NamedSharding(mesh, P('i', 'j')))
self.assertAllClose(v*v, f(v), check_dtypes=False)
def test_partial_auto_of_pjit(self):
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
def h():
def _make_zeros():
return jnp.zeros(())
s = jax.sharding.NamedSharding(mesh, P())
y = jax.jit(_make_zeros, out_shardings=s)()
return y.reshape((1,))
def f():
return shard_map(
h, mesh=mesh, in_specs=(),
out_specs=P('i'), check_vma=False, axis_names=frozenset({'i'}))()
self.assertAllClose(jax.jit(f)(), jnp.zeros((2,)))
def test_partial_auto_of_pjit_different_mesh(self):
if config.use_shardy_partitioner.value:
self.skipTest(
'Shardy requires the mesh axis names to be the same across '
'the entire computation.'
)
mesh = jtu.create_mesh((2, 2), ('i', 'j'))
mesh2 = jax.sharding.Mesh(mesh.devices, ('k', 'l'))
def h():
def _make_zeros():
return jnp.zeros(())
s = jax.sharding.NamedSharding(mesh2, P())
y = jax.jit(_make_zeros, out_shardings=s)()
return y.reshape((1,))
def f():
return shard_map(
h, mesh=mesh, in_specs=(),
out_specs=P('i'), check_vma=False, axis_names=frozenset({'i'}))()
self.assertAllClose(jax.jit(f)(), jnp.zeros((2,)))
def test_partial_auto_axis_index(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
out_sharding = NamedSharding(mesh, P('i', None))
@jax.jit(out_shardings=out_sharding)
def f():
return shard_map(lambda: jax.lax.axis_index('i').reshape(1,1),
in_specs=P('i', None), out_specs=P('i', None),
check_vma=False, axis_names=frozenset({'i'}))()
with jax.set_mesh(mesh):
self.assertAllClose(f(), np.arange(4, dtype=np.int32).reshape(-1, 1))
def test_partial_auto_axis_index_degenerated_axis(self):
mesh = jtu.create_mesh((1, 2), ('i', 'j'))
out_sharding = NamedSharding(mesh, P('i', None))
@jax.jit(out_shardings=out_sharding)
def f():
return shard_map(lambda: jax.lax.axis_index('i').reshape(1, 1),
mesh=mesh, in_specs=P('i', None), out_specs=P('i', None),
check_vma=False, axis_names=frozenset({'i'}))()
self.assertAllClose(f(), np.arange(1, dtype=np.int32).reshape(-1, 1))
def test_partial_auto_ppermute(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
x = jnp.arange(8.)
def g(x):
x = jax.lax.with_sharding_constraint(x, NamedSharding(mesh, P('j')))
return jax.lax.ppermute(x, 'i', [(0, 1), (1, 2), (2, 3), (3, 0)])
@jax.jit
def f(x):
return shard_map(g,
mesh=mesh, in_specs=P('i'), out_specs=P('i'),
check_vma=False, axis_names=frozenset({'i'}))(x)
y = f(x) # don't crash
self.assertAllClose(y, jnp.array([6., 7., 0., 1., 2., 3., 4., 5.]),
check_dtypes=False)
# TODO(parkers,mattjj): get XLA to support this too
# def test_partial_auto_all_to_all(self):
#
# mesh = jtu.create_mesh((4, 2), ('i', 'j'))
# x = jnp.arange(128.).reshape(16, 8)
#
# def g(x):
# x = jax.lax.with_sharding_constraint(x, NamedSharding(mesh, P('j')))
# return jax.lax.all_to_all(x, 'i', 0, 1, tiled=True)
#
# @jax.jit
# def f(x):
# return shard_map(g,
# mesh=mesh, in_specs=P('i', None), out_specs=P(None, 'i'),
# check_vma=False, axis_names=frozenset({'i'}))(x)
#
# f(x) # don't crash
def test_partial_auto_debug_print(self):
if config.use_shardy_partitioner.value:
raise unittest.SkipTest("shardy error")
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
x = jnp.arange(8.)
def g(x):
jax.debug.print('{}', x)
@jax.jit
def f(x):
return shard_map(g, mesh=mesh, in_specs=P('i'), out_specs=None,
check_vma=False, axis_names=frozenset({'i'}))(x)
with jax.set_mesh(mesh):
f(x) # don't crash
def test_partial_auto_of_random_keys(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
keys = jax.random.split(jax.random.key(0), 8)
@jax.jit
def f(x):
return shard_map(lambda k: k,
mesh=mesh, in_specs=P('i'), out_specs=P('i'),
check_vma=False, axis_names=frozenset({'i'}))(keys)
y = f(keys) # doesn't crash
self.assertAllClose(jax.random.key_data(y), jax.random.key_data(keys),
check_dtypes=False)
def test_partial_auto_of_random_keys_slice(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
keys = jax.random.split(jax.random.key(0), 8).reshape(4, 2)
@jax.jit
def f(x):
return shard_map(lambda k: k[0],
mesh=mesh, in_specs=P('i'), out_specs=P('i'),
check_vma=False, axis_names=frozenset({'i'}))(x)
f(keys) # doesn't crash
def test_grad_remat(self):
mesh = jtu.create_mesh((1, 1), ('i', 'j'))
args = [jnp.arange(6.).reshape(3, 2), jnp.arange(6.).reshape(3, 2, 1)]
@partial(jax.remat, policy=lambda *_, **__: True)
@shard_map(mesh=mesh, in_specs=(P('j'), P('i')), out_specs=P('i', 'j'))
def f(x, y):
return jnp.dot(x, y)
jax.grad(lambda x, y: f(x, y).sum())(*args)
def test_vmap_grad_shmap_spmd_axis_name_residuals(self):
# https://github.com/jax-ml/jax/pull/21032
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
@shard_map(mesh=mesh, in_specs=P('j'), out_specs=P('j'))
def f(x):
return jnp.sin(x)
xs = jnp.arange(4 * 16.).reshape(4, 16)
jax.vmap(jax.grad(lambda x: f(x).sum()), spmd_axis_name='i')(xs) # don't crash
def test_vmap_grad_remat_shmap_spmd_axis_name_residuals(self):
# https://github.com/jax-ml/jax/pull/21056
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
@partial(jax.remat, policy=lambda *_, **__: True)
@partial(shard_map, mesh=mesh, in_specs=P('j'), out_specs=P('j'))
def f(x):
return jnp.sin(x)
xs = jnp.arange(4 * 16.).reshape(4, 16)
jax.vmap(jax.grad(lambda x: f(x).sum()), spmd_axis_name='i')(xs) # don't crash
def test_grad_shmap_residuals_axis_names_in_mesh_order(self):
# https://github.com/jax-ml/jax/issues/21236
mesh = jtu.create_mesh((4, 2, 1, 1), ('i', 'j', 'k', 'a'))
@partial(
shard_map,
mesh=mesh,
in_specs=P(('i', 'k')),
out_specs=P(('i', 'k')),
)
def f(x):
return jnp.sin(x)
xs = jnp.arange(16.)
ir = jax.jit(jax.grad(lambda x: f(x).sum())).lower(xs)
if config.use_shardy_partitioner.value:
self.assertIn(
'out_shardings=[<@mesh, [{"i", "k"}]>]', ir.as_text()
)
else:
self.assertIn(
"{jax.result_info = \"[('i', 'k')]\"}", ir.as_text()
)
def test_dynamic_slice_transpose(self):
mesh = jtu.create_mesh((2,), ('x',))
arr = np.arange(16., dtype=np.float32)
@partial(shard_map, mesh=mesh, in_specs=P('x'), out_specs=P('x'))
def f(x):
return lax.dynamic_slice_in_dim(x, jnp.array(1, dtype=np.int32), 2)
f(arr) # doesn't crash
jax.jit(f)(arr) # doesn't crash
def g(x):
return jnp.sum(f(x))
jax.grad(g)(arr) # doesn't crash
jax.jit(jax.grad(g))(arr) # doesn't crash
@parameterized.parameters([P()], [P('x')], [P(('x', 'y'))])
def test_print_inside_shard_map(self, specs):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
x = jnp.arange(4.)
@partial(shard_map, mesh=mesh, in_specs=specs, out_specs=specs)
def f(x):
print(x)
return 2 * x
f(x) # doesn't crash
def test_vmap_spmd_axis_name_error(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(x):
return jnp.sin(x)
xs = jnp.arange(4 * 16.).reshape(4, 16)
with self.assertRaisesRegex(ValueError, "spmd_axis_name cannot appear"):
jax.vmap(f, spmd_axis_name='i')(xs)
@partial(shard_map, mesh=mesh, in_specs=P('j'), out_specs=P(('i', 'j')),
check_vma=False)
def g(x):
return jnp.sin(x)
xs = jnp.arange(4 * 16.).reshape(4, 16)
with self.assertRaisesRegex(ValueError, "spmd_axis_name cannot appear"):
jax.vmap(g, spmd_axis_name='i')(xs)
def test_in_spec_none(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
x = jnp.arange(8).reshape(4, 2)
def f(o, x):
self.assertIs(o, obj)
return jnp.sin(x)
obj = object()
y = shard_map(f, mesh=mesh, in_specs=(None, P('i')), out_specs=P('i'))(obj, x)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
obj = None
y = shard_map(f, mesh=mesh, in_specs=(None, P('i')), out_specs=P('i'))(None, x)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
def f2(o, x):
self.assertIsInstance(o, dict)
self.assertIs(o['a'], obj['a'])
return jnp.sin(x)
obj = {'a': object()}
y = shard_map(f2, mesh=mesh, in_specs=({'a': None}, P('i')), out_specs=P('i'))(obj, x)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
def f3(x, o):
self.assertIs(o, obj)
return jnp.sin(x)
obj = object()
y = shard_map(f3, mesh=mesh, in_specs=(P('i'), None), out_specs=P('i'))(x, obj)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
obj = None
y = shard_map(f3, mesh=mesh, in_specs=(P('i'), None), out_specs=P('i'))(x, obj)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
def f4(o1, o2, x, o3):
self.assertIs(o1, obj1)
self.assertIs(o2[0], obj2[0])
self.assertIs(o2[1], obj2[1])
self.assertIs(o3, obj3)
return jnp.sin(x)
obj1 = object()
obj2 = (object(), object())
obj3 = object()
y = shard_map(f4, mesh=mesh, in_specs=(None, None, P('i'), None),
out_specs=P('i'))(obj1, obj2, x, obj3)
self.assertAllClose(y, jnp.sin(x), check_dtypes=False)
def test_in_spec_none_divisibility_errors(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
x = jnp.arange(4).reshape(2, 2)
with self.assertRaisesRegex(ValueError, 'divisible'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(None, P('i')),
out_specs=None)(object(), x)
with self.assertRaisesRegex(ValueError, 'divisible'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i'), None),
out_specs=None)(x, object())
with self.assertRaisesRegex(ValueError, 'divisible'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i'), None),
out_specs=None)(x, (object(), object()))
with self.assertRaisesRegex(ValueError, 'divisible'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i'), (None, None)),
out_specs=None)(x, (object(), object()))
with self.assertRaisesRegex(ValueError, 'divisible'):
shard_map(lambda *_: None, mesh=mesh, in_specs=((None, None), P('i')),
out_specs=None)((object(), object()), x)
def test_in_spec_none_rank_errors(self):
mesh = jtu.create_mesh((4, 2), ('i', 'j'))
x = jnp.arange(4)
with self.assertRaisesRegex(ValueError, 'rank'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(None, P('i', 'j')),
out_specs=None)(object(), x)
with self.assertRaisesRegex(ValueError, 'rank'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i', 'j'), None),
out_specs=None)(x, object())
with self.assertRaisesRegex(ValueError, 'rank'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i', 'j'), None),
out_specs=None)(x, (object(), object()))
with self.assertRaisesRegex(ValueError, 'rank'):
shard_map(lambda *_: None, mesh=mesh, in_specs=(P('i', 'j'), (None, None)),
out_specs=None)(x, (object(), object()))
with self.assertRaisesRegex(ValueError, 'rank'):
shard_map(lambda *_: None, mesh=mesh, in_specs=((None, None), P('i', 'j')),
out_specs=None)((object(), object()), x)
def test_custom_linear_solve_rep_rules(self):
# https://github.com/jax-ml/jax/issues/20162
mesh = jtu.create_mesh((1,), ('i',))
a = jnp.array(1).reshape(1, 1)
b = jnp.array(1).reshape(1)
@partial(shard_map, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
def f(a, b):
c = jnp.linalg.solve(a, b)
return c
_ = f(a, b) # don't crash
def test_temporary_error_suppression_flag(self):
mesh = jtu.create_mesh((2,), ('i',))
def f(x, y):
z = shard_map(lambda x, y: x + jax.lax.all_gather(y, 'i', tiled=True),
mesh=mesh, in_specs=(P(None), P('i')), out_specs=P(None),
check_vma=False,
)(x, y)
return z
y = jnp.arange(8)
xs = jnp.arange(32).reshape(4, 8)
with self.assertRaisesRegex(ValueError, 'vmap spmd_axis_name cannot appear in'):
_ = jax.vmap(f, in_axes=(0, None), spmd_axis_name='i')(xs, y)
with config.disable_vmap_shmap_error():
_ = jax.vmap(f, in_axes=(0, None), spmd_axis_name='i')(xs, y)
def test_in_spec_none_hashability(self):
mesh = jtu.create_mesh((2,), ('i',))
class A:
def __hash__(self):
raise Exception
@partial(shard_map, mesh=mesh, in_specs=(None,), out_specs=())
def f(a):
return ()
f(A()) # don't crash
@parameterized.named_parameters(
('axis_name', True),
('no_axis_name', False),
)
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_explicit_vmap_grad_shmap(self, use_axis_name, mesh):
np_inp = np.arange(6 * 24, dtype=np.float32).reshape(6, 24)
arr = jax.device_put(np_inp, P('x', None))
def g(x):
self.assertEqual(x.aval.vma, frozenset())
if use_axis_name:
out = jax.shard_map(jnp.cos, in_specs=P('y'), out_specs=P('y'),
axis_names={'y'})(x)
else:
out = jax.shard_map(jnp.cos, in_specs=P('y'), out_specs=P('y'))(x)
self.assertEqual(out.aval.sharding.spec, P('y'))
return out.sum()
out = jax.jit(jax.vmap(jax.grad(g)))(arr)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', 'y')))
def test_get_check_rep(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
def f(x, reduce_along, use_jit):
out_spec = P(*(n for n in ('x', 'y') if n not in reduce_along))
@partial(shard_map, mesh=mesh, in_specs=P('x', 'y'), out_specs=out_spec)
def g(x):
result = lax.psum(x, axis_name=reduce_along)
self.assertEqual(result.aval.vma, x.aval.vma - set(reduce_along))
return result
if use_jit:
return jax.jit(g)(x)
else:
return g(x)
for use_jit in [True, False]:
x = np.zeros((8, 8), dtype=np.float32)
f(x, reduce_along=('y',), use_jit=use_jit)
f(x, reduce_along=('x',), use_jit=use_jit)
f(x, reduce_along=('x', 'y'), use_jit=use_jit)
def test_pmin(self):
mesh = jtu.create_mesh((4,), ('i',))
x = jnp.arange(8., dtype=np.float32)
y = shard_map(lambda x: jax.lax.pmin(x, 'i'),
mesh=mesh, in_specs=P('i'), out_specs=P())(x) # don't crash
self.assertArraysEqual(y, np.array([0, 1], dtype=np.float32))
def test_pmax(self):
mesh = jtu.create_mesh((4,), ('i',))
x = jnp.arange(8., dtype=np.float32)
y = shard_map(lambda x: jax.lax.pmax(x, 'i'),
mesh=mesh, in_specs=P('i'), out_specs=P())(x) # don't crash
self.assertArraysEqual(y, np.array([6, 7], dtype=np.float32))
def test_pmax_vma_in_types(self):
mesh = jtu.create_mesh((4,), ('i',))
x = jnp.arange(8., dtype=np.float32)
f = jax.jit(shard_map(lambda x: jax.lax.pmax(x, 'i'), mesh=mesh,
in_specs=P(), out_specs=P()))
jaxpr = f.trace(x).jaxpr
self.assertIn("pvary[axes=('i',)", str(jaxpr))
f(x) # doesn't crash
def test_mul_with_vma_in_types(self):
mesh = jtu.create_mesh((2,), ('x',))
x = np.arange(8.)
def f(x):
self.assertEqual(x.aval.vma, frozenset({'x'}))
out = x * 2
self.assertEqual(out.aval.vma, frozenset({'x'}))
return out
f = jax.jit(shard_map(f, mesh=mesh, in_specs=P('x'), out_specs=P('x')))
jaxpr = f.trace(x).jaxpr
self.assertIn("pvary[axes=('x',)", str(jaxpr))
out = f(x)
self.assertArraysEqual(out, x * 2)
# TODO(yashkatariya): Enable grad test which requires adding psum_p support.
# def g(x, y):
# return jnp.sum(f(x, y))
# print(jax.jit(jax.grad(g)).trace(x, y).jaxpr)
def test_all_gather_with_vma_in_types(self):
mesh = jtu.create_mesh((2,), ('x',))
x = np.arange(8.)
def f(x):
self.assertEqual(x.aval.vma, frozenset())
out = jax.lax.all_gather(x, 'x')
self.assertEqual(out.aval.vma, frozenset({'x'}))
return out
f = jax.jit(shard_map(f, mesh=mesh, in_specs=P(), out_specs=P('x')))
jaxpr = f.trace(x).jaxpr
self.assertIn("pvary[axes=('x',)", str(jaxpr))
f(x) # doesn't crash
def test_rep_none_canonicalization(self):
# https://github.com/jax-ml/jax/issues/26621
if config.use_shardy_partitioner.value:
self.skipTest('complex values fail under shardy')
N = 8
xs = jnp.ones((8, N), dtype=jnp.int32)
variables = jax.random.normal(jax.random.key(1), (N, N), jnp.complex64)
mesh = jtu.create_mesh((2,), ('i',))
in_specs = (P(), P("i"),)
out_specs = P("i")
variables = jax.lax.with_sharding_constraint(variables, NamedSharding(mesh, P()))
xs = jax.lax.with_sharding_constraint(xs, NamedSharding(mesh, P('i')))
def fun(v, xs):
# Commenting this single line below makes everything work
v = jax.scipy.linalg.expm(v)
v = v.sum()
return v * xs.sum(axis=-1).astype(v.dtype)
res = fun(variables, xs)
fun_shard_map = shard_map(fun, mesh=mesh, in_specs=in_specs, out_specs=out_specs)
res = fun_shard_map(variables, xs) # don't crash
def test_rep_none_canonicalization_again(self):
# https://github.com/jax-ml/jax/issues/24762
mesh = jtu.create_mesh((2,), ('i',))
def f(x):
return jnp.insert(x, 0, 0)[None]
f = shard_map(f, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
f(jnp.zeros(100)) # don't crash
def test_custom_jvp_symbolic_zeros(self):
# https://github.com/jax-ml/jax/issues/26763
mesh = jtu.create_mesh((4,), ('i',))
@jax.custom_jvp
def f(a: jax.Array, b: jax.Array) -> jax.Array:
return a + b
@partial(f.defjvp, symbolic_zeros=True)
def f_jvp(primals, tangents):
a, b = primals
a_dot, b_dot = tangents
y = f(a, b)
y_dot = jnp.zeros_like(y)
if not isinstance(a_dot, SymbolicZero):
y_dot += a_dot
if not isinstance(b_dot, SymbolicZero):
y_dot += b_dot
return y, y_dot
x = jax.random.normal(jax.random.key(0), (jax.device_count(), 20))
A = jax.random.normal(jax.random.key(1), (jax.device_count(), 20))
g = shard_map(f, mesh=mesh, in_specs=P('i'), out_specs=P('i'))
jax.jvp(lambda x: g(x, A), (x,), (x,)) # don't crash
def test_cond_pvary_errors(self):
mesh = jtu.create_mesh((1, 1), ('x', 'y'))
def f(x, y):
def true_fn(x, y):
return x
def false_fun(x, y):
return y
return jax.lax.cond(True, true_fn, false_fun, x, y)
x = jnp.arange(4.)
with self.assertRaisesRegex(
TypeError,
r"applying `jax.lax.pvary\(..., \('y',\)\)` to the output of true_fun"):
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(('x', 'y')))(x, x)
def test_cond_pvary_errors_pytree(self):
mesh = jtu.create_mesh((1, 1), ('x', 'y'))
def f(x, y):
def true_fn(x, y):
return x, y
def false_fun(x, y):
return y, x
return jax.lax.cond(True, true_fn, false_fun, x, y)
x = jnp.arange(4.)
with self.assertRaisesRegex(
TypeError,
r"applying `jax.lax.pvary\(..., \('y',\)\)` to the output of true_fun"):
shard_map(f, mesh=mesh, in_specs=(P('x'), P('y')), out_specs=P(('x', 'y')))(x, x)
def test_scan_pvary_errors(self):
mesh = jtu.create_mesh((1, 1), ('i', 'j'))
x = jnp.arange(3.)
y = jnp.arange(3.)
@partial(shard_map, mesh=mesh, in_specs=(P('i'), P()), out_specs=P('i'))
def f(x, y):
def body(carry, _):
c1, c2 = carry
return (c2, c1), () # swap the carry
(x_, y_), _ = jax.lax.scan(body, (x, y), (), length=2)
return x_, y_
with self.assertRaisesRegex(
TypeError,
r"This might be fixed by applying `jax.lax.pvary\(..., \('i',\)\)` to"
r' the initial'):
f(x, y)
@partial(shard_map, mesh=mesh, in_specs=(P('i'), P()), out_specs=P('i'))
def g(x, y):
def body(carry, _):
c1, c2 = carry
return (c2, c1), ()
y = jax.lax.pvary(y, 'i') # fix the issue
(x_, y_), _ = jax.lax.scan(body, (x, y), (), length=2)
return x_, y_
g(x, y) # doesn't crash
def test_scan_pvary_errors2(self):
mesh = jtu.create_mesh((1, 1), ('i', 'j'))
x = jnp.arange(3.)
y = jnp.arange(3.)
z = jnp.arange(3.)
@partial(shard_map, mesh=mesh, in_specs=(P('i'), P(), P(('i', 'j'))), out_specs=P(('i', 'j')))
def f(x, y, z):
def body(carry, _):
c1, c2, c3 = carry
return (c3, c1, c2), () # swap the carry
# x = jax.lax.pvary(x, 'j')
# y = jax.lax.pvary(y, ('i', 'j'))
carry, _ = jax.lax.scan(body, (x, y, z), (), length=2)
return carry
with self.assertRaisesRegex(
TypeError,
r'This might be fixed by:\n \* applying `jax.lax.pvary\(...,'
r" \('j',\)\)`"):
f(x, y, z)
@partial(shard_map, mesh=mesh, in_specs=(P('i'), P(), P(('i', 'j'))), out_specs=P(('i', 'j')))
def g(x, y, z):
def body(carry, _):
c1, c2, c3 = carry
return (c3, c1, c2), () # swap the carry
x = jax.lax.pvary(x, 'j') # fix the issue
y = jax.lax.pvary(y, ('i', 'j'))
carry, _ = jax.lax.scan(body, (x, y, z), (), length=2)
return carry
g(x, y, z) # doesn't crash
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_shmap_full_manual_context_explicit(self, mesh):
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, P('x', 'y'))
@partial(jax.shard_map, out_specs=P('x', 'y'))
def f(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x', 'y'))
self.assertEqual(x.aval.vma, {'x', 'y'})
out = x * 2
self.assertEqual(out.aval.vma, {'x', 'y'})
return out
out = f(arr)
self.assertArraysEqual(out, np_inp * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', 'y')))
jax.jit(f)(arr) # doesn't crash
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_shmap_partial_manual_explicit(self, mesh):
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, P('x', 'y'))
@partial(jax.shard_map, axis_names=frozenset('x'), out_specs=P('x'))
def f(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x',))
self.assertEqual(get_abstract_mesh().explicit_axes, ('y',))
self.assertEqual(x.aval.sharding.spec, P(None, 'y'))
self.assertEqual(x.aval.vma, {'x'})
out = x * 2
self.assertEqual(out.aval.sharding.spec, P(None, 'y'))
self.assertEqual(out.aval.vma, {'x'})
return out
out = jax.jit(f)(arr)
self.assertArraysEqual(out, np_inp * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', 'y')))
@jtu.with_explicit_mesh((2, 2), ('x', 'y'), axis_types=(AxisType.Auto,) * 2)
def test_shmap_full_manual_context_auto(self, mesh):
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, P('x', 'y'))
@partial(jax.shard_map, in_specs=P('x', 'y'), out_specs=P('x', 'y'))
def f(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x', 'y'))
self.assertEqual(x.aval.vma, {'x', 'y'})
out = x * 2
self.assertEqual(out.aval.vma, {'x', 'y'})
return out
out = f(arr)
self.assertArraysEqual(out, np_inp * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', 'y')))
jax.jit(f)(arr) # doesn't crash
@jtu.with_explicit_mesh((2, 2), ('x', 'y'), axis_types=(AxisType.Auto,) * 2)
def test_shmap_partial_manual_auto(self, mesh):
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, P('x', 'y'))
@partial(jax.shard_map, axis_names=frozenset('x'), in_specs=P('x'),
out_specs=P('x'))
def f(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x',))
self.assertEqual(get_abstract_mesh().auto_axes, ('y',))
self.assertEqual(x.aval.vma, {'x'})
out = x * 2
self.assertEqual(out.aval.vma, {'x'})
return out
out = jax.jit(f)(arr)
self.assertArraysEqual(out, np_inp * 2)
def test_no_mesh_context_error(self):
with self.assertRaisesRegex(ValueError, "The context mesh cannot be empty"):
jax.shard_map(lambda x: x, in_specs=P(), out_specs=P())(np.arange(8))
def test_pvary_in_shmap_of_grad(self):
mesh = jtu.create_mesh((2,), 'x')
def g(x):
return jnp.mean(x ** 2)
def f(x):
val, grad = jax.value_and_grad(g)(x)
return (jnp.atleast_1d(val), jnp.atleast_1d(grad))
jax.shard_map(f, mesh=mesh, in_specs=P('x'), out_specs=P('x')
)(jnp.ones(2,)) # doesn't crash
@jtu.with_explicit_mesh((2,), ('data',))
def test_jnp_histogram(self, mesh):
x = jnp.arange(8 * 4 * 2).reshape(8, 4, 2)
def f(x, bin_edges):
hist, _ = jax.vmap(lambda q: jnp.histogram(q, bins=bin_edges))(x)
return hist
bin_edges = jnp.histogram_bin_edges(x, bins=100)
g = jax.shard_map(f, in_specs=(P('data'), P()), out_specs=P('data'))
g(x, bin_edges) # doesn't crash
jax.jit(g)(x, bin_edges) # doesn't crash
def test_shmap_linearize_and_linearize_transpose_error(self):
mesh = jtu.create_mesh((2,), ('x',))
def f(x):
return jnp.mean(x ** 2)
def m(p, t):
out_p, fwd = jax.linearize(f, p)
out_t = fwd(t)
bwd = jax.linear_transpose(fwd, p)
return bwd(out_t)
with self.assertRaisesRegex(
ValueError,
r"applying `jax.lax.pvary\(..., \('x',\)\)` to the primal value passed"):
shard_map(partial(m, jnp.array([1.])), mesh=mesh, in_specs=P('x'),
out_specs=P('x'))(jnp.ones((2,))) # doesn't crash
def m2(p, t):
p = jax.lax.pvary(p, 'x') # fixes the issue
out_p, fwd = jax.linearize(f, p)
out_t = fwd(t)
bwd = jax.linear_transpose(fwd, p)
return bwd(out_t)
shard_map(partial(m2, jnp.array([1.])), mesh=mesh, in_specs=P('x'),
out_specs=P('x'))(jnp.ones((2,))) # doesn't crash
@jtu.with_explicit_mesh((2, 2), ('x', 'y'), axis_types=(AxisType.Auto,) * 2)
def test_argmax_pvary(self, mesh):
@jax.shard_map(in_specs=P('x', 'y'), out_specs=P('x', 'y'))
def argmax_impl(x):
y = x.argmax(axis=-1, keepdims=1)
return y
argmax_impl(jax.random.normal(jax.random.key(0), (1024, 1024))) # doesn't crash
@parameterized.parameters([False, True])
def test_smap(self, jit):
mesh = jtu.create_mesh((2, 2, 2), ('x', 'y', 'z'))
np_inp = np.arange(32.).reshape(4, 8)
arr = jax.device_put(np_inp, NamedSharding(mesh, P('x', 'y')))
def g(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x', 'y'))
self.assertEqual(get_abstract_mesh().auto_axes, ('z',))
self.assertEqual(x.aval.vma, {'x', 'y'})
out = x * x
self.assertEqual(out.aval.vma, {'x', 'y'})
return out
def h(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x',))
self.assertEqual(get_abstract_mesh().auto_axes, ('y', 'z'))
self.assertEqual(x.aval.vma, {'x'})
out = jax.smap(g, in_axes=0, out_axes=0, axis_name='y')(x)
self.assertEqual(out.aval.vma, {'x'})
return out
def f(x):
return jax.smap(h, in_axes=0, out_axes=0, axis_name='x')(x)
if jit:
f = jax.jit(f)
with jax.set_mesh(mesh):
out = f(arr)
self.assertArraysEqual(out, np_inp * np_inp)
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2, 2), ('x', 'y', 'z'))
def test_smap_explicit(self, jit, mesh):
np_inp = np.arange(32.).reshape(4, 8)
arr = jax.device_put(np_inp, P('x', 'y'))
def g(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x', 'y'))
self.assertEqual(get_abstract_mesh().explicit_axes, ('z',))
self.assertEqual(x.aval.vma, {'x', 'y'})
out = x * x
self.assertEqual(out.aval.vma, {'x', 'y'})
return out
def h(x):
self.assertEqual(get_abstract_mesh().manual_axes, ('x',))
self.assertEqual(get_abstract_mesh().explicit_axes, ('y', 'z'))
self.assertEqual(x.aval.vma, {'x'})
out = jax.smap(g, in_axes=0, out_axes=0, axis_name='y')(x)
self.assertEqual(out.aval.vma, {'x'})
return out
def f(x):
return jax.smap(h, out_axes=0, axis_name='x')(x)
if jit:
f = jax.jit(f)
out = f(arr)
self.assertArraysEqual(out, np_inp * np_inp)
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2,), ('x',), axis_types=(AxisType.Auto,))
def test_smap_replicated(self, jit, mesh):
@jax.smap(in_axes=None, out_axes=None, axis_name='x')
def f(x):
return x * 2
out = f(np.arange(8))
self.assertArraysEqual(out, np.arange(8) * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2,), ('data',), axis_types=(AxisType.Auto,))
def test_smap_replicated_sharded(self, jit, mesh):
@jax.smap(in_axes=(None, 0), out_axes=(None, 0), axis_name='data')
def f(x, y):
return x * 2, y * 2
out1, out2 = f(np.arange(8), np.arange(8))
self.assertArraysEqual(out1, np.arange(8) * 2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P()))
self.assertArraysEqual(out2, np.arange(8) * 2)
self.assertEqual(out2.sharding, NamedSharding(mesh, P('data')))
@jax.smap(in_axes=(None, 0), out_axes=0, axis_name='data')
def g(x, y):
return x + y
out = g(np.arange(4), np.arange(8))
self.assertEqual(out.sharding, NamedSharding(mesh, P('data')))
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2,), ('x',), axis_types=(AxisType.Auto,))
def test_smap_auto_error(self, jit, mesh):
with self.assertRaisesRegex(TypeError, "in_axes was not specified"):
jax.smap(lambda x: x * 2, out_axes=0, axis_name='x')(np.arange(4))
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Explicit, AxisType.Auto))
def test_smap_auto_explicit(self, jit, mesh):
def f(x):
self.assertEqual(x.aval.vma, {'x'})
return x * 2
arr = jax.device_put(np.arange(4), P('x'))
g = jax.smap(f, out_axes=0, axis_name='x')
if jit:
g = jax.jit(g)
out = g(arr)
self.assertArraysEqual(out, np.arange(4) * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x')))
def g(x):
self.assertEqual(x.aval.vma, {'y'})
return x * 2
arr = jax.device_put(np.arange(4), P('y'))
g = jax.smap(g, in_axes=0, out_axes=0, axis_name='y')
if jit:
g = jax.jit(g)
out = g(arr)
self.assertArraysEqual(out, np.arange(4) * 2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('y')))
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Explicit, AxisType.Auto))
def test_smap_auto_explicit_nest(self, jit, mesh):
def g(b):
self.assertEqual(b.aval.vma, {'x', 'y'})
return jnp.sin(b)
def f(a):
self.assertEqual(a.aval.vma, {'y'})
b = a * 2
return jax.smap(g, in_axes=1, out_axes=1, axis_name='x')(b)
arr = jax.device_put(np.arange(16).reshape(8, 2), P('y'))
h = jax.smap(f, in_axes=0, out_axes=0, axis_name='y')
if jit:
h = jax.jit(h)
h(arr) # doesn't crash
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Explicit, AxisType.Auto))
def test_smap_auto_explicit_nest_inner_none(self, jit, mesh):
def g(b):
self.assertEqual(b.aval.vma, {'y'})
return jnp.sin(b)
def f(a):
self.assertEqual(a.aval.vma, {'y'})
b = a * 2
# Going manual over explicit axis `x` but in_axes is Infer and since
# input has no sharding, it will default to None.
return jax.smap(g, out_axes=1, axis_name='x')(b)
arr = jax.device_put(np.arange(16).reshape(8, 2), P('y'))
h = jax.smap(f, in_axes=0, out_axes=0, axis_name='y')
if jit:
h = jax.jit(h)
h(arr) # doesn't crash
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Explicit, AxisType.Auto))
def test_smap_auto_explicit_nest_mesh_call_time(self, jit, mesh):
@jax.smap(in_axes=1, out_axes=1, axis_name='x')
def g(b):
return jnp.sin(b)
@jax.smap(in_axes=0, out_axes=0, axis_name='y')
def f(a):
self.assertEqual(a.aval.vma, {'y'})
b = a * 2
return g(b)
if jit:
f = jax.jit(f)
arr = jax.device_put(np.arange(16).reshape(8, 2), P('y'))
f(arr) # doesn't crash
@parameterized.parameters([False, True])
@jtu.with_explicit_mesh((2, 2), ('x', 'y'),
axis_types=(AxisType.Auto, AxisType.Auto))
def test_smap_nested_psum(self, jit, mesh):
@jax.smap(axis_name='x', in_axes=0, out_axes=0)
def f(x):
x = jnp.sin(x)
@jax.smap(axis_name='y', in_axes=0, out_axes=None)
def g(x):
self.assertEqual(jax.typeof(x).vma, {'x', 'y'})
x = jax.lax.psum(x, 'y')
self.assertEqual(jax.typeof(x).vma, {'x'})
return x
x = g(x)
self.assertEqual(jax.typeof(x).vma, {'x'})
return x
if jit:
f = jax.jit(f)
x = jnp.arange(4.)
f(x) # asserts in f
@jtu.with_explicit_mesh((2,), 'x')
def test_linalg_inv(self, mesh):
key = jax.random.key(123)
arr = jax.random.uniform(key, shape=(4,5,5), out_sharding=P('x'))
@shard_map(out_specs=P('x'))
def f(x):
return jax.lax.map(jnp.linalg.inv, x)
f(arr) # doesn't crash
@jtu.with_explicit_mesh((2,), 'x')
def test_mutable_array_arg_basic(self, mesh):
x_ref = core.new_ref(jnp.zeros(4, 'float32', out_sharding=P('x')))
@jax.jit
@shard_map(out_specs=None)
def f(x_ref):
x_ref[...] += jax.lax.axis_index('x').astype('float32')
f(x_ref)
self.assertAllClose(x_ref[...], jnp.array([0., 0., 1., 1.]),
check_dtypes=False)
@jtu.with_explicit_mesh((2,), 'x')
def test_mutable_array_internal_basic(self, mesh):
x = jnp.arange(4, dtype='float32', out_sharding=P('x'))
@jax.jit
@shard_map(out_specs=P('x'))
def f(x):
x_ref = core.new_ref(jnp.zeros_like(x))
x_ref[...] = x
return x_ref[...]
y = f(x)
self.assertAllClose(y, x, check_dtypes=False)
def test_random_beta_vma(self):
mesh = jtu.create_mesh((2,), 'dp')
rng = jax.random.key(42)
f = shard_map(lambda x, y, z: jax.random.beta(jax.lax.pvary(x, ('dp',)), y, z),
mesh=mesh,
in_specs=(P(), P('dp'), P('dp')), out_specs=P('dp'))
res = f(rng, jnp.ones((64, 1)), jnp.ones((64, 1)))
# explicit key resuse.
a, b = res.reshape(2, 32)
self.assertAllClose(a, b) # Key reuse.
# Also works without key-reuse:
rng = jax.random.key(42)
f = shard_map(lambda x, y, z: jax.random.beta(x[0], y, z), mesh=mesh,
in_specs=(P('dp'), P('dp'), P('dp')), out_specs=P('dp'))
f(jax.random.split(rng, 2), jnp.ones((64, 1)), jnp.ones((64, 1))) # doesn't crash
rng = jax.random.key(42)
f = shard_map(lambda x, y, z: jax.random.beta(x[0], y, z), mesh=mesh,
in_specs=(P('dp'), P(), P()), out_specs=P('dp'))
f(jax.random.split(rng, 2), jnp.ones((64, 1)), jnp.ones((64, 1))) # doesn't crash
@parameterized.named_parameters(
('1', P('x'), {'x'}, P(None, 'y')),
('2', P(None, 'y'), {'y'}, P('x', None))
)
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_partial_manual_explicit_shmap(self, out_spec, axis_name, aval_spec,
mesh):
@jax.shard_map(out_specs=out_spec, axis_names=axis_name)
def f(x):
self.assertEqual(jax.typeof(x).sharding.spec, aval_spec)
return x * 2
arr = jax.device_put(np.arange(16).reshape(8, 2), P('x', 'y'))
out = f(arr)
out2 = jax.jit(f)(arr)
self.assertEqual(out.sharding, out2.sharding)
@jtu.with_explicit_mesh((1, 2, 2), ('x', 'y', 'z'))
def test_axis_index_explicit_mesh_eager_shmap(self, mesh):
def f():
return jnp.array([jax.lax.axis_index(n) for n in mesh.axis_names])
jax.shard_map(f, out_specs=P(mesh.axis_names))() # doesn't crash
jax.jit(jax.shard_map(f, out_specs=P(mesh.axis_names)))() # doesn't crash
jax.shard_map(f, out_specs=P(), check_vma=False)() # doesn't crash
jax.jit(jax.shard_map(f, out_specs=P(), check_vma=False))() # doesn't crash
@config.remove_size_one_mesh_axis_from_type(True)
@jtu.with_explicit_mesh((2, 1), ('x', 'y'))
def test_remove_one_sized_mesh_axis_from_vma(self, mesh):
np_inp = np.arange(16).reshape(8, 2)
arr = jax.device_put(np_inp, P('x', 'y'))
@jax.jit
@jax.shard_map(in_specs=P('x', 'y'), out_specs=P())
def f(x):
self.assertEqual(x.aval.vma, {'x'})
out = jax.lax.psum(x, 'x')
self.assertEqual(out.aval.vma, frozenset())
return out
out = f(arr)
self.assertEqual(out.shape, (4, 2))
self.assertEqual(out.sharding, NamedSharding(mesh, P(None, None)))
self.assertArraysEqual(out, np_inp[:4, :] + np_inp[4:, :])
@jtu.with_explicit_mesh((2,), ('x',))
def test_varargs_error(self, mesh):
@jax.shard_map(in_specs=jax.P('x'), out_specs=())
def f(*foos, **kwargs):
return ()
with self.assertRaises(ValueError): # not AssertionError
f(jnp.arange(3.), jnp.arange(3.), jnp.arange(3.))
@jtu.with_explicit_mesh((2,), 'x')
def test_reduced_vary_automatically_inserted(self, mesh):
arr1 = jax.device_put(np.arange(8.).reshape(4, 2), P('x', None))
arr2 = jax.device_put(np.arange(12.).reshape(2, 6),
P(None, None, reduced={'x'}))
@jax.jit
@jax.shard_map(in_specs=(P('x', None), P(None, None, reduced={'x'})),
out_specs=P('x', None))
def f(x, y):
return jnp.dot(x, y)
out = f(arr1, arr2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', None)))
self.assertArraysEqual(out, arr1 @ arr2)
def g(x, y):
return f(x, y).sum()
out1, out2 = jax.jit(jax.grad(g, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, arr1.sharding)
self.assertEqual(out2.sharding,
NamedSharding(mesh, P(None, None, unreduced={'x'})))
@jtu.with_explicit_mesh((2, 2), ('x', 'y'))
def test_reduced_vary_automatically_inserted_psum(self, mesh):
arr1 = jax.device_put(np.arange(8.).reshape(4, 2), P('x', 'y'))
arr2 = jax.device_put(np.arange(12.).reshape(2, 6),
P('y', None, reduced={'x'}))
@jax.jit
@jax.shard_map(in_specs=(P('x', 'y'), P('y', None, reduced={'x'})),
out_specs=P('x', None))
def f(x, y):
self.assertEqual(x.vma, {'x', 'y'})
self.assertEqual(y.vma, {'y'})
self.assertEqual(y.aval.sharding.spec.reduced, {'x'})
z = jnp.dot(x, y)
self.assertEqual(z.vma, {'x', 'y'})
return jax.lax.psum(z, axis_name='y')
out = f(arr1, arr2)
self.assertEqual(out.sharding, NamedSharding(mesh, P('x', None)))
self.assertArraysEqual(out, jnp.dot(arr1, arr2, out_sharding=P('x')))
def g(x, y):
return f(x, y).sum()
out1, out2 = jax.jit(jax.grad(g, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, arr1.sharding)
self.assertEqual(out2.sharding,
NamedSharding(mesh, P('y', None, unreduced={'x'})))
@config.numpy_dtype_promotion('standard')
@jtu.with_explicit_mesh((2,), 'x')
def test_astype_reduced_fwd_unreduced_bwd_shmap(self, mesh):
inputs = jax.device_put(np.ones((32, 64), dtype=jnp.bfloat16), P('x', None))
params = jax.device_put(np.ones((64, 64), dtype=jnp.float32),
P(None, None, reduced={'x'}))
targets = jax.device_put(np.ones((32, 64), dtype=jnp.bfloat16), P('x', None))
@jax.shard_map(in_specs=(P('x', None), P(None, None, reduced={'x'})),
out_specs=P('x', None))
def dot(inputs, params):
self.assertEqual(params.aval.sharding.spec.reduced, {'x'})
params = params.astype(jnp.bfloat16)
self.assertEqual(params.aval.sharding.spec.reduced, {'x'})
return jnp.dot(inputs.astype(jnp.bfloat16), params)
@jax.jit
def loss_fn(inputs, params, targets):
out = dot(inputs, params)
return jnp.mean(jnp.sum((out - targets) ** 2, axis=-1))
jax.jit(jax.grad(loss_fn, argnums=1))(inputs, params, targets) # doesn't crash
@jtu.with_explicit_mesh((2,), 'x')
def test_transpose_unreduced_shmap(self, mesh):
arr1 = jax.device_put(np.arange(8.).reshape(2, 4), P(reduced={'x'}))
arr2 = jax.device_put(np.arange(12.).reshape(2, 6), P(None, 'x'))
@jax.shard_map(out_specs=P(None, 'x'))
def f(x, y):
x_ = x.T
return jnp.dot(x_, y)
@jax.jit
def g(x, y):
return f(x, y).sum()
out = g(arr1, arr2)
self.assertEqual(out.sharding, NamedSharding(mesh, P()))
self.assertArraysEqual(out, (arr1.T @ arr2).sum())
out1, out2 = jax.jit(jax.grad(g, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding,
NamedSharding(mesh, P(None, None, unreduced={'x'})))
self.assertEqual(out2.sharding, arr2.sharding)
@parameterized.named_parameters(
('mul', jax.lax.mul),
('add', jax.lax.add),
)
@jtu.with_explicit_mesh((2,), 'x')
def test_one_input_sharded_another_reduced_shmap(self, func, mesh):
np1 = np.arange(16.)
np2 = np.arange(8.)
arr1 = jax.device_put(np1, P('x'))
arr2 = jax.device_put(np2, P(None, reduced={'x'}))
@jax.jit
@jax.shard_map(out_specs=P())
def f(x, y):
z = func(x, y)
return jax.lax.psum(z, 'x')
out = f(arr1, arr2)
self.assertEqual(out.sharding, NamedSharding(mesh, P(None)))
with jax.set_mesh(empty_concrete_mesh):
ex_out = np.sum([func(s.data, np2) for s in arr1.addressable_shards],
axis=0)
self.assertArraysEqual(out, ex_out)
@jax.jit
def g(x, y):
return f(x, y).sum()
out1, out2 = jax.jit(jax.grad(g, argnums=(0, 1)))(arr1, arr2)
self.assertEqual(out1.sharding, NamedSharding(mesh, P('x')))
self.assertEqual(out2.sharding,
NamedSharding(mesh, P(None, unreduced={'x'})))
| ShardMapTest |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 26407,
"end": 26525
} | class ____(Hostname):
platform = 'Darwin'
distribution = None
strategy_class = DarwinStrategy
| DarwinHostname |
python | streamlit__streamlit | e2e_playwright/shared/data_mocks.py | {
"start": 898,
"end": 7168
} | class ____(NamedTuple):
expected_rows: int
expected_cols: int
expected_data_format: DataFormat
SHARED_TEST_CASES = [
# None:
(None, CaseMetadata(0, 0, DataFormat.EMPTY)),
# Empty list:
([], CaseMetadata(0, 0, DataFormat.LIST_OF_VALUES)),
# Empty tuple:
((), CaseMetadata(0, 0, DataFormat.TUPLE_OF_VALUES)),
# Empty dict (not a an empty set!)
({}, CaseMetadata(0, 0, DataFormat.KEY_VALUE_DICT)),
# Empty set:
(set(), CaseMetadata(0, 0, DataFormat.SET_OF_VALUES)),
# Empty numpy array:
# for unknown reasons, pd.DataFrame initializes empty numpy arrays with a single column
(np.ndarray(0), CaseMetadata(0, 1, DataFormat.NUMPY_LIST)),
# Empty column value mapping with columns:
({"name": [], "type": []}, CaseMetadata(0, 2, DataFormat.COLUMN_VALUE_MAPPING)),
# Empty dataframe:
(pd.DataFrame(), CaseMetadata(0, 0, DataFormat.PANDAS_DATAFRAME)),
# Empty dataframe with columns:
(
pd.DataFrame(
columns=["name", "type"], index=pd.RangeIndex(start=0, step=1)
), # Explicitly set the range index to have the same behavior across versions
CaseMetadata(0, 2, DataFormat.PANDAS_DATAFRAME),
),
# Pandas DataFrame:
(
pd.DataFrame(["st.text_area", "st.markdown"]),
CaseMetadata(2, 1, DataFormat.PANDAS_DATAFRAME),
),
# List of strings (List[str]):
(
["st.text_area", "st.number_input", "st.text_input"],
CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES),
),
# List of integers (List[int]):
([1, 2, 3], CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES)),
# List of floats (List[float]):
([1.0, 2.0, 3.0], CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES)),
# List of booleans (List[bool]):
([True, False, True], CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES)),
# List of Nones (List[None]):
([None, None, None], CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES)),
# List of dates (List[date]):
(
[date(2020, 1, 1), date(2020, 1, 2), date(2020, 1, 3)],
CaseMetadata(3, 1, DataFormat.LIST_OF_VALUES),
),
# Set of strings (Set[str]):
# Set does not have a stable order across different Python version.
# Therefore, we are only testing this with one item.
(
{"st.number_input"},
CaseMetadata(1, 1, DataFormat.SET_OF_VALUES),
),
# Tuple of strings (Tuple[str]):
(
("st.text_area", "st.number_input", "st.text_input"),
CaseMetadata(3, 1, DataFormat.TUPLE_OF_VALUES),
),
# Numpy list / 1D numpy array (np.array[str]):
(
np.array(["st.text_area", "st.number_input", "st.text_input"]),
CaseMetadata(3, 1, DataFormat.NUMPY_LIST),
),
# np.array[int]:
(np.array([1, 2, 3]), CaseMetadata(3, 1, DataFormat.NUMPY_LIST)),
# Multi-dimensional numpy array (np.array[List[Scalar]])
(
np.array(
[
["st.text_area", "widget"],
["st.markdown", "element"],
]
),
CaseMetadata(2, 2, DataFormat.NUMPY_MATRIX),
),
# np.array[List[str]]:
(
np.array([["st.text_area"], ["st.number_input"], ["st.text_input"]]),
CaseMetadata(3, 1, DataFormat.NUMPY_MATRIX),
),
# Pandas Series (pd.Series):
(
pd.Series(["st.text_area", "st.number_input", "st.text_input"], name="widgets"),
CaseMetadata(3, 1, DataFormat.PANDAS_SERIES),
),
# Pandas Styler (pd.Styler):
(
pd.DataFrame(["st.text_area", "st.markdown"]).style,
CaseMetadata(2, 1, DataFormat.PANDAS_STYLER),
),
# Pandas Index (pd.Index):
(
pd.Index(["st.text_area", "st.markdown"]),
CaseMetadata(2, 1, DataFormat.PANDAS_INDEX),
),
# Pyarrow Table (pyarrow.Table) from pandas:
(
pa.Table.from_pandas(pd.DataFrame(["st.text_area", "st.markdown"])),
CaseMetadata(2, 1, DataFormat.PYARROW_TABLE),
),
# List of rows (List[List[Scalar]]):
(
[["st.text_area", "widget"], ["st.markdown", "element"]],
CaseMetadata(2, 2, DataFormat.LIST_OF_ROWS),
),
# List of records (List[Dict[str, Scalar]]):
(
[
{"name": "st.text_area", "type": "widget"},
{"name": "st.markdown", "type": "element"},
],
CaseMetadata(2, 2, DataFormat.LIST_OF_RECORDS),
),
# Column-index mapping ({column: {index: value}}):
(
{
"type": {"st.text_area": "widget", "st.markdown": "element"},
"usage": {"st.text_area": 4.92, "st.markdown": 47.22},
},
CaseMetadata(2, 2, DataFormat.COLUMN_INDEX_MAPPING),
),
# Column-value mapping ({column: List[values]}}):
(
{
"name": ["st.text_area", "st.markdown"],
"type": ["widget", "element"],
},
CaseMetadata(2, 2, DataFormat.COLUMN_VALUE_MAPPING),
),
# Column-series mapping ({column: Series(values)}):
(
{
"name": pd.Series(["st.text_area", "st.markdown"], name="name"),
"type": pd.Series(["widget", "element"], name="type"),
},
CaseMetadata(2, 2, DataFormat.COLUMN_SERIES_MAPPING),
),
# Key-value dict ({index: value}):
(
{"st.text_area": "widget", "st.markdown": "element"},
CaseMetadata(2, 1, DataFormat.KEY_VALUE_DICT),
),
# Raw pyarrow array (pyarrow.Array):
(
pa.array(["st.text_area", "st.markdown"]),
CaseMetadata(2, 1, DataFormat.PYARROW_ARRAY),
),
# Raw pyarrow table (pyarrow.Array):
(
pa.Table.from_pydict(
{
"name": pa.array(["st.text_area", "st.markdown"]),
"usage": pa.array([4.92, 47.22]),
}
),
CaseMetadata(2, 1, DataFormat.PYARROW_TABLE),
),
]
def random_date() -> datetime:
start_date = datetime.fromisoformat("2018-01-31T09:24:31.123+00:00")
end_date = datetime.fromisoformat("2022-01-31T09:24:31.345+00:00")
return (
start_date
+ timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=random.randint(0, int((end_date - start_date).total_seconds())),
)
).replace(tzinfo=None)
| CaseMetadata |
python | astropy__astropy | astropy/modeling/tests/test_fitting_parallel.py | {
"start": 5267,
"end": 12282
} | class ____:
def test_no_world(self):
# This also doubles as a test when there are no iterating dimensions
data = gaussian(np.arange(20), 2, 10, 1)
model = Gaussian1D(amplitude=1.5, mean=12, stddev=1.5)
fitter = LevMarLSQFitter()
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.value, 2)
assert_allclose(model_fit.mean.value, 10)
assert_allclose(model_fit.stddev.value, 1)
def test_wcs_1d(self):
# Test specifying world as a WCS, for the 1D model case
data = gaussian(
np.arange(20)[:, None],
np.array([2, 1.8]),
np.array([10, 11]),
np.array([1, 1.1]),
)
model = Gaussian1D(amplitude=1.5, mean=1.2, stddev=0.15)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=2)
wcs.wcs.ctype = "OFFSET", "WAVE"
wcs.wcs.crval = 10, 0.1
wcs.wcs.crpix = 1, 1
wcs.wcs.cdelt = 10, 0.1
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=wcs,
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.value, [2, 1.8])
assert_allclose(model_fit.mean.value, [1.1, 1.2])
assert_allclose(model_fit.stddev.value, [0.1, 0.11])
def test_wcs_pixel_dimension_mismatch(self):
data = np.empty((20, 10))
model = Gaussian1D(amplitude=1.5, mean=1.2, stddev=0.15)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=3)
with pytest.raises(
ValueError,
match=re.escape(
"The WCS pixel_n_dim (3) does not match the number of "
"dimensions in the data (2)"
),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=wcs,
scheduler="synchronous",
)
def test_wcs_world_dimension_mismatch(self):
data = np.empty((20, 10))
model = Gaussian1D(amplitude=1.5, mean=1.2, stddev=0.15)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=2)
wcs.wcs.ctype = "RA---TAN", "DEC--TAN"
wcs.wcs.crval = 10.0, 20.0
wcs.wcs.crpix = 1, 1
wcs.wcs.cdelt = 0.01, 0.01
with pytest.raises(
ValueError,
match=re.escape(
"The number of WCS world axes corresponding to the fitting axes "
"(2) does not match the number of fitting axes (1)"
),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=wcs,
scheduler="synchronous",
)
def test_array(self):
# Test specifying world as a tuple of arrays with dimensions matching the data
data = gaussian(
np.arange(21)[:, None],
np.array([2, 1.8]),
np.array([10, 10]),
np.array([1, 1.1]),
)
model = Gaussian1D(amplitude=1.5, mean=7, stddev=2)
fitter = LevMarLSQFitter()
world1 = np.array([np.linspace(0, 10, 21), np.linspace(5, 15, 21)]).T
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=(world1,),
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.value, [2, 1.8])
assert_allclose(model_fit.mean.value, [5, 10])
assert_allclose(model_fit.stddev.value, [0.5, 0.55])
def test_array_length_mismatch(self):
data = np.empty((20, 2))
model = Gaussian1D(amplitude=1.5, mean=7, stddev=2)
fitter = LevMarLSQFitter()
world1 = np.array([np.linspace(0, 10, 21), np.linspace(5, 15, 21)]).T
with pytest.raises(
ValueError,
match=re.escape(
"The number of world arrays (2) must match number of fitting axes (1)"
),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=(world1, world1),
)
def test_array_shape_mismatch(self):
data = np.empty((20, 2))
model = Gaussian1D(amplitude=1.5, mean=7, stddev=2)
fitter = LevMarLSQFitter()
world1 = np.array([np.linspace(0, 10, 31), np.linspace(5, 15, 31)]).T
with pytest.raises(
ValueError,
match=re.escape(
"The arrays in the world tuple should be broadcastable to the "
"shape of the data (expected (20, 2)), got (31, 2))"
),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=(world1,),
)
def test_array_dimension_mismatch(self):
model = Planar2D()
data = np.empty((20, 10, 5))
fitter = LevMarLSQFitter()
with pytest.raises(
ValueError,
match=re.escape(
"world[2] has length 6 but data along dimension 2 has length 5"
),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=(1, 2),
world=(np.arange(10), np.arange(6)),
)
def test_invalid_type(self):
data = np.empty((20, 2))
model = Gaussian1D(amplitude=1.5, mean=7, stddev=2)
fitter = LevMarLSQFitter()
world1 = np.array([np.linspace(0, 10, 21), np.linspace(5, 15, 21)]).T
with pytest.raises(
TypeError,
match=re.escape("world should be None, a WCS object or a tuple of arrays"),
):
parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world="banana",
)
def test_fitter_kwargs(tmp_path):
data = gaussian(np.arange(20), 2, 10, 1)
data = np.broadcast_to(data.reshape((20, 1)), (20, 3)).copy()
data[0, 0] = np.nan
model = Gaussian1D(amplitude=1.5, mean=12, stddev=1.5)
fitter = LevMarLSQFitter()
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
fitter_kwargs={"filter_non_finite": True},
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.value, 2)
assert_allclose(model_fit.mean.value, 10)
assert_allclose(model_fit.stddev.value, 1)
| TestWorld |
python | mozilla__bleach | bleach/_vendor/html5lib/_tokenizer.py | {
"start": 639,
"end": 77040
} | class ____(object):
""" This class takes care of tokenizing HTML.
* self.currentToken
Holds the token that is currently being processed.
* self.state
Holds a reference to the method to be invoked... XXX
* self.stream
Points to HTMLInputStream object.
"""
def __init__(self, stream, parser=None, **kwargs):
self.stream = HTMLInputStream(stream, **kwargs)
self.parser = parser
# Setup the initial tokenizer state
self.escapeFlag = False
self.lastFourChars = []
self.state = self.dataState
self.escape = False
# The current token being created
self.currentToken = None
super(HTMLTokenizer, self).__init__()
def __iter__(self):
""" This is where the magic happens.
We do our usually processing through the states and when we have a token
to return we yield the token which pauses processing until the next token
is requested.
"""
self.tokenQueue = deque([])
# Start processing. When EOF is reached self.state will return False
# instead of True and the loop will terminate.
while self.state():
while self.stream.errors:
yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)}
while self.tokenQueue:
yield self.tokenQueue.popleft()
def consumeNumberEntity(self, isHex):
"""This function returns either U+FFFD or the character based on the
decimal or hexadecimal representation. It also discards ";" if present.
If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
"""
allowed = digits
radix = 10
if isHex:
allowed = hexDigits
radix = 16
charStack = []
# Consume all the characters that are in range while making sure we
# don't hit an EOF.
c = self.stream.char()
while c in allowed and c is not EOF:
charStack.append(c)
c = self.stream.char()
# Convert the set of characters consumed to an int.
charAsInt = int("".join(charStack), radix)
# Certain characters get replaced with others
if charAsInt in replacementCharacters:
char = replacementCharacters[charAsInt]
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
elif ((0xD800 <= charAsInt <= 0xDFFF) or
(charAsInt > 0x10FFFF)):
char = "\uFFFD"
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
else:
# Should speed up this check somehow (e.g. move the set to a constant)
if ((0x0001 <= charAsInt <= 0x0008) or
(0x000E <= charAsInt <= 0x001F) or
(0x007F <= charAsInt <= 0x009F) or
(0xFDD0 <= charAsInt <= 0xFDEF) or
charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE,
0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE,
0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE,
0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE,
0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE,
0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE,
0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE,
0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE,
0xFFFFF, 0x10FFFE, 0x10FFFF])):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
try:
# Try/except needed as UCS-2 Python builds' unichar only works
# within the BMP.
char = chr(charAsInt)
except ValueError:
v = charAsInt - 0x10000
char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF))
# Discard the ; if present. Otherwise, put it back on the queue and
# invoke parseError on parser.
if c != ";":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"numeric-entity-without-semicolon"})
self.stream.unget(c)
return char
def consumeEntity(self, allowedChar=None, fromAttribute=False):
# Initialise to the default output for when no entity is matched
output = "&"
charStack = [self.stream.char()]
if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or
(allowedChar is not None and allowedChar == charStack[0])):
self.stream.unget(charStack[0])
elif charStack[0] == "#":
# Read the next character to see if it's hex or decimal
hex = False
charStack.append(self.stream.char())
if charStack[-1] in ("x", "X"):
hex = True
charStack.append(self.stream.char())
# charStack[-1] should be the first digit
if (hex and charStack[-1] in hexDigits) \
or (not hex and charStack[-1] in digits):
# At least one digit found, so consume the whole number
self.stream.unget(charStack[-1])
output = self.consumeNumberEntity(hex)
else:
# No digits found
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "expected-numeric-entity"})
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
else:
# At this point in the process might have named entity. Entities
# are stored in the global variable "entities".
#
# Consume characters and compare to these to a substring of the
# entity names in the list until the substring no longer matches.
while (charStack[-1] is not EOF):
if not entitiesTrie.has_keys_with_prefix("".join(charStack)):
break
charStack.append(self.stream.char())
# At this point we have a string that starts with some characters
# that may match an entity
# Try to find the longest entity the string will match to take care
# of ¬i for instance.
try:
entityName = entitiesTrie.longest_prefix("".join(charStack[:-1]))
entityLength = len(entityName)
except KeyError:
entityName = None
if entityName is not None:
if entityName[-1] != ";":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"named-entity-without-semicolon"})
if (entityName[-1] != ";" and fromAttribute and
(charStack[entityLength] in asciiLetters or
charStack[entityLength] in digits or
charStack[entityLength] == "=")):
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
else:
output = entities[entityName]
self.stream.unget(charStack.pop())
output += "".join(charStack[entityLength:])
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-named-entity"})
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
if fromAttribute:
self.currentToken["data"][-1][1] += output
else:
if output in spaceCharacters:
tokenType = "SpaceCharacters"
else:
tokenType = "Characters"
self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output})
def processEntityInAttribute(self, allowedChar):
"""This method replaces the need for "entityInAttributeValueState".
"""
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
def emitCurrentToken(self):
"""This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted.
"""
token = self.currentToken
# Add token to the queue to be yielded
if (token["type"] in tagTokenTypes):
token["name"] = token["name"].translate(asciiUpper2Lower)
if token["type"] == tokenTypes["StartTag"]:
raw = token["data"]
data = attributeMap(raw)
if len(raw) > len(data):
# we had some duplicated attribute, fix so first wins
data.update(raw[::-1])
token["data"] = data
if token["type"] == tokenTypes["EndTag"]:
if token["data"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "attributes-in-end-tag"})
if token["selfClosing"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "self-closing-flag-on-end-tag"})
self.tokenQueue.append(token)
self.state = self.dataState
# Below are the various tokenizer states worked out.
def dataState(self):
data = self.stream.char()
if data == "&":
self.state = self.entityDataState
elif data == "<":
self.state = self.tagOpenState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\u0000"})
elif data is EOF:
# Tokenization ends.
return False
elif data in spaceCharacters:
# Directly after emitting a token you switch back to the "data
# state". At that point spaceCharacters are important so they are
# emitted separately.
self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data":
data + self.stream.charsUntil(spaceCharacters, True)})
# No need to update lastFourChars here, since the first space will
# have already been appended to lastFourChars and will have broken
# any <!-- or --> sequences
else:
chars = self.stream.charsUntil(("&", "<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def entityDataState(self):
self.consumeEntity()
self.state = self.dataState
return True
def rcdataState(self):
data = self.stream.char()
if data == "&":
self.state = self.characterReferenceInRcdata
elif data == "<":
self.state = self.rcdataLessThanSignState
elif data == EOF:
# Tokenization ends.
return False
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data in spaceCharacters:
# Directly after emitting a token you switch back to the "data
# state". At that point spaceCharacters are important so they are
# emitted separately.
self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data":
data + self.stream.charsUntil(spaceCharacters, True)})
# No need to update lastFourChars here, since the first space will
# have already been appended to lastFourChars and will have broken
# any <!-- or --> sequences
else:
chars = self.stream.charsUntil(("&", "<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def characterReferenceInRcdata(self):
self.consumeEntity()
self.state = self.rcdataState
return True
def rawtextState(self):
data = self.stream.char()
if data == "<":
self.state = self.rawtextLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
# Tokenization ends.
return False
else:
chars = self.stream.charsUntil(("<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def scriptDataState(self):
data = self.stream.char()
if data == "<":
self.state = self.scriptDataLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
# Tokenization ends.
return False
else:
chars = self.stream.charsUntil(("<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def plaintextState(self):
data = self.stream.char()
if data == EOF:
# Tokenization ends.
return False
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + self.stream.charsUntil("\u0000")})
return True
def tagOpenState(self):
data = self.stream.char()
if data == "!":
self.state = self.markupDeclarationOpenState
elif data == "/":
self.state = self.closeTagOpenState
elif data in asciiLetters:
self.currentToken = {"type": tokenTypes["StartTag"],
"name": data, "data": [],
"selfClosing": False,
"selfClosingAcknowledged": False}
self.state = self.tagNameState
elif data == ">":
# XXX In theory it could be something besides a tag name. But
# do we really care?
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name-but-got-right-bracket"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"})
self.state = self.dataState
elif data == "?":
# XXX In theory it could be something besides a tag name. But
# do we really care?
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name-but-got-question-mark"})
self.stream.unget(data)
self.state = self.bogusCommentState
else:
# XXX
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.dataState
return True
def closeTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.currentToken = {"type": tokenTypes["EndTag"], "name": data,
"data": [], "selfClosing": False}
self.state = self.tagNameState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-right-bracket"})
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-eof"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.state = self.dataState
else:
# XXX data can be _'_...
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-char",
"datavars": {"data": data}})
self.stream.unget(data)
self.state = self.bogusCommentState
return True
def tagNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == ">":
self.emitCurrentToken()
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-tag-name"})
self.state = self.dataState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] += "\uFFFD"
else:
self.currentToken["name"] += data
# (Don't use charsUntil here, because tag names are
# very short and it's faster to not do anything fancy)
return True
def rcdataLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.rcdataEndTagOpenState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rcdataEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.rcdataEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rcdataEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rawtextLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.rawtextEndTagOpenState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.rawtextState
return True
def rawtextEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.rawtextEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.rawtextState
return True
def rawtextEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.rawtextState
return True
def scriptDataLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.scriptDataEndTagOpenState
elif data == "!":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<!"})
self.state = self.scriptDataEscapeStartState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.scriptDataEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapeStartState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapeStartDashState
else:
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapeStartDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashDashState
else:
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapedState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashState
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
self.state = self.dataState
else:
chars = self.stream.charsUntil(("<", "-", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def scriptDataEscapedDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashDashState
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataEscapedState
elif data == EOF:
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedDashDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"})
self.state = self.scriptDataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataEscapedState
elif data == EOF:
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.scriptDataEscapedEndTagOpenState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data})
self.temporaryBuffer = data
self.state = self.scriptDataDoubleEscapeStartState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer = data
self.state = self.scriptDataEscapedEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataDoubleEscapeStartState(self):
data = self.stream.char()
if data in (spaceCharacters | frozenset(("/", ">"))):
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
if self.temporaryBuffer.lower() == "script":
self.state = self.scriptDataDoubleEscapedState
else:
self.state = self.scriptDataEscapedState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.temporaryBuffer += data
else:
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataDoubleEscapedState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataDoubleEscapedDashState
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
return True
def scriptDataDoubleEscapedDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataDoubleEscapedDashDashState
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataDoubleEscapedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapedDashDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"})
self.state = self.scriptDataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataDoubleEscapedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapedLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"})
self.temporaryBuffer = ""
self.state = self.scriptDataDoubleEscapeEndState
else:
self.stream.unget(data)
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapeEndState(self):
data = self.stream.char()
if data in (spaceCharacters | frozenset(("/", ">"))):
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
if self.temporaryBuffer.lower() == "script":
self.state = self.scriptDataEscapedState
else:
self.state = self.scriptDataDoubleEscapedState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.temporaryBuffer += data
else:
self.stream.unget(data)
self.state = self.scriptDataDoubleEscapedState
return True
def beforeAttributeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data in asciiLetters:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == ">":
self.emitCurrentToken()
elif data == "/":
self.state = self.selfClosingStartTagState
elif data in ("'", '"', "=", "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"invalid-character-in-attribute-name"})
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"].append(["\uFFFD", ""])
self.state = self.attributeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-name-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
return True
def attributeNameState(self):
data = self.stream.char()
leavingThisState = True
emitToken = False
if data == "=":
self.state = self.beforeAttributeValueState
elif data in asciiLetters:
self.currentToken["data"][-1][0] += data +\
self.stream.charsUntil(asciiLetters, True)
leavingThisState = False
elif data == ">":
# XXX If we emit here the attributes are converted to a dict
# without being checked and when the code below runs we error
# because data is a dict not a list
emitToken = True
elif data in spaceCharacters:
self.state = self.afterAttributeNameState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][0] += "\uFFFD"
leavingThisState = False
elif data in ("'", '"', "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"invalid-character-in-attribute-name"})
self.currentToken["data"][-1][0] += data
leavingThisState = False
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "eof-in-attribute-name"})
self.state = self.dataState
else:
self.currentToken["data"][-1][0] += data
leavingThisState = False
if leavingThisState:
# Attributes are not dropped at this stage. That happens when the
# start tag token is emitted so values can still be safely appended
# to attributes, but we do want to report the parse error in time.
self.currentToken["data"][-1][0] = (
self.currentToken["data"][-1][0].translate(asciiUpper2Lower))
for name, _ in self.currentToken["data"][:-1]:
if self.currentToken["data"][-1][0] == name:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"duplicate-attribute"})
break
# XXX Fix for above XXX
if emitToken:
self.emitCurrentToken()
return True
def afterAttributeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data == "=":
self.state = self.beforeAttributeValueState
elif data == ">":
self.emitCurrentToken()
elif data in asciiLetters:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"].append(["\uFFFD", ""])
self.state = self.attributeNameState
elif data in ("'", '"', "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"invalid-character-after-attribute-name"})
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-end-of-tag-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
return True
def beforeAttributeValueState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data == "\"":
self.state = self.attributeValueDoubleQuotedState
elif data == "&":
self.state = self.attributeValueUnQuotedState
self.stream.unget(data)
elif data == "'":
self.state = self.attributeValueSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-value-but-got-right-bracket"})
self.emitCurrentToken()
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
self.state = self.attributeValueUnQuotedState
elif data in ("=", "<", "`"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"equals-in-unquoted-attribute-value"})
self.currentToken["data"][-1][1] += data
self.state = self.attributeValueUnQuotedState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-value-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data
self.state = self.attributeValueUnQuotedState
return True
def attributeValueDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterAttributeValueState
elif data == "&":
self.processEntityInAttribute('"')
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-double-quote"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data +\
self.stream.charsUntil(("\"", "&", "\u0000"))
return True
def attributeValueSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterAttributeValueState
elif data == "&":
self.processEntityInAttribute("'")
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-single-quote"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data +\
self.stream.charsUntil(("'", "&", "\u0000"))
return True
def attributeValueUnQuotedState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == "&":
self.processEntityInAttribute(">")
elif data == ">":
self.emitCurrentToken()
elif data in ('"', "'", "=", "<", "`"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-in-unquoted-attribute-value"})
self.currentToken["data"][-1][1] += data
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-no-quotes"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data + self.stream.charsUntil(
frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters)
return True
def afterAttributeValueState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == ">":
self.emitCurrentToken()
elif data == "/":
self.state = self.selfClosingStartTagState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-EOF-after-attribute-value"})
self.stream.unget(data)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-after-attribute-value"})
self.stream.unget(data)
self.state = self.beforeAttributeNameState
return True
def selfClosingStartTagState(self):
data = self.stream.char()
if data == ">":
self.currentToken["selfClosing"] = True
self.emitCurrentToken()
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"unexpected-EOF-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.beforeAttributeNameState
return True
def bogusCommentState(self):
# Make a new comment token and give it as value all the characters
# until the first > or EOF (charsUntil checks for EOF automatically)
# and emit it.
data = self.stream.charsUntil(">")
data = data.replace("\u0000", "\uFFFD")
self.tokenQueue.append(
{"type": tokenTypes["Comment"], "data": data})
# Eat the character directly after the bogus comment which is either a
# ">" or an EOF.
self.stream.char()
self.state = self.dataState
return True
def markupDeclarationOpenState(self):
charStack = [self.stream.char()]
if charStack[-1] == "-":
charStack.append(self.stream.char())
if charStack[-1] == "-":
self.currentToken = {"type": tokenTypes["Comment"], "data": ""}
self.state = self.commentStartState
return True
elif charStack[-1] in ('d', 'D'):
matched = True
for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'),
('y', 'Y'), ('p', 'P'), ('e', 'E')):
charStack.append(self.stream.char())
if charStack[-1] not in expected:
matched = False
break
if matched:
self.currentToken = {"type": tokenTypes["Doctype"],
"name": "",
"publicId": None, "systemId": None,
"correct": True}
self.state = self.doctypeState
return True
elif (charStack[-1] == "[" and
self.parser is not None and
self.parser.tree.openElements and
self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace):
matched = True
for expected in ["C", "D", "A", "T", "A", "["]:
charStack.append(self.stream.char())
if charStack[-1] != expected:
matched = False
break
if matched:
self.state = self.cdataSectionState
return True
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-dashes-or-doctype"})
while charStack:
self.stream.unget(charStack.pop())
self.state = self.bogusCommentState
return True
def commentStartState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentStartDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"incorrect-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += data
self.state = self.commentState
return True
def commentStartDashState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "-\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"incorrect-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "-" + data
self.state = self.commentState
return True
def commentState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += data + \
self.stream.charsUntil(("-", "\u0000"))
return True
def commentEndDashState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "-\uFFFD"
self.state = self.commentState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-end-dash"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "-" + data
self.state = self.commentState
return True
def commentEndState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "--\uFFFD"
self.state = self.commentState
elif data == "!":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-bang-after-double-dash-in-comment"})
self.state = self.commentEndBangState
elif data == "-":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-dash-after-double-dash-in-comment"})
self.currentToken["data"] += data
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-double-dash"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
# XXX
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-comment"})
self.currentToken["data"] += "--" + data
self.state = self.commentState
return True
def commentEndBangState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "-":
self.currentToken["data"] += "--!"
self.state = self.commentEndDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "--!\uFFFD"
self.state = self.commentState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-end-bang-state"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "--!" + data
self.state = self.commentState
return True
def doctypeState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-eof"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"need-space-after-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypeNameState
return True
def beforeDoctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-right-bracket"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] = "\uFFFD"
self.state = self.doctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-eof"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["name"] = data
self.state = self.doctypeNameState
return True
def doctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.state = self.afterDoctypeNameState
elif data == ">":
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] += "\uFFFD"
self.state = self.doctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype-name"})
self.currentToken["correct"] = False
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["name"] += data
return True
def afterDoctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.currentToken["correct"] = False
self.stream.unget(data)
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
if data in ("p", "P"):
matched = True
for expected in (("u", "U"), ("b", "B"), ("l", "L"),
("i", "I"), ("c", "C")):
data = self.stream.char()
if data not in expected:
matched = False
break
if matched:
self.state = self.afterDoctypePublicKeywordState
return True
elif data in ("s", "S"):
matched = True
for expected in (("y", "Y"), ("s", "S"), ("t", "T"),
("e", "E"), ("m", "M")):
data = self.stream.char()
if data not in expected:
matched = False
break
if matched:
self.state = self.afterDoctypeSystemKeywordState
return True
# All the characters read before the current 'data' will be
# [a-zA-Z], so they're garbage in the bogus doctype and can be
# discarded; only the latest character might be '>' or EOF
# and needs to be ungetted
self.stream.unget(data)
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-space-or-right-bracket-in-doctype", "datavars":
{"data": data}})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def afterDoctypePublicKeywordState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypePublicIdentifierState
elif data in ("'", '"'):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypePublicIdentifierState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.stream.unget(data)
self.state = self.beforeDoctypePublicIdentifierState
return True
def beforeDoctypePublicIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == "\"":
self.currentToken["publicId"] = ""
self.state = self.doctypePublicIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["publicId"] = ""
self.state = self.doctypePublicIdentifierSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def doctypePublicIdentifierDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterDoctypePublicIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["publicId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["publicId"] += data
return True
def doctypePublicIdentifierSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterDoctypePublicIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["publicId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["publicId"] += data
return True
def afterDoctypePublicIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.betweenDoctypePublicAndSystemIdentifiersState
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == '"':
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def betweenDoctypePublicAndSystemIdentifiersState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == '"':
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def afterDoctypeSystemKeywordState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypeSystemIdentifierState
elif data in ("'", '"'):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypeSystemIdentifierState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.stream.unget(data)
self.state = self.beforeDoctypeSystemIdentifierState
return True
def beforeDoctypeSystemIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == "\"":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def doctypeSystemIdentifierDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterDoctypeSystemIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["systemId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["systemId"] += data
return True
def doctypeSystemIdentifierSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterDoctypeSystemIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["systemId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["systemId"] += data
return True
def afterDoctypeSystemIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.state = self.bogusDoctypeState
return True
def bogusDoctypeState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
# XXX EMIT
self.stream.unget(data)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
pass
return True
def cdataSectionState(self):
data = []
while True:
data.append(self.stream.charsUntil("]"))
data.append(self.stream.charsUntil(">"))
char = self.stream.char()
if char == EOF:
break
else:
assert char == ">"
if data[-1][-2:] == "]]":
data[-1] = data[-1][:-2]
break
else:
data.append(char)
data = "".join(data) # pylint:disable=redefined-variable-type
# Deal with null here rather than in the parser
nullCount = data.count("\u0000")
if nullCount > 0:
for _ in range(nullCount):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
data = data.replace("\u0000", "\uFFFD")
if data:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": data})
self.state = self.dataState
return True
| HTMLTokenizer |
python | kubernetes-client__python | kubernetes/client/models/v1_device_attribute.py | {
"start": 383,
"end": 5816
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'bool': 'bool',
'int': 'int',
'string': 'str',
'version': 'str'
}
attribute_map = {
'bool': 'bool',
'int': 'int',
'string': 'string',
'version': 'version'
}
def __init__(self, bool=None, int=None, string=None, version=None, local_vars_configuration=None): # noqa: E501
"""V1DeviceAttribute - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._bool = None
self._int = None
self._string = None
self._version = None
self.discriminator = None
if bool is not None:
self.bool = bool
if int is not None:
self.int = int
if string is not None:
self.string = string
if version is not None:
self.version = version
@property
def bool(self):
"""Gets the bool of this V1DeviceAttribute. # noqa: E501
BoolValue is a true/false value. # noqa: E501
:return: The bool of this V1DeviceAttribute. # noqa: E501
:rtype: bool
"""
return self._bool
@bool.setter
def bool(self, bool):
"""Sets the bool of this V1DeviceAttribute.
BoolValue is a true/false value. # noqa: E501
:param bool: The bool of this V1DeviceAttribute. # noqa: E501
:type: bool
"""
self._bool = bool
@property
def int(self):
"""Gets the int of this V1DeviceAttribute. # noqa: E501
IntValue is a number. # noqa: E501
:return: The int of this V1DeviceAttribute. # noqa: E501
:rtype: int
"""
return self._int
@int.setter
def int(self, int):
"""Sets the int of this V1DeviceAttribute.
IntValue is a number. # noqa: E501
:param int: The int of this V1DeviceAttribute. # noqa: E501
:type: int
"""
self._int = int
@property
def string(self):
"""Gets the string of this V1DeviceAttribute. # noqa: E501
StringValue is a string. Must not be longer than 64 characters. # noqa: E501
:return: The string of this V1DeviceAttribute. # noqa: E501
:rtype: str
"""
return self._string
@string.setter
def string(self, string):
"""Sets the string of this V1DeviceAttribute.
StringValue is a string. Must not be longer than 64 characters. # noqa: E501
:param string: The string of this V1DeviceAttribute. # noqa: E501
:type: str
"""
self._string = string
@property
def version(self):
"""Gets the version of this V1DeviceAttribute. # noqa: E501
VersionValue is a semantic version according to semver.org spec 2.0.0. Must not be longer than 64 characters. # noqa: E501
:return: The version of this V1DeviceAttribute. # noqa: E501
:rtype: str
"""
return self._version
@version.setter
def version(self, version):
"""Sets the version of this V1DeviceAttribute.
VersionValue is a semantic version according to semver.org spec 2.0.0. Must not be longer than 64 characters. # noqa: E501
:param version: The version of this V1DeviceAttribute. # noqa: E501
:type: str
"""
self._version = version
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1DeviceAttribute):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1DeviceAttribute):
return True
return self.to_dict() != other.to_dict()
| V1DeviceAttribute |
python | pypa__setuptools | setuptools/tests/test_build_ext.py | {
"start": 6669,
"end": 10099
} | class ____:
def get_build_ext_cmd(self, optional: bool, **opts) -> build_ext:
files: dict[str, str | dict[str, dict[str, str]]] = {
"eggs.c": "#include missingheader.h\n",
".build": {"lib": {}, "tmp": {}},
}
path.build(files)
extension = Extension('spam.eggs', ['eggs.c'], optional=optional)
dist = Distribution(dict(ext_modules=[extension]))
dist.script_name = 'setup.py'
cmd = build_ext(dist)
vars(cmd).update(build_lib=".build/lib", build_temp=".build/tmp", **opts)
cmd.ensure_finalized()
return cmd
def get_log_messages(self, caplog, capsys):
"""
Historically, distutils "logged" by printing to sys.std*.
Later versions adopted the logging framework. Grab
messages regardless of how they were captured.
"""
std = capsys.readouterr()
return std.out.splitlines() + std.err.splitlines() + caplog.messages
def test_optional(self, tmpdir_cwd, caplog, capsys):
"""
If optional extensions fail to build, setuptools should show the error
in the logs but not fail to build
"""
cmd = self.get_build_ext_cmd(optional=True, inplace=True)
cmd.run()
assert any(
'build_ext: building extension "spam.eggs" failed'
for msg in self.get_log_messages(caplog, capsys)
)
# No compile error exception should be raised
def test_non_optional(self, tmpdir_cwd):
# Non-optional extensions should raise an exception
cmd = self.get_build_ext_cmd(optional=False, inplace=True)
with pytest.raises(CompileError):
cmd.run()
def test_build_ext_config_handling(tmpdir_cwd):
files = {
'setup.py': DALS(
"""
from setuptools import Extension, setup
setup(
name='foo',
version='0.0.0',
ext_modules=[Extension('foo', ['foo.c'])],
)
"""
),
'foo.c': DALS(
"""
#include "Python.h"
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"foo",
NULL,
0,
NULL,
NULL,
NULL,
NULL,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit_foo(void)
#else
#define INITERROR return
void initfoo(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("extension", NULL);
#endif
if (module == NULL)
INITERROR;
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
"""
),
'setup.cfg': DALS(
"""
[build]
build_base = foo_build
"""
),
}
path.build(files)
code, (stdout, stderr) = environment.run_setup_py(
cmd=['build'],
data_stream=(0, 2),
)
assert code == 0, f'\nSTDOUT:\n{stdout}\nSTDERR:\n{stderr}'
| TestBuildExtInplace |
python | ipython__ipython | tests/test_guarded_eval.py | {
"start": 8134,
"end": 8188
} | class ____(TypedDict):
name: str
year: int
| Movie |
python | streamlit__streamlit | lib/streamlit/web/server/app_static_file_handler.py | {
"start": 1504,
"end": 3224
} | class ____(tornado.web.StaticFileHandler):
def initialize(self, path: str, default_filename: str | None = None) -> None:
super().initialize(path, default_filename)
def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:
full_path = os.path.abspath(absolute_path)
ret_val = super().validate_absolute_path(root, absolute_path)
if os.path.isdir(full_path):
# we don't want to serve directories, and serve only files
raise tornado.web.HTTPError(404)
if os.path.commonpath([full_path, root]) != root:
# Don't allow misbehaving clients to break out of the static files directory
_LOGGER.warning(
"Serving files outside of the static directory is not supported"
)
raise tornado.web.HTTPError(404)
if (
os.path.exists(full_path)
and os.path.getsize(full_path) > MAX_APP_STATIC_FILE_SIZE
):
raise tornado.web.HTTPError(
404,
"File is too large, its size should not exceed "
f"{MAX_APP_STATIC_FILE_SIZE} bytes",
reason="File is too large",
)
return ret_val
def set_default_headers(self) -> None:
# CORS protection is disabled because we need access to this endpoint
# from the inner iframe.
self.set_header("Access-Control-Allow-Origin", "*")
def set_extra_headers(self, path: str) -> None:
if Path(path).suffix not in SAFE_APP_STATIC_FILE_EXTENSIONS:
self.set_header("Content-Type", "text/plain")
self.set_header("X-Content-Type-Options", "nosniff")
| AppStaticFileHandler |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 7997,
"end": 25386
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
self.raw_es = elasticsearch.Elasticsearch(
settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"]
)
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = ElasticSearchMockUnifiedIndex()
self.smmi = ElasticsearchMockSearchIndex()
self.smmidni = ElasticsearchMockSearchIndexWithSkipDocument()
self.smtmmi = ElasticsearchMaintainTypeMockSearchIndex()
self.ui.build(indexes=[self.smmi])
connections["elasticsearch"]._index = self.ui
self.sb = connections["elasticsearch"].get_backend()
# Force the backend to rebuild the mapping each time.
self.sb.existing_mapping = {}
self.sb.setup()
self.sample_objs = []
for i in range(1, 4):
mock = MockModel()
mock.id = i
mock.author = "daniel%s" % i
mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i)
self.sample_objs.append(mock)
def tearDown(self):
connections["elasticsearch"]._index = self.old_ui
super().tearDown()
self.sb.silently_fail = True
def raw_search(self, query):
try:
return self.raw_es.search(
q="*:*",
index=settings.HAYSTACK_CONNECTIONS["elasticsearch"]["INDEX_NAME"],
)
except elasticsearch.TransportError:
return {}
def test_non_silent(self):
bad_sb = connections["elasticsearch"].backend(
"bad",
URL="http://omg.wtf.bbq:1000/",
INDEX_NAME="whatver",
SILENTLY_FAIL=False,
TIMEOUT=1,
)
try:
bad_sb.update(self.smmi, self.sample_objs)
self.fail()
except:
pass
try:
bad_sb.remove("core.mockmodel.1")
self.fail()
except:
pass
try:
bad_sb.clear()
self.fail()
except:
pass
try:
bad_sb.search("foo")
self.fail()
except:
pass
def test_update_no_documents(self):
url = settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"]
index_name = settings.HAYSTACK_CONNECTIONS["elasticsearch"]["INDEX_NAME"]
sb = connections["elasticsearch"].backend(
"elasticsearch", URL=url, INDEX_NAME=index_name, SILENTLY_FAIL=True
)
self.assertEqual(sb.update(self.smmi, []), None)
sb = connections["elasticsearch"].backend(
"elasticsearch", URL=url, INDEX_NAME=index_name, SILENTLY_FAIL=False
)
try:
sb.update(self.smmi, [])
self.fail()
except:
pass
def test_update(self):
self.sb.update(self.smmi, self.sample_objs)
# Check what Elasticsearch thinks is there.
self.assertEqual(self.raw_search("*:*")["hits"]["total"], 3)
self.assertEqual(
sorted(
[res["_source"] for res in self.raw_search("*:*")["hits"]["hits"]],
key=lambda x: x["id"],
),
[
{
"django_id": "1",
"django_ct": "core.mockmodel",
"name": "daniel1",
"name_exact": "daniel1",
"text": "Indexed!\n1\n",
"pub_date": "2009-02-24T00:00:00",
"id": "core.mockmodel.1",
},
{
"django_id": "2",
"django_ct": "core.mockmodel",
"name": "daniel2",
"name_exact": "daniel2",
"text": "Indexed!\n2\n",
"pub_date": "2009-02-23T00:00:00",
"id": "core.mockmodel.2",
},
{
"django_id": "3",
"django_ct": "core.mockmodel",
"name": "daniel3",
"name_exact": "daniel3",
"text": "Indexed!\n3\n",
"pub_date": "2009-02-22T00:00:00",
"id": "core.mockmodel.3",
},
],
)
def test_update_with_SkipDocument_raised(self):
self.sb.update(self.smmidni, self.sample_objs)
# Check what Elasticsearch thinks is there.
res = self.raw_search("*:*")["hits"]
self.assertEqual(res["total"], 2)
self.assertListEqual(
sorted([x["_source"]["id"] for x in res["hits"]]),
["core.mockmodel.1", "core.mockmodel.2"],
)
def test_remove(self):
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*")["hits"]["total"], 3)
self.sb.remove(self.sample_objs[0])
self.assertEqual(self.raw_search("*:*")["hits"]["total"], 2)
self.assertEqual(
sorted(
[res["_source"] for res in self.raw_search("*:*")["hits"]["hits"]],
key=operator.itemgetter("django_id"),
),
[
{
"django_id": "2",
"django_ct": "core.mockmodel",
"name": "daniel2",
"name_exact": "daniel2",
"text": "Indexed!\n2\n",
"pub_date": "2009-02-23T00:00:00",
"id": "core.mockmodel.2",
},
{
"django_id": "3",
"django_ct": "core.mockmodel",
"name": "daniel3",
"name_exact": "daniel3",
"text": "Indexed!\n3\n",
"pub_date": "2009-02-22T00:00:00",
"id": "core.mockmodel.3",
},
],
)
def test_remove_succeeds_on_404(self):
self.sb.silently_fail = False
self.sb.remove("core.mockmodel.421")
def test_clear(self):
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 3)
self.sb.clear()
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 0)
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 3)
self.sb.clear([AnotherMockModel])
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 3)
self.sb.clear([MockModel])
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 0)
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 3)
self.sb.clear([AnotherMockModel, MockModel])
self.assertEqual(self.raw_search("*:*").get("hits", {}).get("total", 0), 0)
def test_results_ask_for_index_per_entry(self):
# Test that index class is obtained per result entry, not per every entry field
self.sb.update(self.smmi, self.sample_objs)
with self.ui.spy() as spy:
self.sb.search("*:*", limit_to_registered_models=False)
self.assertEqual(len(spy.get("get_index", [])), len(self.sample_objs))
def test_search(self):
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*")["hits"]["total"], 3)
self.assertEqual(self.sb.search(""), {"hits": 0, "results": []})
self.assertEqual(self.sb.search("*:*")["hits"], 3)
self.assertEqual(
set([result.pk for result in self.sb.search("*:*")["results"]]),
set(["2", "1", "3"]),
)
self.assertEqual(self.sb.search("", highlight=True), {"hits": 0, "results": []})
self.assertEqual(self.sb.search("Index", highlight=True)["hits"], 3)
self.assertEqual(
sorted(
[
result.highlighted[0]
for result in self.sb.search("Index", highlight=True)["results"]
]
),
[
"<em>Indexed</em>!\n1\n",
"<em>Indexed</em>!\n2\n",
"<em>Indexed</em>!\n3\n",
],
)
self.assertEqual(
sorted(
[
result.highlighted[0]
for result in self.sb.search(
"Index",
highlight={"pre_tags": ["<start>"], "post_tags": ["</end>"]},
)["results"]
]
),
[
"<start>Indexed</end>!\n1\n",
"<start>Indexed</end>!\n2\n",
"<start>Indexed</end>!\n3\n",
],
)
self.assertEqual(self.sb.search("Indx")["hits"], 0)
self.assertEqual(self.sb.search("indaxed")["spelling_suggestion"], "indexed")
self.assertEqual(
self.sb.search("arf", spelling_query="indexyd")["spelling_suggestion"],
"indexed",
)
self.assertEqual(
self.sb.search("", facets={"name": {}}), {"hits": 0, "results": []}
)
results = self.sb.search("Index", facets={"name": {}})
self.assertEqual(results["hits"], 3)
self.assertEqual(
results["facets"]["fields"]["name"],
[("daniel3", 1), ("daniel2", 1), ("daniel1", 1)],
)
self.assertEqual(
self.sb.search(
"",
date_facets={
"pub_date": {
"start_date": datetime.date(2008, 1, 1),
"end_date": datetime.date(2009, 4, 1),
"gap_by": "month",
"gap_amount": 1,
}
},
),
{"hits": 0, "results": []},
)
results = self.sb.search(
"Index",
date_facets={
"pub_date": {
"start_date": datetime.date(2008, 1, 1),
"end_date": datetime.date(2009, 4, 1),
"gap_by": "month",
"gap_amount": 1,
}
},
)
self.assertEqual(results["hits"], 3)
self.assertEqual(
results["facets"]["dates"]["pub_date"],
[(datetime.datetime(2009, 2, 1, 0, 0), 3)],
)
self.assertEqual(
self.sb.search("", query_facets=[("name", "[* TO e]")]),
{"hits": 0, "results": []},
)
results = self.sb.search("Index", query_facets=[("name", "[* TO e]")])
self.assertEqual(results["hits"], 3)
self.assertEqual(results["facets"]["queries"], {"name": 3})
self.assertEqual(
self.sb.search("", narrow_queries=set(["name:daniel1"])),
{"hits": 0, "results": []},
)
results = self.sb.search("Index", narrow_queries=set(["name:daniel1"]))
self.assertEqual(results["hits"], 1)
# Ensure that swapping the ``result_class`` works.
self.assertTrue(
isinstance(
self.sb.search("index", result_class=MockSearchResult)["results"][0],
MockSearchResult,
)
)
# Check the use of ``limit_to_registered_models``.
self.assertEqual(
self.sb.search("", limit_to_registered_models=False),
{"hits": 0, "results": []},
)
self.assertEqual(
self.sb.search("*:*", limit_to_registered_models=False)["hits"], 3
)
self.assertEqual(
sorted(
[
result.pk
for result in self.sb.search(
"*:*", limit_to_registered_models=False
)["results"]
]
),
["1", "2", "3"],
)
# Stow.
old_limit_to_registered_models = getattr(
settings, "HAYSTACK_LIMIT_TO_REGISTERED_MODELS", True
)
settings.HAYSTACK_LIMIT_TO_REGISTERED_MODELS = False
self.assertEqual(self.sb.search(""), {"hits": 0, "results": []})
self.assertEqual(self.sb.search("*:*")["hits"], 3)
self.assertEqual(
sorted([result.pk for result in self.sb.search("*:*")["results"]]),
["1", "2", "3"],
)
# Restore.
settings.HAYSTACK_LIMIT_TO_REGISTERED_MODELS = old_limit_to_registered_models
def test_spatial_search_parameters(self):
from django.contrib.gis.geos import Point
p1 = Point(1.23, 4.56)
kwargs = self.sb.build_search_kwargs(
"*:*",
distance_point={"field": "location", "point": p1},
sort_by=(("distance", "desc"),),
)
self.assertIn("sort", kwargs)
self.assertEqual(1, len(kwargs["sort"]))
geo_d = kwargs["sort"][0]["_geo_distance"]
# ElasticSearch supports the GeoJSON-style lng, lat pairs so unlike Solr the values should be
# in the same order as we used to create the Point():
# http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-geo-distance-filter.html#_lat_lon_as_array_4
self.assertDictEqual(
geo_d, {"location": [1.23, 4.56], "unit": "km", "order": "desc"}
)
def test_more_like_this(self):
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(self.raw_search("*:*")["hits"]["total"], 3)
# A functional MLT example with enough data to work is below. Rely on
# this to ensure the API is correct enough.
self.assertEqual(self.sb.more_like_this(self.sample_objs[0])["hits"], 0)
self.assertEqual(
[
result.pk
for result in self.sb.more_like_this(self.sample_objs[0])["results"]
],
[],
)
def test_build_schema(self):
old_ui = connections["elasticsearch"].get_unified_index()
(content_field_name, mapping) = self.sb.build_schema(old_ui.all_searchfields())
self.assertEqual(content_field_name, "text")
self.assertEqual(len(mapping), 4 + 2) # +2 management fields
self.assertEqual(
mapping,
{
"django_id": {
"index": "not_analyzed",
"type": "string",
"include_in_all": False,
},
"django_ct": {
"index": "not_analyzed",
"type": "string",
"include_in_all": False,
},
"text": {"type": "string", "analyzer": "snowball"},
"pub_date": {"type": "date"},
"name": {"type": "string", "analyzer": "snowball"},
"name_exact": {"index": "not_analyzed", "type": "string"},
},
)
ui = UnifiedIndex()
ui.build(indexes=[ElasticsearchComplexFacetsMockSearchIndex()])
(content_field_name, mapping) = self.sb.build_schema(ui.all_searchfields())
self.assertEqual(content_field_name, "text")
self.assertEqual(len(mapping), 15 + 2) # +2 management fields
self.assertEqual(
mapping,
{
"django_id": {
"index": "not_analyzed",
"type": "string",
"include_in_all": False,
},
"django_ct": {
"index": "not_analyzed",
"type": "string",
"include_in_all": False,
},
"name": {"type": "string", "analyzer": "snowball"},
"is_active_exact": {"type": "boolean"},
"created": {"type": "date"},
"post_count": {"type": "long"},
"created_exact": {"type": "date"},
"sites_exact": {"index": "not_analyzed", "type": "string"},
"is_active": {"type": "boolean"},
"sites": {"type": "string", "analyzer": "snowball"},
"post_count_i": {"type": "long"},
"average_rating": {"type": "float"},
"text": {"type": "string", "analyzer": "snowball"},
"pub_date_exact": {"type": "date"},
"name_exact": {"index": "not_analyzed", "type": "string"},
"pub_date": {"type": "date"},
"average_rating_exact": {"type": "float"},
},
)
def test_verify_type(self):
old_ui = connections["elasticsearch"].get_unified_index()
ui = UnifiedIndex()
smtmmi = ElasticsearchMaintainTypeMockSearchIndex()
ui.build(indexes=[smtmmi])
connections["elasticsearch"]._index = ui
sb = connections["elasticsearch"].get_backend()
sb.update(smtmmi, self.sample_objs)
self.assertEqual(sb.search("*:*")["hits"], 3)
self.assertEqual(
[result.month for result in sb.search("*:*")["results"]], ["02", "02", "02"]
)
connections["elasticsearch"]._index = old_ui
| ElasticsearchSearchBackendTestCase |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 12042,
"end": 14663
} | class ____(ManagedKafkaBaseOperator):
"""
Get an Apache Kafka cluster.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param cluster_id: Required. The ID of the cluster whose configuration to return.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = tuple({"cluster_id"} | set(ManagedKafkaBaseOperator.template_fields))
operator_extra_links = (ApacheKafkaClusterLink(),)
def __init__(
self,
cluster_id: str,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.cluster_id = cluster_id
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"location": self.location,
"cluster_id": self.cluster_id,
"project_id": self.project_id,
}
def execute(self, context: Context):
ApacheKafkaClusterLink.persist(context=context)
self.log.info("Getting Cluster: %s", self.cluster_id)
try:
cluster = self.hook.get_cluster(
project_id=self.project_id,
location=self.location,
cluster_id=self.cluster_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
self.log.info("Cluster was gotten.")
return types.Cluster.to_dict(cluster)
except NotFound as not_found_err:
self.log.info("The Cluster %s does not exist.", self.cluster_id)
raise AirflowException(not_found_err)
| ManagedKafkaGetClusterOperator |
python | anthropics__anthropic-sdk-python | src/anthropic/types/raw_content_block_delta_event.py | {
"start": 259,
"end": 393
} | class ____(BaseModel):
delta: RawContentBlockDelta
index: int
type: Literal["content_block_delta"]
| RawContentBlockDeltaEvent |
python | google__jax | jax/_src/source_info_util.py | {
"start": 6399,
"end": 6784
} | class ____(threading.local):
context: SourceInfo
def __init__(self):
self.context = new_source_info()
_source_info_context = _SourceInfoContext()
def current() -> SourceInfo:
source_info = _source_info_context.context
if not source_info.traceback:
source_info = source_info.replace(traceback=xla_client.Traceback.get_traceback())
return source_info
| _SourceInfoContext |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 10004,
"end": 10875
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
self.layer_1 = nn.Linear(config.d_model, config.d_inner)
self.layer_2 = nn.Linear(config.d_inner, config.d_model)
self.dropout = nn.Dropout(config.dropout)
if isinstance(config.ff_activation, str):
self.activation_function = ACT2FN[config.ff_activation]
else:
self.activation_function = config.ff_activation
def forward(self, inp):
output = inp
output = self.layer_1(output)
output = self.activation_function(output)
output = self.dropout(output)
output = self.layer_2(output)
output = self.dropout(output)
output = self.layer_norm(output + inp)
return output
| XLNetFeedForward |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 12538,
"end": 12862
} | class ____(
SerializedAttributes.with_attributes(
'MetricAttributes',
checkpointable_objects=['variables'],
functions=[],
)):
"""Attributes that are added to Metric objects when saved to SavedModel.
List of all attributes:
variables: list of all variables
"""
pass
| MetricAttributes |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_process_event.py | {
"start": 12535,
"end": 17650
} | class ____(BaseDeriveCodeMappings):
"""Behaviour that is not specific to a language."""
def test_skips_not_supported_platforms(self) -> None:
with patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}):
self._process_and_assert_configuration_changes(
repo_trees={}, frames=[{}], platform="other"
)
def test_handle_existing_code_mapping(self) -> None:
self.create_repo_and_code_mapping("repo", "foo/", "src/foo/")
# The platform & frames are irrelevant for this test
event = self.create_event([self.frame("foo/bar/baz.py", True)], "python")
assert event.group_id is not None
process_event(self.project.id, event.group_id, event.event_id)
all_cm = RepositoryProjectPathConfig.objects.all()
assert len(all_cm) == 1
assert all_cm[0].automatically_generated is False
def test_dry_run_platform(self) -> None:
frame_filename = "foo/bar.py"
file_in_repo = "src/foo/bar.py"
platform = "other"
with (
patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}),
patch(f"{CODE_ROOT}.utils.platform.PlatformConfig.is_supported", return_value=True),
patch(
f"{CODE_ROOT}.utils.platform.PlatformConfig.is_dry_run_platform", return_value=True
),
):
# No code mapping will be stored, however, we get what would have been created
self._process_and_assert_configuration_changes(
repo_trees={REPO1: [file_in_repo]},
frames=[self.frame(frame_filename, True)],
platform=platform,
expected_new_code_mappings=[self.code_mapping("foo/", "src/foo/")],
)
def test_extension_is_not_included(self) -> None:
frame_filename = "foo/bar.tbd"
file_in_repo = "src/foo/bar.tbd"
platform = "other"
self.event = self.create_event([{"filename": frame_filename, "in_app": True}], platform)
with (
patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}),
patch(f"{REPO_TREES_CODE}.get_supported_extensions", return_value=[]),
):
# No extensions are supported, thus, we won't generate a code mapping
self._process_and_assert_configuration_changes(
repo_trees={REPO1: [file_in_repo]},
frames=[self.frame(frame_filename, True)],
platform=platform,
)
def test_extension_is_included(self) -> None:
frame_filename = "foo/bar.tbd"
file_in_repo = "src/foo/bar.tbd"
platform = "other"
self.event = self.create_event([{"filename": frame_filename, "in_app": True}], platform)
with (
patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}),
patch(f"{REPO_TREES_CODE}.get_supported_extensions", return_value=["tbd"]),
):
self._process_and_assert_configuration_changes(
repo_trees={REPO1: [file_in_repo]},
frames=[self.frame(frame_filename, True)],
platform=platform,
expected_new_code_mappings=[self.code_mapping("foo/", "src/foo/")],
)
def test_multiple_calls(self) -> None:
platform = "other"
# XXX: We need a test for when repo_files changes over time
repo_trees = {
REPO1: ["src/foo/bar.py", "src/app/main.py"],
REPO2: ["app/baz/qux.py"],
}
with (
patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}),
patch(f"{CODE_ROOT}.utils.platform.PlatformConfig.is_supported", return_value=True),
):
self._process_and_assert_configuration_changes(
repo_trees=repo_trees,
frames=[self.frame("foo/bar.py", True)],
platform=platform,
expected_new_code_mappings=[self.code_mapping("foo/", "src/foo/")],
)
# Processing the same stacktrace again should not create anything new,
# thus, not passing in expected_new_code_mapping
self._process_and_assert_configuration_changes(
repo_trees=repo_trees, frames=[self.frame("foo/bar.py", True)], platform=platform
)
# New code mapping in the same repository
self._process_and_assert_configuration_changes(
repo_trees=repo_trees,
frames=[self.frame("app/main.py", True)],
platform=platform,
expected_new_code_mappings=[self.code_mapping("app/", "src/app/")],
)
# New code mapping in a different repository
self._process_and_assert_configuration_changes(
repo_trees=repo_trees,
frames=[self.frame("baz/qux.py", True)],
platform=platform,
expected_new_code_mappings=[self.code_mapping("baz/", "app/baz/", REPO2)],
)
| TestGenericBehaviour |
python | huggingface__transformers | src/transformers/models/voxtral/processing_voxtral.py | {
"start": 1956,
"end": 20004
} | class ____(ProcessorMixin):
r"""
Constructs a Voxtral processor which wraps [`WhisperFeatureExtractor`] and
[`MistralCommonBackend`] into a single processor that inherits both the audio feature extraction and
tokenizer functionalities.
Args:
feature_extractor ([`WhisperFeatureExtractor`]):
The feature extractor is a required input.
tokenizer ([`MistralCommonBackend`]):
The tokenizer is a required input.
"""
def __init__(
self,
feature_extractor,
tokenizer,
):
self.audio_token_id = 24
self.audio_token = tokenizer.convert_ids_to_tokens(self.audio_token_id)
super().__init__(feature_extractor, tokenizer)
def _retrieve_input_features(self, audio, max_source_positions, **kwargs):
"""
Handles specific logic of Voxtral expected input features: audio arrays should be padded to next multiple of 480000 (duration is a multiple of 30s), see VoxtralProcessorKwargs' default audio_kwargs.
Then mel input features are extracted and stacked along batch dimension, splitting into chunks of max_source_positions.
"""
input_features_list = []
for audio_array in audio:
audio_inputs = self.feature_extractor(audio_array, **kwargs)
# let's split into chunks of max_source_positions, and then stack them along batch dimension
input_features = audio_inputs["input_features"].reshape(
self.feature_extractor.feature_size, -1, max_source_positions
)
input_features_list.append(input_features.transpose(0, 1))
return torch.cat(input_features_list)
def apply_chat_template(
self,
conversation: Union[list[dict[str, str]], list[list[dict[str, str]]]],
**kwargs: Unpack[AllKwargsForChatTemplate],
) -> str:
"""
This method applies the model's chat completion template given a conversation. It relies on MistralCommonBackend's
[`~MistralCommonBackend.apply_chat_template`] to prepare input ids to the model and on WhisperFeatureExtractor's
[`~WhisperFeatureExtractor.__call__`] to prepare input features to the model.
Note that audio is padded to the nearest 30-second multiple prior to mel feature extraction.
A `conversation` is a list of messages, where each message is a dictionary with a `role` and a `content` field.
For Voxtral, `role` can be `"user"` or `"assistant"`.
The `content` field can be a string or a list of dictionaries with a `type` field. See example below.
```python
from huggingface_hub import hf_hub_download
from transformers.audio_utils import load_audio_as
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3"
audio_path = hf_hub_download(repo_id="hf-internal-testing/dummy-audio-samples", filename="bcn_weather.mp3", repo_type="dataset")
audio_base64 = load_audio_as(audio_path, return_format="base64", force_mono=True)
# audio + text
conversation = [
{
"role": "user",
"content": [
{"type": "audio", "url": audio_url},
{"type": "audio", "path": audio_path},
{"type": "audio", "base64": audio_base64},
{"type": "text", "text": "How many audio do you hear?"},
],
},
]
processor = VoxtralProcessor.from_pretrained("mistralai/Voxtral-Mini-3B-2507")
inputs = processor.apply_chat_template(conversation)
```
Args:
conversation (`Union[list[Dict, [str, str]], list[list[dict[str, str]]]]`):
The conversation to format.
"""
if kwargs.get("continue_final_message", False):
if kwargs.get("add_generation_prompt", False):
raise ValueError(
"continue_final_message and add_generation_prompt are not compatible. Use continue_final_message when you want the model to continue the final message, and add_generation_prompt when you want to add a header that will prompt it to start a new assistant message instead."
)
if kwargs.get("return_assistant_tokens_mask", False):
raise ValueError("continue_final_message is not compatible with return_assistant_tokens_mask.")
# Fill sets of kwargs that should be used by different parts of template
processed_kwargs = {
"mm_load_kwargs": {},
"template_kwargs": {},
}
for kwarg_type in processed_kwargs:
for key in AllKwargsForChatTemplate.__annotations__[kwarg_type].__annotations__:
kwarg_type_defaults = AllKwargsForChatTemplate.__annotations__[kwarg_type]
default_value = getattr(kwarg_type_defaults, key, None)
value = kwargs.pop(key, default_value)
if value is not None and not isinstance(value, dict):
processed_kwargs[kwarg_type][key] = value
# Pass unprocessed custom kwargs
processed_kwargs["template_kwargs"].update(kwargs)
if isinstance(conversation, (list, tuple)) and (
isinstance(conversation[0], (list, tuple)) or hasattr(conversation[0], "content")
):
is_batched = True
conversations = conversation
else:
is_batched = False
conversations = [conversation]
# Check for any overlapping keys between mm_load_kwargs and kwargs
mm_load_kwargs = processed_kwargs["mm_load_kwargs"]
if any(key in kwargs for key in mm_load_kwargs):
overlapping_keys = [key for key in mm_load_kwargs if key in kwargs]
logger.warning(
f"{overlapping_keys[0] if len(overlapping_keys) == 1 else ', '.join(overlapping_keys)} load multimodal data kwarg{'s' if len(overlapping_keys) > 1 else ''} {'have' if len(overlapping_keys) > 1 else 'has'} been passed to the processor, but {'they are' if len(overlapping_keys) > 1 else 'it is'} not supported for VoxtralProcessor since it relies on mistral_common directly. {'They' if len(overlapping_keys) > 1 else 'It'} will be ignored."
)
output_kwargs = self._merge_kwargs(
VoxtralProcessorKwargs,
**kwargs,
)
text_kwargs = output_kwargs["text_kwargs"]
audio_kwargs = output_kwargs["audio_kwargs"]
return_tensors = text_kwargs.get("return_tensors", None)
if return_tensors != "pt":
raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
tokenizer_kwargs = {**processed_kwargs["template_kwargs"], **text_kwargs}
tokenizer_kwargs["return_tensors"] = None # let's not return tensors here
tokenize = tokenizer_kwargs.pop("tokenize", False)
return_dict = tokenizer_kwargs.pop("return_dict", True)
encoded_instruct_inputs = self.tokenizer.apply_chat_template(
conversations,
tokenize=tokenize,
return_dict=return_dict,
**tokenizer_kwargs,
)
if tokenize:
if return_dict:
audio = encoded_instruct_inputs.pop("audio", None)
data = dict(encoded_instruct_inputs)
if audio is not None:
max_source_positions = audio_kwargs.pop("max_source_positions")
data["input_features"] = self._retrieve_input_features(audio, max_source_positions, **audio_kwargs)
return BatchFeature(data=data, tensor_type=return_tensors)
if not is_batched:
return encoded_instruct_inputs[0]
return encoded_instruct_inputs
def __call__(
self,
text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]],
**kwargs: Unpack[VoxtralProcessorKwargs],
):
r"""
Method to prepare text to be fed as input to the model. This method forwards the `text`
arguments to MistralCommonBackend's [`~MistralCommonBackend.__call__`] to encode
the text. Please refer to the docstring of the above methods for more information.
This methods does not support audio. To prepare the audio, please use:
1. `apply_chat_template` [`~VoxtralProcessor.apply_chat_template`] method.
2. `apply_transcription_request` [`~VoxtralProcessor.apply_transcription_request`] method.
Args:
text (`str`, `list[str]`, `list[list[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors of a particular framework. Acceptable values are:
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return NumPy `np.ndarray` objects.
Returns:
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
- **input_features** -- List of audio values to be fed to a model. Returned when `audio` is not `None`.
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
`None`).
"""
if isinstance(text, str):
text = [text]
if any(self.audio_token in t for t in text):
raise ValueError(
f"{self.audio_token} is present in the provided text which is not supported by VoxtralProcessor. Please use the `apply_chat_template` method instead."
)
output_kwargs = self._merge_kwargs(VoxtralProcessorKwargs, **kwargs)
out = self.tokenizer(text, **output_kwargs["text_kwargs"])
return BatchFeature(data=out, tensor_type=output_kwargs["text_kwargs"].get("return_tensors", None))
# TODO: @eustlb, this should be moved to mistral_common + testing
def apply_transcription_request(
self,
audio: Union[str, list[str], AudioInput],
model_id: str,
language: Optional[Union[str, list[Union[str, None]]]] = None,
sampling_rate: Optional[int] = None,
format: Optional[Union[str, list[str]]] = None,
**kwargs: Unpack[VoxtralProcessorKwargs],
):
"""
This method applies the model's transcription request template given a language and audio.
It relies on MistralCommonBackend and WhisperFeatureExtractor to prepare input ids and input features to the model.
```python
from transformers import VoxtralProcessor
model_id = "mistralai/Voxtral-Mini-3B-2507"
processor = VoxtralProcessor.from_pretrained(model_id)
language = "en"
audio = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3"
# set the language is already know for better accuracy
inputs = processor.apply_transcription_request(language=language, audio=audio, model_id=model_id)
# but you can also let the model detect the language automatically
inputs = processor.apply_transcription_request(audio=audio, model_id=model_id)
```
Args:
audio (`str`, `list[str]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
The audio or batch of audio to be prepared. If provided as a string, it should correspond to the path or url of the audio file.
model_id (`str`:
The hub model id of the model to use for transcription.
language (`str`, `list[Union[str, None]]`, *optional*):
The language or languages of the audio.
If not provided or None, automatic language detection will be used for all audio.
If provided as a string (a language code in the [ISO 639-1 alpha-2 format](https://en.wikipedia.org/wiki/ISO_639-1) e.g. `"en"`), it will be applied uniformly to all audio.
If provided as a list of strings/ None values, e.g. `["en", None, "fr"]`, will be applied to each audio individually with a one-to-one mapping,
with a None value indicating automatic language detection for that audio.
sampling_rate (`int`, *optional*):
The sampling rate of the audio. Necessary if it is provided as `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`.
Used to avoid silent errors when passing audio that is not in the expected sampling rate.
format (`str`, `list[str]`, *optional*):
The format of the audio, necessary if is provided as `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`.
"""
output_kwargs = self._merge_kwargs(
VoxtralProcessorKwargs,
**kwargs,
)
text_kwargs = output_kwargs["text_kwargs"]
audio_kwargs = output_kwargs["audio_kwargs"]
is_str = isinstance(audio, str)
is_list_of_str = all(isinstance(el, str) for el in audio)
is_list_of_audio = not (is_str or is_list_of_str)
if is_list_of_audio:
if sampling_rate is None:
logger.warning_once(
f"You've provided audio without specifying the sampling rate. It will be assumed to be {audio_kwargs['sampling_rate']}, which can result in silent errors."
)
elif sampling_rate != audio_kwargs["sampling_rate"]:
raise ValueError(
f"The sampling rate of the audio ({sampling_rate}) does not match the sampling rate of the processor ({audio_kwargs['sampling_rate']}). Please provide resampled the audio to the expected sampling rate."
)
sampling_rate = audio_kwargs["sampling_rate"]
# make sure to remove from text_kwargs and audio_kwargs
return_dict = text_kwargs.pop("return_dict", False)
tokenize = text_kwargs.pop("tokenize", False)
_ = audio_kwargs.pop("return_dict", False)
_ = audio_kwargs.pop("tokenize", False)
return_tensors = text_kwargs.pop("return_tensors", None)
if return_tensors != "pt":
raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
# validate audio input
if is_str:
audio = [load_audio_as(audio, return_format="buffer", force_mono=True, sampling_rate=sampling_rate)]
elif is_list_of_str:
audio = [
load_audio_as(el, return_format="buffer", force_mono=True, sampling_rate=sampling_rate) for el in audio
]
else:
audio = make_list_of_audio(audio)
if len(audio) != len(format):
raise ValueError(
f"When passed as a list of audio, the length ({len(audio)}) must match the number of format ({len(format)})"
)
audio_buffers = []
for array, f in zip(audio, format):
# Create new BytesIO object and write audio data to it
buffer = io.BytesIO()
# Convert to mono if needed
if array.ndim == 2:
array = array.mean(axis=1)
# Write to buffer with default format and sampling rate
sf.write(buffer, array, samplerate=audio_kwargs["sampling_rate"], format=f)
buffer.seek(0)
audio_buffers.append(buffer)
audio = audio_buffers
# validate language input
n_audio = len(audio)
if isinstance(language, str):
language = [language] * n_audio
elif language is None:
language = [None] * n_audio
if len(language) != n_audio:
raise ValueError(
f"When passed as a list of languages, the length ({len(language)}) must match the number of audio ({n_audio})"
)
input_ids = []
texts = []
audio_arrays = []
for audio_el, language_el in zip(audio, language):
openai_transcription_request = {
"model": model_id,
"file": audio_el,
"language": language_el,
}
transcription_request = TranscriptionRequest.from_openai(openai_transcription_request)
tokenized_transcription_request = self.tokenizer.tokenizer.encode_transcription(transcription_request)
input_ids.append(tokenized_transcription_request.tokens)
texts.append(tokenized_transcription_request.text)
audio_arrays.extend([el.audio_array for el in tokenized_transcription_request.audios])
if tokenize:
if return_dict:
# text are already tokenized but we need to pad etc
encoding = self.tokenizer(
input_ids,
add_special_tokens=False,
**text_kwargs,
)
data = dict(encoding)
# extract the input features
max_source_positions = audio_kwargs.pop("max_source_positions")
data["input_features"] = self._retrieve_input_features(
audio_arrays, max_source_positions, **audio_kwargs
)
return BatchFeature(data=data, tensor_type=return_tensors)
return texts
__all__ = ["VoxtralProcessor"]
| VoxtralProcessor |
python | facebook__pyre-check | client/configuration/search_path.py | {
"start": 840,
"end": 1094
} | class ____(abc.ABC):
@abc.abstractmethod
def path(self) -> str:
raise NotImplementedError()
@abc.abstractmethod
def command_line_argument(self) -> str:
raise NotImplementedError()
@dataclasses.dataclass(frozen=True)
| Element |
python | pypa__setuptools | setuptools/_distutils/command/install.py | {
"start": 4860,
"end": 30072
} | class ____(Command):
description = "install everything from build directory"
user_options = [
# Select installation scheme and set base director(y|ies)
('prefix=', None, "installation prefix"),
('exec-prefix=', None, "(Unix only) prefix for platform-specific files"),
('home=', None, "(Unix only) home directory to install under"),
# Or, just set the base director(y|ies)
(
'install-base=',
None,
"base installation directory (instead of --prefix or --home)",
),
(
'install-platbase=',
None,
"base installation directory for platform-specific files (instead of --exec-prefix or --home)",
),
('root=', None, "install everything relative to this alternate root directory"),
# Or, explicitly set the installation scheme
(
'install-purelib=',
None,
"installation directory for pure Python module distributions",
),
(
'install-platlib=',
None,
"installation directory for non-pure module distributions",
),
(
'install-lib=',
None,
"installation directory for all module distributions (overrides --install-purelib and --install-platlib)",
),
('install-headers=', None, "installation directory for C/C++ headers"),
('install-scripts=', None, "installation directory for Python scripts"),
('install-data=', None, "installation directory for data files"),
# Byte-compilation options -- see install_lib.py for details, as
# these are duplicated from there (but only install_lib does
# anything with them).
('compile', 'c', "compile .py to .pyc [default]"),
('no-compile', None, "don't compile .py files"),
(
'optimize=',
'O',
"also compile with optimization: -O1 for \"python -O\", "
"-O2 for \"python -OO\", and -O0 to disable [default: -O0]",
),
# Miscellaneous control options
('force', 'f', "force installation (overwrite any existing files)"),
('skip-build', None, "skip rebuilding everything (for testing/debugging)"),
# Where to install documentation (eventually!)
# ('doc-format=', None, "format of documentation to generate"),
# ('install-man=', None, "directory for Unix man pages"),
# ('install-html=', None, "directory for HTML documentation"),
# ('install-info=', None, "directory for GNU info files"),
('record=', None, "filename in which to record list of installed files"),
]
boolean_options: ClassVar[list[str]] = ['compile', 'force', 'skip-build']
if HAS_USER_SITE:
user_options.append((
'user',
None,
f"install in user site-package '{USER_SITE}'",
))
boolean_options.append('user')
negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'}
def initialize_options(self) -> None:
"""Initializes options."""
# High-level options: these select both an installation base
# and scheme.
self.prefix: str | None = None
self.exec_prefix: str | None = None
self.home: str | None = None
self.user = False
# These select only the installation base; it's up to the user to
# specify the installation scheme (currently, that means supplying
# the --install-{platlib,purelib,scripts,data} options).
self.install_base = None
self.install_platbase = None
self.root: str | None = None
# These options are the actual installation directories; if not
# supplied by the user, they are filled in using the installation
# scheme implied by prefix/exec-prefix/home and the contents of
# that installation scheme.
self.install_purelib = None # for pure module distributions
self.install_platlib = None # non-pure (dists w/ extensions)
self.install_headers = None # for C/C++ headers
self.install_lib: str | None = None # set to either purelib or platlib
self.install_scripts = None
self.install_data = None
self.install_userbase = USER_BASE
self.install_usersite = USER_SITE
self.compile = None
self.optimize = None
# Deprecated
# These two are for putting non-packagized distributions into their
# own directory and creating a .pth file if it makes sense.
# 'extra_path' comes from the setup file; 'install_path_file' can
# be turned off if it makes no sense to install a .pth file. (But
# better to install it uselessly than to guess wrong and not
# install it when it's necessary and would be used!) Currently,
# 'install_path_file' is always true unless some outsider meddles
# with it.
self.extra_path = None
self.install_path_file = True
# 'force' forces installation, even if target files are not
# out-of-date. 'skip_build' skips running the "build" command,
# handy if you know it's not necessary. 'warn_dir' (which is *not*
# a user option, it's just there so the bdist_* commands can turn
# it off) determines whether we warn about installing to a
# directory not in sys.path.
self.force = False
self.skip_build = False
self.warn_dir = True
# These are only here as a conduit from the 'build' command to the
# 'install_*' commands that do the real work. ('build_base' isn't
# actually used anywhere, but it might be useful in future.) They
# are not user options, because if the user told the install
# command where the build directory is, that wouldn't affect the
# build command.
self.build_base = None
self.build_lib = None
# Not defined yet because we don't know anything about
# documentation yet.
# self.install_man = None
# self.install_html = None
# self.install_info = None
self.record = None
# -- Option finalizing methods -------------------------------------
# (This is rather more involved than for most commands,
# because this is where the policy for installing third-
# party Python modules on various platforms given a wide
# array of user input is decided. Yes, it's quite complex!)
def finalize_options(self) -> None: # noqa: C901
"""Finalizes options."""
# This method (and its helpers, like 'finalize_unix()',
# 'finalize_other()', and 'select_scheme()') is where the default
# installation directories for modules, extension modules, and
# anything else we care to install from a Python module
# distribution. Thus, this code makes a pretty important policy
# statement about how third-party stuff is added to a Python
# installation! Note that the actual work of installation is done
# by the relatively simple 'install_*' commands; they just take
# their orders from the installation directory options determined
# here.
# Check for errors/inconsistencies in the options; first, stuff
# that's wrong on any platform.
if (self.prefix or self.exec_prefix or self.home) and (
self.install_base or self.install_platbase
):
raise DistutilsOptionError(
"must supply either prefix/exec-prefix/home or install-base/install-platbase -- not both"
)
if self.home and (self.prefix or self.exec_prefix):
raise DistutilsOptionError(
"must supply either home or prefix/exec-prefix -- not both"
)
if self.user and (
self.prefix
or self.exec_prefix
or self.home
or self.install_base
or self.install_platbase
):
raise DistutilsOptionError(
"can't combine user with prefix, "
"exec_prefix/home, or install_(plat)base"
)
# Next, stuff that's wrong (or dubious) only on certain platforms.
if os.name != "posix":
if self.exec_prefix:
self.warn("exec-prefix option ignored on this platform")
self.exec_prefix = None
# Now the interesting logic -- so interesting that we farm it out
# to other methods. The goal of these methods is to set the final
# values for the install_{lib,scripts,data,...} options, using as
# input a heady brew of prefix, exec_prefix, home, install_base,
# install_platbase, user-supplied versions of
# install_{purelib,platlib,lib,scripts,data,...}, and the
# install schemes. Phew!
self.dump_dirs("pre-finalize_{unix,other}")
if os.name == 'posix':
self.finalize_unix()
else:
self.finalize_other()
self.dump_dirs("post-finalize_{unix,other}()")
# Expand configuration variables, tilde, etc. in self.install_base
# and self.install_platbase -- that way, we can use $base or
# $platbase in the other installation directories and not worry
# about needing recursive variable expansion (shudder).
py_version = sys.version.split()[0]
(prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
try:
abiflags = sys.abiflags
except AttributeError:
# sys.abiflags may not be defined on all platforms.
abiflags = ''
local_vars = {
'dist_name': self.distribution.get_name(),
'dist_version': self.distribution.get_version(),
'dist_fullname': self.distribution.get_fullname(),
'py_version': py_version,
'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',
'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',
'sys_prefix': prefix,
'prefix': prefix,
'sys_exec_prefix': exec_prefix,
'exec_prefix': exec_prefix,
'abiflags': abiflags,
'platlibdir': getattr(sys, 'platlibdir', 'lib'),
'implementation_lower': _get_implementation().lower(),
'implementation': _get_implementation(),
}
# vars for compatibility on older Pythons
compat_vars = dict(
# Python 3.9 and earlier
py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''),
)
if HAS_USER_SITE:
local_vars['userbase'] = self.install_userbase
local_vars['usersite'] = self.install_usersite
self.config_vars = collections.ChainMap(
local_vars,
sysconfig.get_config_vars(),
compat_vars,
fw.vars(),
)
self.expand_basedirs()
self.dump_dirs("post-expand_basedirs()")
# Now define config vars for the base directories so we can expand
# everything else.
local_vars['base'] = self.install_base
local_vars['platbase'] = self.install_platbase
if DEBUG:
from pprint import pprint
print("config vars:")
pprint(dict(self.config_vars))
# Expand "~" and configuration variables in the installation
# directories.
self.expand_dirs()
self.dump_dirs("post-expand_dirs()")
# Create directories in the home dir:
if self.user:
self.create_home_path()
# Pick the actual directory to install all modules to: either
# install_purelib or install_platlib, depending on whether this
# module distribution is pure or not. Of course, if the user
# already specified install_lib, use their selection.
if self.install_lib is None:
if self.distribution.has_ext_modules(): # has extensions: non-pure
self.install_lib = self.install_platlib
else:
self.install_lib = self.install_purelib
# Convert directories from Unix /-separated syntax to the local
# convention.
self.convert_paths(
'lib',
'purelib',
'platlib',
'scripts',
'data',
'headers',
'userbase',
'usersite',
)
# Deprecated
# Well, we're not actually fully completely finalized yet: we still
# have to deal with 'extra_path', which is the hack for allowing
# non-packagized module distributions (hello, Numerical Python!) to
# get their own directories.
self.handle_extra_path()
self.install_libbase = self.install_lib # needed for .pth file
self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
# If a new root directory was supplied, make all the installation
# dirs relative to it.
if self.root is not None:
self.change_roots(
'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers'
)
self.dump_dirs("after prepending root")
# Find out the build directories, ie. where to install from.
self.set_undefined_options(
'build', ('build_base', 'build_base'), ('build_lib', 'build_lib')
)
# Punt on doc directories for now -- after all, we're punting on
# documentation completely!
def dump_dirs(self, msg) -> None:
"""Dumps the list of user options."""
if not DEBUG:
return
from ..fancy_getopt import longopt_xlate
log.debug(msg + ":")
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = self.negative_opt[opt_name]
opt_name = opt_name.translate(longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = opt_name.translate(longopt_xlate)
val = getattr(self, opt_name)
log.debug(" %s: %s", opt_name, val)
def finalize_unix(self) -> None:
"""Finalizes options for posix platforms."""
if self.install_base is not None or self.install_platbase is not None:
incomplete_scheme = (
(
self.install_lib is None
and self.install_purelib is None
and self.install_platlib is None
)
or self.install_headers is None
or self.install_scripts is None
or self.install_data is None
)
if incomplete_scheme:
raise DistutilsOptionError(
"install-base or install-platbase supplied, but "
"installation scheme is incomplete"
)
return
if self.user:
if self.install_userbase is None:
raise DistutilsPlatformError("User base directory is not specified")
self.install_base = self.install_platbase = self.install_userbase
self.select_scheme("posix_user")
elif self.home is not None:
self.install_base = self.install_platbase = self.home
self.select_scheme("posix_home")
else:
if self.prefix is None:
if self.exec_prefix is not None:
raise DistutilsOptionError(
"must not supply exec-prefix without prefix"
)
# Allow Fedora to add components to the prefix
_prefix_addition = getattr(sysconfig, '_prefix_addition', "")
self.prefix = os.path.normpath(sys.prefix) + _prefix_addition
self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition
else:
if self.exec_prefix is None:
self.exec_prefix = self.prefix
self.install_base = self.prefix
self.install_platbase = self.exec_prefix
self.select_scheme("posix_prefix")
def finalize_other(self) -> None:
"""Finalizes options for non-posix platforms"""
if self.user:
if self.install_userbase is None:
raise DistutilsPlatformError("User base directory is not specified")
self.install_base = self.install_platbase = self.install_userbase
self.select_scheme(os.name + "_user")
elif self.home is not None:
self.install_base = self.install_platbase = self.home
self.select_scheme("posix_home")
else:
if self.prefix is None:
self.prefix = os.path.normpath(sys.prefix)
self.install_base = self.install_platbase = self.prefix
try:
self.select_scheme(os.name)
except KeyError:
raise DistutilsPlatformError(
f"I don't know how to install stuff on '{os.name}'"
)
def select_scheme(self, name) -> None:
_select_scheme(self, name)
def _expand_attrs(self, attrs):
for attr in attrs:
val = getattr(self, attr)
if val is not None:
if os.name in ('posix', 'nt'):
val = os.path.expanduser(val)
val = subst_vars(val, self.config_vars)
setattr(self, attr, val)
def expand_basedirs(self) -> None:
"""Calls `os.path.expanduser` on install_base, install_platbase and
root."""
self._expand_attrs(['install_base', 'install_platbase', 'root'])
def expand_dirs(self) -> None:
"""Calls `os.path.expanduser` on install dirs."""
self._expand_attrs([
'install_purelib',
'install_platlib',
'install_lib',
'install_headers',
'install_scripts',
'install_data',
])
def convert_paths(self, *names) -> None:
"""Call `convert_path` over `names`."""
for name in names:
attr = "install_" + name
setattr(self, attr, convert_path(getattr(self, attr)))
def handle_extra_path(self) -> None:
"""Set `path_file` and `extra_dirs` using `extra_path`."""
if self.extra_path is None:
self.extra_path = self.distribution.extra_path
if self.extra_path is not None:
log.warning(
"Distribution option extra_path is deprecated. "
"See issue27919 for details."
)
if isinstance(self.extra_path, str):
self.extra_path = self.extra_path.split(',')
if len(self.extra_path) == 1:
path_file = extra_dirs = self.extra_path[0]
elif len(self.extra_path) == 2:
path_file, extra_dirs = self.extra_path
else:
raise DistutilsOptionError(
"'extra_path' option must be a list, tuple, or "
"comma-separated string with 1 or 2 elements"
)
# convert to local form in case Unix notation used (as it
# should be in setup scripts)
extra_dirs = convert_path(extra_dirs)
else:
path_file = None
extra_dirs = ''
# XXX should we warn if path_file and not extra_dirs? (in which
# case the path file would be harmless but pointless)
self.path_file = path_file
self.extra_dirs = extra_dirs
def change_roots(self, *names) -> None:
"""Change the install directories pointed by name using root."""
for name in names:
attr = "install_" + name
setattr(self, attr, change_root(self.root, getattr(self, attr)))
def create_home_path(self) -> None:
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for path in self.config_vars.values():
if str(path).startswith(home) and not os.path.isdir(path):
self.debug_print(f"os.makedirs('{path}', 0o700)")
os.makedirs(path, 0o700)
# -- Command execution methods -------------------------------------
def run(self):
"""Runs the command."""
# Obviously have to build before we can install
if not self.skip_build:
self.run_command('build')
# If we built for any other platform, we can't install.
build_plat = self.distribution.get_command_obj('build').plat_name
# check warn_dir - it is a clue that the 'install' is happening
# internally, and not to sys.path, so we don't check the platform
# matches what we are running.
if self.warn_dir and build_plat != get_platform():
raise DistutilsPlatformError("Can't install when cross-compiling")
# Run all sub-commands (at least those that need to be run)
for cmd_name in self.get_sub_commands():
self.run_command(cmd_name)
if self.path_file:
self.create_path_file()
# write list of installed files, if requested.
if self.record:
outputs = self.get_outputs()
if self.root: # strip any package prefix
root_len = len(self.root)
for counter in range(len(outputs)):
outputs[counter] = outputs[counter][root_len:]
self.execute(
write_file,
(self.record, outputs),
f"writing list of installed files to '{self.record}'",
)
sys_path = map(os.path.normpath, sys.path)
sys_path = map(os.path.normcase, sys_path)
install_lib = os.path.normcase(os.path.normpath(self.install_lib))
if (
self.warn_dir
and not (self.path_file and self.install_path_file)
and install_lib not in sys_path
):
log.debug(
(
"modules installed to '%s', which is not in "
"Python's module search path (sys.path) -- "
"you'll have to change the search path yourself"
),
self.install_lib,
)
def create_path_file(self):
"""Creates the .pth file"""
filename = os.path.join(self.install_libbase, self.path_file + ".pth")
if self.install_path_file:
self.execute(
write_file, (filename, [self.extra_dirs]), f"creating {filename}"
)
else:
self.warn(f"path file '{filename}' not created")
# -- Reporting methods ---------------------------------------------
def get_outputs(self):
"""Assembles the outputs of all the sub-commands."""
outputs = []
for cmd_name in self.get_sub_commands():
cmd = self.get_finalized_command(cmd_name)
# Add the contents of cmd.get_outputs(), ensuring
# that outputs doesn't contain duplicate entries
for filename in cmd.get_outputs():
if filename not in outputs:
outputs.append(filename)
if self.path_file and self.install_path_file:
outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth"))
return outputs
def get_inputs(self):
"""Returns the inputs of all the sub-commands"""
# XXX gee, this looks familiar ;-(
inputs = []
for cmd_name in self.get_sub_commands():
cmd = self.get_finalized_command(cmd_name)
inputs.extend(cmd.get_inputs())
return inputs
# -- Predicates for sub-command list -------------------------------
def has_lib(self):
"""Returns true if the current distribution has any Python
modules to install."""
return (
self.distribution.has_pure_modules() or self.distribution.has_ext_modules()
)
def has_headers(self):
"""Returns true if the current distribution has any headers to
install."""
return self.distribution.has_headers()
def has_scripts(self):
"""Returns true if the current distribution has any scripts to.
install."""
return self.distribution.has_scripts()
def has_data(self):
"""Returns true if the current distribution has any data to.
install."""
return self.distribution.has_data_files()
# 'sub_commands': a list of commands this command might have to run to
# get its work done. See cmd.py for more info.
sub_commands = [
('install_lib', has_lib),
('install_headers', has_headers),
('install_scripts', has_scripts),
('install_data', has_data),
('install_egg_info', lambda self: True),
]
| install |
python | sphinx-doc__sphinx | sphinx/builders/xml.py | {
"start": 550,
"end": 3335
} | class ____(Builder):
"""Builds Docutils-native XML."""
name = 'xml'
format = 'xml'
epilog = __('The XML files are in %(outdir)s.')
out_suffix = '.xml'
allow_parallel = True
default_translator_class = XMLTranslator
def init(self) -> None:
pass
def get_outdated_docs(self) -> Iterator[str]:
for docname in self.env.found_docs:
if docname not in self.env.all_docs:
yield docname
continue
targetname = self.outdir / (docname + self.out_suffix)
try:
targetmtime = _last_modified_time(targetname)
except Exception:
targetmtime = 0
try:
srcmtime = _last_modified_time(self.env.doc2path(docname))
if srcmtime > targetmtime:
yield docname
except OSError:
# source doesn't exist anymore
pass
def get_target_uri(self, docname: str, typ: str | None = None) -> str:
return docname
def write_doc(self, docname: str, doctree: nodes.document) -> None:
# work around multiple string % tuple issues in docutils;
# replace tuples in attribute values with lists
doctree = doctree.deepcopy()
for domain in self.env.domains.sorted():
doctree[f'xmlns:{domain.name}'] = 'https://www.sphinx-doc.org/'
for node in doctree.findall(nodes.Element):
for att, value in node.attributes.items():
if isinstance(value, tuple):
node.attributes[att] = list(value)
value = node.attributes[att]
if isinstance(value, list):
for i, val in enumerate(value):
if isinstance(val, tuple):
value[i] = list(val)
output = self._translate(doctree)
out_file_name = self.outdir / (docname + self.out_suffix)
out_file_name.parent.mkdir(parents=True, exist_ok=True)
try:
out_file_name.write_text(output, encoding='utf-8')
except OSError as err:
logger.warning(__('error writing file %s: %s'), out_file_name, err)
def _translate(self, doctree: nodes.document) -> str:
doctree.settings.newlines = doctree.settings.indents = self.config.xml_pretty
doctree.settings.xml_declaration = True
doctree.settings.doctype_declaration = True
# copied from docutils.writers.docutils_xml.Writer.translate()
# so that we can override the translator class
visitor: XMLTranslator = self.create_translator(doctree)
doctree.walkabout(visitor)
return ''.join(visitor.output)
def finish(self) -> None:
pass
| XMLBuilder |
python | arrow-py__arrow | tests/test_parser.py | {
"start": 53299,
"end": 54576
} | class ____:
def test_shortmonth_capitalized(self):
assert self.parser.parse("2013-Jan-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
def test_shortmonth_allupper(self):
assert self.parser.parse("2013-JAN-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
def test_shortmonth_alllower(self):
assert self.parser.parse("2013-jan-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
def test_month_capitalized(self):
assert self.parser.parse("2013-January-01", "YYYY-MMMM-DD") == datetime(
2013, 1, 1
)
def test_month_allupper(self):
assert self.parser.parse("2013-JANUARY-01", "YYYY-MMMM-DD") == datetime(
2013, 1, 1
)
def test_month_alllower(self):
assert self.parser.parse("2013-january-01", "YYYY-MMMM-DD") == datetime(
2013, 1, 1
)
def test_localized_month_name(self):
parser_ = parser.DateTimeParser("fr-fr")
assert parser_.parse("2013-Janvier-01", "YYYY-MMMM-DD") == datetime(2013, 1, 1)
def test_localized_month_abbreviation(self):
parser_ = parser.DateTimeParser("it-it")
assert parser_.parse("2013-Gen-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
@pytest.mark.usefixtures("dt_parser")
| TestDateTimeParserMonthName |
python | skorch-dev__skorch | skorch/tests/test_probabilistic.py | {
"start": 19744,
"end": 21599
} | class ____(BaseProbabilisticTests):
"""Tests for GPRegressor."""
##########################
# constants and fixtures #
##########################
n_samples = 60
n_targets = 1
supports_predict_proba = False
supports_return_std = True
supports_return_cov = True
settable_params = {'gp__module__eps': 1e-5}
scoring = 'neg_mean_squared_error'
@pytest.fixture
def data(self):
X = np.linspace(-8, 8.01, self.n_samples).astype(np.float32)
y = (np.sin(X) + np.random.randn(len(X)) * 0.2).astype(np.float32)
return X, y
@pytest.fixture
def gp_cls(self):
from skorch.probabilistic import GPRegressor
return GPRegressor
@pytest.fixture
def module_cls(self):
return VariationalRegressionModule
@pytest.fixture
def gp(self, gp_cls, module_cls, data):
X, y = data
gpr = gp_cls(
module_cls,
module__inducing_points=torch.from_numpy(X[:10]),
criterion=gpytorch.mlls.VariationalELBO,
criterion__num_data=int(0.8 * len(y)),
batch_size=24,
)
# we want to make sure batching is properly tested
assert gpr.batch_size < self.n_samples
return gpr
# Since GPyTorch v1.10, GPRegressor works with pickle/deepcopy.
def test_pickling(self, gp_fit, data):
loaded = pickle.loads(pickle.dumps(gp_fit))
X, _ = data
y_pred_before = gp_fit.predict(X)
y_pred_after = loaded.predict(X)
assert np.allclose(y_pred_before, y_pred_after)
def test_deepcopy(self, gp_fit, data):
copied = copy.deepcopy(gp_fit)
X, _ = data
y_pred_before = gp_fit.predict(X)
y_pred_after = copied.predict(X)
assert np.allclose(y_pred_before, y_pred_after)
| TestGPRegressorVariational |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-bedrock/tests/test_bedrock_async.py | {
"start": 447,
"end": 761
} | class ____:
async def __aenter__(self) -> "AsyncMockClient":
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
pass
async def invoke_model(self, *args, **kwargs):
return {"contentType": "application/json", "body": AsyncMockStreamReader()}
| AsyncMockClient |
python | scrapy__scrapy | tests/test_utils_datatypes.py | {
"start": 6833,
"end": 8353
} | class ____:
def test_list(self):
seq = [1, 2, 3]
d = SequenceExclude(seq)
assert 0 in d
assert 4 in d
assert 2 not in d
def test_range(self):
seq = range(10, 20)
d = SequenceExclude(seq)
assert 5 in d
assert 20 in d
assert 15 not in d
def test_range_step(self):
seq = range(10, 20, 3)
d = SequenceExclude(seq)
are_not_in = [v for v in range(10, 20, 3) if v in d]
assert are_not_in == []
are_not_in = [v for v in range(10, 20) if v in d]
assert are_not_in == [11, 12, 14, 15, 17, 18]
def test_string_seq(self):
seq = "cde"
d = SequenceExclude(seq)
chars = "".join(v for v in "abcdefg" if v in d)
assert chars == "abfg"
def test_stringset_seq(self):
seq = set("cde")
d = SequenceExclude(seq)
chars = "".join(v for v in "abcdefg" if v in d)
assert chars == "abfg"
def test_set(self):
"""Anything that is not in the supplied sequence will evaluate as 'in' the container."""
seq = {-3, "test", 1.1}
d = SequenceExclude(seq)
assert 0 in d
assert "foo" in d
assert 3.14 in d
assert set("bar") in d
# supplied sequence is a set, so checking for list (non)inclusion fails
with pytest.raises(TypeError):
["a", "b", "c"] in d # noqa: B015
for v in [-3, "test", 1.1]:
assert v not in d
| TestSequenceExclude |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/vincent_renderer.py | {
"start": 191,
"end": 2227
} | class ____(Renderer):
def open_figure(self, fig: Any, props: Dict[str, Union[int, float]]) -> None:
self.chart = None
self.figwidth = int(props["figwidth"] * props["dpi"])
self.figheight = int(props["figheight"] * props["dpi"])
def draw_line(
self,
data: numpy.ndarray,
coordinates: str,
style: dict,
label: str,
mplobj: Optional[Any] = None,
) -> None:
import vincent # only import if VincentRenderer is used
if coordinates != "data":
warnings.warn("Only data coordinates supported. Skipping this")
linedata = {"x": data[:, 0], "y": data[:, 1]}
line = vincent.Line(linedata, iter_idx="x", width=self.figwidth, height=self.figheight)
# TODO: respect the other style settings
line.scales["color"].range = [style["color"]]
if self.chart is None:
self.chart = line
else:
warnings.warn("Multiple plot elements not yet supported")
def draw_markers(
self,
data: numpy.ndarray,
coordinates: str,
style: dict,
label: str,
mplobj: Optional[Any] = None,
) -> None:
import vincent # only import if VincentRenderer is used
if coordinates != "data":
warnings.warn("Only data coordinates supported. Skipping this")
markerdata = {"x": data[:, 0], "y": data[:, 1]}
markers = vincent.Scatter(markerdata, iter_idx="x", width=self.figwidth, height=self.figheight)
# TODO: respect the other style settings
markers.scales["color"].range = [style["facecolor"]]
if self.chart is None:
self.chart = markers
else:
warnings.warn("Multiple plot elements not yet supported")
def fig_to_vincent(fig: Any) -> "vincent.core.Vega":
"""Convert a matplotlib figure to a vincent object"""
renderer = VincentRenderer()
exporter = Exporter(renderer)
exporter.run(fig)
return renderer.chart
| VincentRenderer |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_related.py | {
"start": 720,
"end": 1072
} | class ____(typing.List):
pass
ClsUnsubscriptable()[1] # [unsubscriptable-object]
ClsUnsubscriptable[int] # [unsubscriptable-object]
ClsGetItem()[1]
ClsGetItem[int] # [unsubscriptable-object]
ClsClassGetItem()[1] # [unsubscriptable-object]
ClsClassGetItem[int]
# subscriptable because of inheritance
ClsList([0, 1, 2])[1]
ClsList[int]
| ClsList |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverride1.py | {
"start": 796,
"end": 1145
} | class ____(Base3):
@overload
def foo(self, x: float) -> float: ...
@overload
def foo(self, x: str) -> str: ...
# This should generate an error because no overloaded signature
# is compatible with the base method, nor is the implementation.
def foo(self, x: int | str | float) -> int | str | float:
return x
| Derived3 |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 3299,
"end": 6704
} | class ____(_TensorLoader):
def __init__(
self,
resolve_fun: Callable,
stream: Optional[torch.Stream] = None,
inflight_threshhold: int = 1_000_000,
) -> None:
self.resolve_fun = resolve_fun
self.items: list[tuple[int, object]] = []
self.inflight_threshhold = inflight_threshhold
self.in_flight_data = 0
self.current_items: collections.deque = collections.deque()
self.idx = 0
self.started = False
self.device_type = (
stream.device_type if stream else _get_available_device_type()
)
self.device_module = _get_device_module(self.device_type)
self.stream = cast(
torch.cuda.Stream, stream or self.device_module.current_stream()
)
if self.stream != self.device_module.current_stream():
self.stream.wait_stream(self.device_module.current_stream())
@property
def _done(self) -> bool:
return self.idx >= len(self.items)
def _drain(self) -> list[tuple[torch.Tensor, object]]:
drained = []
if self.in_flight_data >= self.inflight_threshhold:
self.stream.synchronize()
while self.in_flight_data >= self.inflight_threshhold:
val = self.current_items.popleft()
self.in_flight_data -= val[0].numel() * val[0].element_size()
drained.append(val)
return drained
def _refill(self) -> None:
with self.device_module.stream(self.stream):
while not self._done and self.in_flight_data < self.inflight_threshhold:
_, obj = self.items[self.idx]
self.idx += 1
tensor = self.resolve_fun(obj).detach()
if tensor.device.type == self.device_type:
tensor = tensor.to(device="cpu", non_blocking=True)
elif tensor.device == torch.device("cpu"):
if (
tensor.untyped_storage().size()
!= tensor.numel() * tensor.itemsize
):
# this forces the tensor to be both contiguous and with minimal storage
tensor = tensor.clone()
self.current_items.append(
(
tensor,
obj,
)
)
self.in_flight_data += tensor.numel() * tensor.element_size()
def _finish(self) -> Iterable[tuple[torch.Tensor, object]]:
if not self._done:
raise AssertionError("_finish called before all items were processed")
if len(self.current_items) > 0:
self.stream.synchronize()
return self.current_items
def add(self, size: int, obj: object) -> None:
if self.started:
raise RuntimeError("cannot add items after loading started")
self.items.append((size, obj))
def start_loading(self) -> None:
if self.started:
return
self.started = True
self.items.sort(key=operator.itemgetter(0))
self._refill()
def values(self) -> Iterator[tuple[torch.Tensor, object]]:
self.start_loading()
while not self._done:
drained = self._drain()
self._refill()
yield from drained
yield from self._finish()
| _OverlappingCpuLoader |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 1769,
"end": 1871
} | class ____(models.Model):
b = models.ForeignKey("LoopB", null=False, on_delete=models.CASCADE)
| LoopA |
python | django__django | tests/auth_tests/operations_migrations/0001_initial.py | {
"start": 43,
"end": 295
} | class ____(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
name="OldModel",
fields=[
("id", models.AutoField(primary_key=True)),
],
),
]
| Migration |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 19061,
"end": 22639
} | class ____(Benchmark):
# list of distributions to time
dists = ["pareto", "laplace", "rayleigh", "invgauss", "gumbel_r",
"gumbel_l", "powerlaw", "lognorm"]
# add custom values for rvs and fit, if desired, for any distribution:
# key should match name in dists and value should be list of loc, scale,
# and shapes
custom_input = {}
fnames = ['floc', 'fscale', 'f0', 'f1', 'f2']
fixed = {}
param_names = ["distribution", "case", "loc_fixed", "scale_fixed",
"shape1_fixed", "shape2_fixed", "shape3_fixed"]
# in the `_distr_params.py` list, some distributions have multiple sets of
# "sane" shape combinations. `case` needs to be an enumeration of the
# maximum number of cases for a benchmarked distribution; the maximum is
# currently two. Should a benchmarked distribution have more cases in the
# `_distr_params.py` list, this will need to be increased.
params = [dists, range(2), * [[True, False]] * 5]
def setup(self, dist_name, case, loc_fixed, scale_fixed,
shape1_fixed, shape2_fixed, shape3_fixed):
self.distn = eval("stats." + dist_name)
# default `loc` and `scale` are .834 and 4.342, and shapes are from
# `_distr_params.py`. If there are multiple cases of valid shapes in
# `distcont`, they are benchmarked separately.
default_shapes_n = [s[1] for s in distcont if s[0] == dist_name]
if case >= len(default_shapes_n):
raise NotImplementedError("no alternate case for this dist")
default_shapes = default_shapes_n[case]
param_values = self.custom_input.get(dist_name, [*default_shapes,
.834, 4.342])
# separate relevant and non-relevant parameters for this distribution
# based on the number of shapes
nparam = len(param_values)
all_parameters = [loc_fixed, scale_fixed, shape1_fixed, shape2_fixed,
shape3_fixed]
relevant_parameters = all_parameters[:nparam]
nonrelevant_parameters = all_parameters[nparam:]
# skip if all parameters are fixed or if non relevant parameters are
# not all false
if True in nonrelevant_parameters or False not in relevant_parameters:
raise NotImplementedError("skip non-relevant case")
# TODO: fix failing benchmarks (Aug. 2023), skipped for now
if ((dist_name == "pareto" and loc_fixed and scale_fixed)
or (dist_name == "invgauss" and loc_fixed)):
raise NotImplementedError("skip failing benchmark")
# add fixed values if fixed in relevant_parameters to self.fixed
# with keys from self.fnames and values in the same order as `fnames`.
fixed_vales = self.custom_input.get(dist_name, [.834, 4.342,
*default_shapes])
self.fixed = dict(zip(compress(self.fnames, relevant_parameters),
compress(fixed_vales, relevant_parameters)))
self.param_values = param_values
# shapes need to come before loc and scale
self.data = self.distn.rvs(*param_values[2:], *param_values[:2],
size=1000,
random_state=np.random.default_rng(4653465))
def time_fit(self, dist_name, case, loc_fixed, scale_fixed,
shape1_fixed, shape2_fixed, shape3_fixed):
self.distn.fit(self.data, **self.fixed)
| ContinuousFitAnalyticalMLEOverride |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/commit.py | {
"start": 102,
"end": 468
} | class ____(serializers.Serializer):
path = serializers.CharField(max_length=510)
type = serializers.CharField(max_length=1)
def validate_type(self, value):
if not CommitFileChange.is_valid_type(value):
raise serializers.ValidationError("Commit patch_set type %s is not supported." % value)
return value
| CommitPatchSetSerializer |
python | jazzband__django-simple-history | simple_history/tests/tests/test_manager.py | {
"start": 4033,
"end": 9692
} | class ____(TestCase):
def test_create_and_delete(self):
document = Document.objects.create()
now = datetime.now()
document.delete()
docs_as_of_now = Document.history.as_of(now)
doc = docs_as_of_now[0]
# as_of queries inject a property allowing callers
# to go from instance to historical instance
historic = getattr(doc, SIMPLE_HISTORY_REVERSE_ATTR_NAME)
self.assertIsNotNone(historic)
# as_of queries inject the time point of the original
# query into the historic record so callers can do magical
# things like chase historic foreign key relationships
# by patching forward and reverse one-to-one relationship
# processing (see issue 880)
self.assertEqual(historic._as_of, now)
docs_as_of_tmw = Document.history.as_of(now + timedelta(days=1))
with self.assertNumQueries(1):
self.assertFalse(list(docs_as_of_tmw))
def test_multiple(self):
document1 = Document.objects.create()
document2 = Document.objects.create()
historical = Document.history.as_of(datetime.now() + timedelta(days=1))
# history, even converted to objects, is kept in reverse chronological order
# because sorting it based on the original table's meta ordering is not possible
# when the ordering leverages foreign key relationships
with self.assertNumQueries(1):
self.assertEqual(list(historical), [document2, document1])
def test_filter_pk_as_instance(self):
# when a queryset is returning historical documents, `pk` queries
# reference the history_id; however when a queryset is returning
# instances, `pk' queries reference the original table's primary key
document1 = RankedDocument.objects.create(id=101, rank=42)
RankedDocument.objects.create(id=102, rank=84)
self.assertFalse(RankedDocument.history.filter(pk=document1.id))
self.assertTrue(
RankedDocument.history.all().as_instances().filter(pk=document1.id)
)
def test_as_of(self):
"""Demonstrates how as_of works now that it returns a QuerySet."""
t0 = datetime.now()
document1 = RankedDocument.objects.create(rank=42)
document2 = RankedDocument.objects.create(rank=84)
t1 = datetime.now()
document2.rank = 51
document2.save()
document1.delete()
t2 = datetime.now()
# nothing exists at t0
queryset = RankedDocument.history.as_of(t0)
self.assertEqual(queryset.count(), 0)
# at t1, two records exist
queryset = RankedDocument.history.as_of(t1)
self.assertEqual(queryset.count(), 2)
self.assertEqual(queryset.filter(rank__gte=75).count(), 1)
ids = {item["id"] for item in queryset.values("id")}
self.assertEqual(ids, {document1.id, document2.id})
# these records are historic
record = queryset[0]
historic = getattr(record, SIMPLE_HISTORY_REVERSE_ATTR_NAME)
self.assertIsInstance(historic, RankedDocument.history.model)
self.assertEqual(historic._as_of, t1)
# at t2 we have one record left
queryset = RankedDocument.history.as_of(t2)
self.assertEqual(queryset.count(), 1)
self.assertEqual(queryset.filter(rank__gte=75).count(), 0)
def test_historical_query_set(self):
"""
Demonstrates how the HistoricalQuerySet works to provide as_of functionality.
"""
document1 = RankedDocument.objects.create(rank=10)
document2 = RankedDocument.objects.create(rank=20)
document2.rank = 21
document2.save()
document1.delete()
t1 = datetime.now()
document3 = RankedDocument.objects.create(rank=30) # noqa: F841
document2.rank = 22
document2.save()
t2 = datetime.now()
# 4 records before `t1` (for document 1 and 2), 2 after (for document 2 and 3)
queryset = RankedDocument.history.filter(history_date__lte=t1)
self.assertEqual(queryset.count(), 4)
self.assertEqual(RankedDocument.history.filter(history_date__gt=t1).count(), 2)
# `latest_of_each()` returns the most recent record of each document
with self.assertNumQueries(1):
self.assertEqual(queryset.latest_of_each().count(), 2)
# `as_instances()` returns the historical instances as of each record's time,
# but excludes deletion records (i.e. document 1's most recent record)
with self.assertNumQueries(1):
self.assertEqual(queryset.latest_of_each().as_instances().count(), 1)
# (Duplicate calls to these methods should not change the number of queries,
# since they're idempotent)
with self.assertNumQueries(1):
self.assertEqual(
queryset.latest_of_each()
.latest_of_each()
.as_instances()
.as_instances()
.count(),
1,
)
self.assertSetEqual(
# In conclusion, all of these methods combined...
set(
RankedDocument.history.filter(history_date__lte=t1)
.latest_of_each()
.as_instances()
),
# ...are equivalent to calling `as_of()`!
set(RankedDocument.history.as_of(t1)),
)
self.assertEqual(RankedDocument.history.as_of(t1).get().rank, 21)
self.assertListEqual(
[d.rank for d in RankedDocument.history.as_of(t2)], [22, 30]
)
| AsOfTestCaseWithoutSetUp |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/react/formatter.py | {
"start": 1418,
"end": 4595
} | class ____(BaseAgentChatFormatter):
"""ReAct chat formatter."""
system_header: str = REACT_CHAT_SYSTEM_HEADER # default
context: str = "" # not needed w/ default
observation_role: MessageRole = Field(
default=MessageRole.USER,
description=(
"Message role of tool outputs. If the LLM you use supports function/tool "
"calling, you may set it to `MessageRole.TOOL` to avoid the tool outputs "
"being misinterpreted as new user messages."
),
)
def format(
self,
tools: Sequence[BaseTool],
chat_history: List[ChatMessage],
current_reasoning: Optional[List[BaseReasoningStep]] = None,
) -> List[ChatMessage]:
"""Format chat history into list of ChatMessage."""
current_reasoning = current_reasoning or []
format_args = {
"tool_desc": "\n".join(get_react_tool_descriptions(tools)),
"tool_names": ", ".join([tool.metadata.get_name() for tool in tools]),
}
if self.context:
format_args["context"] = self.context
fmt_sys_header = self.system_header.format(**format_args)
# format reasoning history as alternating user and assistant messages
# where the assistant messages are thoughts and actions and the tool
# messages are observations
reasoning_history = []
for reasoning_step in current_reasoning:
if isinstance(reasoning_step, ObservationReasoningStep):
message = ChatMessage(
role=self.observation_role,
content=reasoning_step.get_content(),
)
else:
message = ChatMessage(
role=MessageRole.ASSISTANT,
content=reasoning_step.get_content(),
)
reasoning_history.append(message)
return [
ChatMessage(role=MessageRole.SYSTEM, content=fmt_sys_header),
*chat_history,
*reasoning_history,
]
@classmethod
def from_defaults(
cls,
system_header: Optional[str] = None,
context: Optional[str] = None,
observation_role: MessageRole = MessageRole.USER,
) -> "ReActChatFormatter":
"""Create ReActChatFormatter from defaults."""
if not system_header:
system_header = (
REACT_CHAT_SYSTEM_HEADER
if not context
else CONTEXT_REACT_CHAT_SYSTEM_HEADER
)
return ReActChatFormatter(
system_header=system_header,
context=context or "",
observation_role=observation_role,
)
@classmethod
def from_context(cls, context: str) -> "ReActChatFormatter":
"""
Create ReActChatFormatter from context.
NOTE: deprecated
"""
logger.warning(
"ReActChatFormatter.from_context is deprecated, please use `from_defaults` instead."
)
return ReActChatFormatter.from_defaults(
system_header=CONTEXT_REACT_CHAT_SYSTEM_HEADER, context=context
)
| ReActChatFormatter |
python | django__django | django/forms/fields.py | {
"start": 35822,
"end": 36555
} | class ____(Field):
"""
A Field whose clean() method calls multiple Field clean() methods.
"""
def __init__(self, fields, **kwargs):
super().__init__(**kwargs)
# Set 'required' to False on the individual fields, because the
# required validation will be handled by ComboField, not by those
# individual fields.
for f in fields:
f.required = False
self.fields = fields
def clean(self, value):
"""
Validate the given value against all of self.fields, which is a
list of Field instances.
"""
super().clean(value)
for field in self.fields:
value = field.clean(value)
return value
| ComboField |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py | {
"start": 161,
"end": 215
} | class ____:
def __call__(self, x: str) -> int: ...
| B |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 7293,
"end": 7486
} | class ____(BaseModel):
input_tokens: int
input_tokens_details: InputTokensDetails
output_tokens: int
output_tokens_details: OutputTokensDetails
total_tokens: int
| ResponseUsage |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 1684,
"end": 7640
} | class ____:
def setup_method(self):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField()
integer = serializers.IntegerField()
self.Serializer = ExampleSerializer
def test_valid_serializer(self):
serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
assert serializer.is_valid()
assert serializer.validated_data == {'char': 'abc', 'integer': 123}
assert serializer.data == {'char': 'abc', 'integer': 123}
assert serializer.errors == {}
def test_invalid_serializer(self):
serializer = self.Serializer(data={'char': 'abc'})
assert not serializer.is_valid()
assert serializer.validated_data == {}
assert serializer.data == {'char': 'abc'}
assert serializer.errors == {'integer': ['This field is required.']}
def test_invalid_datatype(self):
serializer = self.Serializer(data=[{'char': 'abc'}])
assert not serializer.is_valid()
assert serializer.validated_data == {}
assert serializer.data == {}
assert serializer.errors == {'non_field_errors': ['Invalid data. Expected a dictionary, but got list.']}
def test_partial_validation(self):
serializer = self.Serializer(data={'char': 'abc'}, partial=True)
assert serializer.is_valid()
assert serializer.validated_data == {'char': 'abc'}
assert serializer.errors == {}
def test_empty_serializer(self):
serializer = self.Serializer()
assert serializer.data == {'char': '', 'integer': None}
def test_missing_attribute_during_serialization(self):
class MissingAttributes:
pass
instance = MissingAttributes()
serializer = self.Serializer(instance)
with pytest.raises(AttributeError):
serializer.data
def test_data_access_before_save_raises_error(self):
def create(validated_data):
return validated_data
serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
serializer.create = create
assert serializer.is_valid()
assert serializer.data == {'char': 'abc', 'integer': 123}
with pytest.raises(AssertionError):
serializer.save()
def test_validate_none_data(self):
data = None
serializer = self.Serializer(data=data)
assert not serializer.is_valid()
assert serializer.errors == {'non_field_errors': ['No data provided']}
def test_serialize_chainmap(self):
data = ChainMap({'char': 'abc'}, {'integer': 123})
serializer = self.Serializer(data=data)
assert serializer.is_valid()
assert serializer.validated_data == {'char': 'abc', 'integer': 123}
assert serializer.errors == {}
def test_serialize_custom_mapping(self):
class SinglePurposeMapping(Mapping):
def __getitem__(self, key):
return 'abc' if key == 'char' else 123
def __iter__(self):
yield 'char'
yield 'integer'
def __len__(self):
return 2
serializer = self.Serializer(data=SinglePurposeMapping())
assert serializer.is_valid()
assert serializer.validated_data == {'char': 'abc', 'integer': 123}
assert serializer.errors == {}
def test_custom_to_internal_value(self):
"""
to_internal_value() is expected to return a dict, but subclasses may
return application specific type.
"""
class Point:
def __init__(self, srid, x, y):
self.srid = srid
self.coords = (x, y)
# Declares a serializer that converts data into an object
class NestedPointSerializer(serializers.Serializer):
longitude = serializers.FloatField(source='x')
latitude = serializers.FloatField(source='y')
def to_internal_value(self, data):
kwargs = super().to_internal_value(data)
return Point(srid=4326, **kwargs)
serializer = NestedPointSerializer(data={'longitude': 6.958307, 'latitude': 50.941357})
assert serializer.is_valid()
assert isinstance(serializer.validated_data, Point)
assert serializer.validated_data.srid == 4326
assert serializer.validated_data.coords[0] == 6.958307
assert serializer.validated_data.coords[1] == 50.941357
assert serializer.errors == {}
def test_iterable_validators(self):
"""
Ensure `validators` parameter is compatible with reasonable iterables.
"""
data = {'char': 'abc', 'integer': 123}
for validators in ([], (), set()):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField(validators=validators)
integer = serializers.IntegerField()
serializer = ExampleSerializer(data=data)
assert serializer.is_valid()
assert serializer.validated_data == data
assert serializer.errors == {}
def raise_exception(value):
raise exceptions.ValidationError('Raised error')
for validators in ([raise_exception], (raise_exception,), {raise_exception}):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField(validators=validators)
integer = serializers.IntegerField()
serializer = ExampleSerializer(data=data)
assert not serializer.is_valid()
assert serializer.data == data
assert serializer.validated_data == {}
assert serializer.errors == {'char': [
exceptions.ErrorDetail(string='Raised error', code='invalid')
]}
def test_serializer_is_subscriptable(self):
assert serializers.Serializer is serializers.Serializer["foo"]
| TestSerializer |
python | ray-project__ray | doc/source/serve/doc_code/getting_started/model_deployment.py | {
"start": 267,
"end": 1339
} | class ____:
def __init__(self):
# Load model
self.model = pipeline("translation_en_to_fr", model="t5-small")
def translate(self, text: str) -> str:
# Run inference
model_output = self.model(text)
# Post-process output to return only the translation text
translation = model_output[0]["translation_text"]
return translation
async def __call__(self, http_request: Request) -> str:
english_text: str = await http_request.json()
return self.translate(english_text)
# __model_end__
# __model_deploy_start__
translator_app = Translator.bind()
# __model_deploy_end__
translator_app = Translator.options(ray_actor_options={}).bind()
serve.run(translator_app)
# __client_function_start__
# File name: model_client.py
import requests
english_text = "Hello world!"
response = requests.post("http://127.0.0.1:8000/", json=english_text)
french_text = response.text
print(french_text)
# __client_function_end__
assert french_text == "Bonjour monde!"
serve.shutdown()
ray.shutdown()
| Translator |
python | pytorch__pytorch | benchmarks/tensorexpr/reduction.py | {
"start": 26,
"end": 2325
} | class ____(benchmark.Benchmark):
def __init__(self, mode, device, dtype, case, M, N, K, skip_input_transform):
super().__init__(mode, device, dtype)
self.case = case
self.M = M
self.N = N
self.K = K
self._set_skip_input_transform(skip_input_transform)
self.inputs = [
self.randn(
[M, N, K], device=device, dtype=dtype, requires_grad=self.requires_grad
)
]
if case == "row":
self.dims = [1, 2]
elif case == "mid":
self.dims = [0, 2]
elif case == "col":
self.dims = [0, 1]
elif case == "full":
self.dims = [0, 1, 2]
else:
raise ValueError(f"invalid case: {case}")
def forward(self, inputs):
if self.skip_input_transform:
x = inputs
else:
x = self.add(inputs, 0.001)
y = self.sum(x, self.dims)
return y
def config(self):
if self.case == "full":
return [self.M * self.N * self.K, self._skip_input_transform_str()]
return [self.M, self.N, self.K, self._skip_input_transform_str()]
@staticmethod
def default_configs():
return [
# [512, 512, 512],
[512, 64, 512, "s0"],
]
@staticmethod
def module():
return "reduce"
def memory_workload(self):
if self.mode == "fwd":
sol_count = 1
algorithmic_count = 1
else:
sol_count = (1) + (1)
algorithmic_count = 1 + 1
buffer_size = self.M * self.N * self.K
return {
"sol": buffer_size * sol_count,
"algorithmic": buffer_size * algorithmic_count,
}
def _set_skip_input_transform(self, input_str):
# In the test setting, s1 will skip the input transformation, and s0 will not.
if input_str == "s0":
self.skip_input_transform = False
elif input_str == "s1":
self.skip_input_transform = True
else:
raise ValueError(f"invalid skip_input_transform: {input_str}")
def _skip_input_transform_str(self):
if self.skip_input_transform:
return "s1"
else:
return "s0"
| ReduceBench |
python | openai__openai-python | src/openai/types/webhooks/eval_run_failed_webhook_event.py | {
"start": 316,
"end": 743
} | class ____(BaseModel):
id: str
"""The unique ID of the event."""
created_at: int
"""The Unix timestamp (in seconds) of when the eval run failed."""
data: Data
"""Event data payload."""
type: Literal["eval.run.failed"]
"""The type of the event. Always `eval.run.failed`."""
object: Optional[Literal["event"]] = None
"""The object of the event. Always `event`."""
| EvalRunFailedWebhookEvent |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 49721,
"end": 51223
} | class ____(TestCase):
validator = None
# pywsgi checks content-length, but wsgi does not
content_length = None
assert TestCase.handler_class._print_unexpected_exc
class handler_class(TestCase.handler_class):
def _print_unexpected_exc(self):
raise AssertionError("Should not print a traceback")
def application(self, env, start_response):
self.assertEqual(env['CONTENT_LENGTH'], self.content_length)
start_response('200 OK', [('Content-Type', 'text/plain')])
return [b'hello']
def test_negative_content_length(self):
self.content_length = '-100'
with self.makefile() as fd:
fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %s\r\n\r\n' % self.content_length)
read_http(fd, code=(200, 400))
def test_illegal_content_length(self):
self.content_length = 'abc'
with self.makefile() as fd:
fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %s\r\n\r\n' % self.content_length)
read_http(fd, code=(200, 400))
def test_bad_request_line_with_percent(self):
# If the request is invalid and contains Python formatting characters (%)
# we don't fail to log the error and we do generate a 400.
# https://github.com/gevent/gevent/issues/1708
bad_request = 'GET / HTTP %\r\n'
with self.makefile() as fd:
fd.write(bad_request)
read_http(fd, code=400)
| BadRequestTests |
python | wandb__wandb | wandb/apis/public/registries/registries_search.py | {
"start": 4402,
"end": 8054
} | class ____(
SizedRelayPaginator["RegistryCollectionFragment", "ArtifactCollection"]
):
"""An lazy iterator of `ArtifactCollection` objects in a Registry."""
QUERY: ClassVar[Document | None] = None
last_response: RegistryCollectionConnection | None
def __init__(
self,
client: RetryingClient,
organization: str,
registry_filter: dict[str, Any] | None = None,
collection_filter: dict[str, Any] | None = None,
per_page: PositiveInt = 100,
):
if self.QUERY is None:
from wandb.sdk.artifacts._generated import REGISTRY_COLLECTIONS_GQL
type(self).QUERY = gql(REGISTRY_COLLECTIONS_GQL)
self.client = client
self.organization = organization
self.registry_filter = registry_filter
self.collection_filter = collection_filter or {}
variables = {
"registryFilter": json.dumps(f) if (f := registry_filter) else None,
"collectionFilter": json.dumps(f) if (f := collection_filter) else None,
"organization": organization,
"perPage": per_page,
}
super().__init__(client, variables=variables, per_page=per_page)
def __next__(self):
# Implement custom next since its possible to load empty pages because of auth
self.index += 1
while len(self.objects) <= self.index:
if not self._load_page():
raise StopIteration
return self.objects[self.index]
@tracked
def versions(
self, filter: dict[str, Any] | None = None, per_page: PositiveInt = 100
) -> Versions:
return Versions(
client=self.client,
organization=self.organization,
registry_filter=self.registry_filter,
collection_filter=self.collection_filter,
artifact_filter=filter,
per_page=per_page,
)
@override
def _update_response(self) -> None:
from wandb.sdk.artifacts._generated import RegistryCollections
from wandb.sdk.artifacts._models.pagination import RegistryCollectionConnection
data = self.client.execute(self.QUERY, variable_values=self.variables)
result = RegistryCollections.model_validate(data)
if not ((org := result.organization) and (org_entity := org.org_entity)):
raise ValueError(
f"Organization {self.organization!r} not found. Please verify the organization name is correct."
)
try:
conn = org_entity.artifact_collections
self.last_response = RegistryCollectionConnection.model_validate(conn)
except (LookupError, AttributeError, ValidationError) as e:
raise ValueError("Unexpected response data") from e
def _convert(self, node: RegistryCollectionFragment) -> ArtifactCollection | None:
from wandb._pydantic import gql_typename
from wandb.apis.public import ArtifactCollection
from wandb.sdk.artifacts._generated import ArtifactSequenceTypeFields
if not (
# We don't _expect_ any registry collections to be
# ArtifactSequences, but defensively filter them out anyway.
node.project
and (node.typename__ != gql_typename(ArtifactSequenceTypeFields))
):
return None
return ArtifactCollection(
client=self.client,
entity=node.project.entity.name,
project=node.project.name,
name=node.name,
type=node.type.name,
organization=self.organization,
attrs=node,
)
| Collections |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 29495,
"end": 32521
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
config: Qwen2_5OmniAudioEncoderConfig,
):
super().__init__()
self.embed_dim = config.d_model
self.num_heads = config.encoder_attention_heads
self.dropout = config.attention_dropout
self.head_dim = self.embed_dim // self.num_heads
self.num_key_value_groups = 1 # needed for eager attention
self.config = config
if (self.head_dim * self.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`: {self.num_heads})."
)
self.scaling = self.head_dim**-0.5
self.attention_dropout = 0.0
self.is_decoder = False
self.is_causal = False
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
seq_length, _ = hidden_states.size()
query_states = self.q_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
key_states = self.k_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
value_states = self.v_proj(hidden_states).reshape(seq_length, self.num_heads, -1)
query_states = query_states.transpose(0, 1).unsqueeze(0)
key_states = key_states.transpose(0, 1).unsqueeze(0)
value_states = value_states.transpose(0, 1).unsqueeze(0)
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, _ = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask=attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
cu_seq_lens_q=cu_seqlens, # pass cu seq lens for FA2
cu_seq_lens_k=cu_seqlens,
max_length_q=max_seqlen,
max_length_k=max_seqlen,
is_causal=False,
**kwargs,
)
attn_output = attn_output.reshape(seq_length, -1).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output
| Qwen2_5OmniAudioAttention |
python | lepture__authlib | authlib/integrations/starlette_client/apps.py | {
"start": 416,
"end": 1628
} | class ____:
async def save_authorize_data(self, request, **kwargs):
state = kwargs.pop("state", None)
if state:
if self.framework.cache:
session = None
else:
session = request.session
await self.framework.set_state_data(session, state, kwargs)
else:
raise RuntimeError("Missing state value")
async def authorize_redirect(self, request, redirect_uri=None, **kwargs):
"""Create a HTTP Redirect for Authorization Endpoint.
:param request: HTTP request instance from Starlette view.
:param redirect_uri: Callback or redirect URI for authorization.
:param kwargs: Extra parameters to include.
:return: A HTTP redirect response.
"""
# Handle Starlette >= 0.26.0 where redirect_uri may now be a URL and not a string
if redirect_uri and isinstance(redirect_uri, URL):
redirect_uri = str(redirect_uri)
rv = await self.create_authorization_url(redirect_uri, **kwargs)
await self.save_authorize_data(request, redirect_uri=redirect_uri, **rv)
return RedirectResponse(rv["url"], status_code=302)
| StarletteAppMixin |
python | Netflix__metaflow | metaflow/plugins/aws/aws_client.py | {
"start": 63,
"end": 4287
} | class ____(object):
name = "boto3"
@staticmethod
def get_client(
module, with_error=False, role_arn=None, session_vars=None, client_params=None
):
from metaflow.exception import MetaflowException
from metaflow.metaflow_config import (
AWS_SANDBOX_ENABLED,
AWS_SANDBOX_STS_ENDPOINT_URL,
AWS_SANDBOX_API_KEY,
S3_CLIENT_RETRY_CONFIG,
)
if session_vars is None:
session_vars = {}
if client_params is None:
client_params = {}
import requests
try:
import boto3
import botocore
from botocore.exceptions import ClientError
from botocore.config import Config
except (NameError, ImportError):
raise MetaflowException(
"Could not import module 'boto3'. Install boto3 first."
)
# Convert dictionary config to Config object if needed
if "config" in client_params and not isinstance(
client_params["config"], Config
):
client_params["config"] = Config(**client_params["config"])
if module == "s3" and (
"config" not in client_params or client_params["config"].retries is None
):
# do not set anything if the user has already set something
config = client_params.get("config", Config())
config.retries = S3_CLIENT_RETRY_CONFIG
client_params["config"] = config
if AWS_SANDBOX_ENABLED:
# role is ignored in the sandbox
global cached_aws_sandbox_creds
if cached_aws_sandbox_creds is None:
# authenticate using STS
url = "%s/auth/token" % AWS_SANDBOX_STS_ENDPOINT_URL
headers = {"x-api-key": AWS_SANDBOX_API_KEY}
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
cached_aws_sandbox_creds = r.json()
except requests.exceptions.HTTPError as e:
raise MetaflowException(repr(e))
if with_error:
return (
boto3.session.Session(**cached_aws_sandbox_creds).client(
module, **client_params
),
ClientError,
)
return boto3.session.Session(**cached_aws_sandbox_creds).client(
module, **client_params
)
session = boto3.session.Session()
if role_arn:
fetcher = botocore.credentials.AssumeRoleCredentialFetcher(
client_creator=session._session.create_client,
source_credentials=session._session.get_credentials(),
role_arn=role_arn,
extra_args={},
)
creds = botocore.credentials.DeferredRefreshableCredentials(
method="assume-role", refresh_using=fetcher.fetch_credentials
)
botocore_session = botocore.session.Session(session_vars=session_vars)
botocore_session._credentials = creds
session = boto3.session.Session(botocore_session=botocore_session)
if with_error:
return session.client(module, **client_params), ClientError
return session.client(module, **client_params)
def get_aws_client(
module, with_error=False, role_arn=None, session_vars=None, client_params=None
):
global cached_provider_class
if cached_provider_class is None:
from metaflow.metaflow_config import DEFAULT_AWS_CLIENT_PROVIDER
from metaflow.plugins import AWS_CLIENT_PROVIDERS
for p in AWS_CLIENT_PROVIDERS:
if p.name == DEFAULT_AWS_CLIENT_PROVIDER:
cached_provider_class = p
break
else:
raise ValueError(
"Cannot find AWS Client provider %s" % DEFAULT_AWS_CLIENT_PROVIDER
)
return cached_provider_class.get_client(
module,
with_error,
role_arn=role_arn,
session_vars=session_vars,
client_params=client_params,
)
| Boto3ClientProvider |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 51927,
"end": 52315
} | class ____:
def test_type_conversion(self):
arg_type = '?bhilBHILefdgFDG'
res_type = 'ddddddddddddgDDG'
for dtin, dtout in zip(arg_type, res_type):
msg = f"dtin: {dtin}, dtout: {dtout}"
arg = np.ones(1, dtype=dtin)
res = np.float_power(arg, arg)
assert_(res.dtype.name == np.dtype(dtout).name, msg)
| TestFloat_power |
python | sphinx-doc__sphinx | sphinx/domains/cpp/__init__.py | {
"start": 3988,
"end": 16570
} | class ____(ObjectDescription[ASTDeclaration]):
"""Description of a C++ language object."""
doc_field_types: list[Field] = [
GroupedField(
'template parameter',
label=_('Template Parameters'),
names=('tparam', 'template parameter'),
can_collapse=True,
),
]
option_spec: ClassVar[OptionSpec] = {
'no-index-entry': directives.flag,
'no-contents-entry': directives.flag,
'no-typesetting': directives.flag,
'noindexentry': directives.flag,
'nocontentsentry': directives.flag,
'tparam-line-spec': directives.flag,
'single-line-parameter-list': directives.flag,
}
def _add_enumerator_to_parent(self, ast: ASTDeclaration) -> None:
assert ast.objectType == 'enumerator'
# find the parent, if it exists && is an enum
# && it's unscoped,
# then add the name to the parent scope
symbol = ast.symbol
assert symbol
assert symbol.identOrOp is not None
assert symbol.templateParams is None
assert symbol.templateArgs is None
parent_symbol = symbol.parent
assert parent_symbol
if parent_symbol.parent is None:
# TODO: we could warn, but it is somewhat equivalent to unscoped
# enums, without the enum
return # no parent
parent_decl = parent_symbol.declaration
if parent_decl is None:
# the parent is not explicitly declared
# TODO: we could warn, but it could be a style to just assume
# enumerator parents to be scoped
return
if parent_decl.objectType != 'enum':
# TODO: maybe issue a warning, enumerators in non-enums is weird,
# but it is somewhat equivalent to unscoped enums, without the enum
return
if parent_decl.directiveType != 'enum':
return
target_symbol = parent_symbol.parent
s = target_symbol.find_identifier(
symbol.identOrOp,
matchSelf=False,
recurseInAnon=True,
searchInSiblings=False,
)
if s is not None:
# something is already declared with that name
return
decl_clone = symbol.declaration.clone()
decl_clone.enumeratorScopedSymbol = symbol
Symbol(
parent=target_symbol,
identOrOp=symbol.identOrOp,
templateParams=None,
templateArgs=None,
declaration=decl_clone,
docname=self.env.current_document.docname,
line=self.get_source_info()[1],
)
def add_target_and_index(
self, ast: ASTDeclaration, sig: str, signode: TextElement
) -> None:
# general note: name must be lstrip(':')'ed, to remove "::"
ids = []
for i in range(1, _max_id + 1):
try:
id = ast.get_id(version=i)
ids.append(id)
except NoOldIdError:
assert i < _max_id
# let's keep the newest first
ids.reverse()
newest_id = ids[0]
assert newest_id # shouldn't be None
if not re.compile(r'^[a-zA-Z0-9_]*$').match(newest_id):
logger.warning(
'Index id generation for C++ object "%s" failed, please '
'report as bug (id=%s).',
ast,
newest_id,
location=self.get_location(),
)
name = ast.symbol.get_full_nested_name().get_display_string().lstrip(':')
# Add index entry, but not if it's a declaration inside a concept
is_in_concept = False
s = ast.symbol.parent
while s is not None:
decl = s.declaration
s = s.parent
if decl is None:
continue
if decl.objectType == 'concept':
is_in_concept = True
break
if not is_in_concept and 'no-index-entry' not in self.options:
stripped_name = name
for prefix in self.config.cpp_index_common_prefix:
if name.startswith(prefix):
stripped_name = stripped_name[len(prefix) :]
break
index_text = self.get_index_text(stripped_name)
self.indexnode['entries'].append((
'single',
index_text,
newest_id,
'',
None,
))
if newest_id not in self.state.document.ids:
# if the name is not unique, the first one will win
names = self.env.domaindata['cpp']['names']
if name not in names:
names[name] = ast.symbol.docname
# always add the newest id
assert newest_id
signode['ids'].append(newest_id)
# only add compatibility ids when there are no conflicts
for id in ids[1:]:
if not id: # is None when the element didn't exist in that version
continue
if id not in self.state.document.ids:
signode['ids'].append(id)
self.state.document.note_explicit_target(signode)
@property
def object_type(self) -> str:
raise NotImplementedError
@property
def display_object_type(self) -> str:
return self.object_type
def get_index_text(self, name: str) -> str:
return _('%s (C++ %s)') % (name, self.display_object_type)
def parse_definition(self, parser: DefinitionParser) -> ASTDeclaration:
return parser.parse_declaration(self.object_type, self.objtype)
def describe_signature(
self, signode: desc_signature, ast: ASTDeclaration, options: dict[str, Any]
) -> None:
ast.describe_signature(signode, 'lastIsName', self.env, options)
def run(self) -> list[Node]:
env = self.env
if env.current_document.cpp_parent_symbol is None:
root = env.domaindata['cpp']['root_symbol']
env.current_document.cpp_parent_symbol = root
env.ref_context['cpp:parent_key'] = root.get_lookup_key()
# The lookup keys assume that no nested scopes exists inside overloaded functions.
# See: https://github.com/sphinx-doc/sphinx/issues/5191
# Example:
# .. cpp:function:: void f(int)
# .. cpp:function:: void f(double)
#
# .. cpp:function:: void g()
#
# :cpp:any:`boom`
#
# So we disallow any signatures inside functions.
parent_symbol = env.current_document.cpp_parent_symbol
parent_decl = parent_symbol.declaration
if parent_decl is not None and parent_decl.objectType == 'function':
msg = (
'C++ declarations inside functions are not supported. '
f'Parent function: {parent_symbol.get_full_nested_name()}\n'
f'Directive name: {self.name}\nDirective arg: {self.arguments[0]}'
)
logger.warning(msg, location=self.get_location())
name = _make_phony_error_name()
symbol = parent_symbol.add_name(name)
env.current_document.cpp_last_symbol = symbol
return []
# When multiple declarations are made in the same directive
# they need to know about each other to provide symbol lookup for function parameters.
# We use last_symbol to store the latest added declaration in a directive.
env.current_document.cpp_last_symbol = None
return super().run()
def handle_signature(self, sig: str, signode: desc_signature) -> ASTDeclaration:
parent_symbol: Symbol = self.env.current_document.cpp_parent_symbol
max_len = (
self.config.cpp_maximum_signature_line_length
or self.config.maximum_signature_line_length
or 0
)
signode['multi_line_parameter_list'] = (
'single-line-parameter-list' not in self.options
and (len(sig) > max_len > 0)
)
parser = DefinitionParser(sig, location=signode, config=self.config)
try:
ast = self.parse_definition(parser)
parser.assert_end()
except DefinitionError as e:
logger.warning(e, location=signode)
# It is easier to assume some phony name than handling the error in
# the possibly inner declarations.
name = _make_phony_error_name()
symbol = parent_symbol.add_name(name)
self.env.current_document.cpp_last_symbol = symbol
raise ValueError from e
try:
symbol = parent_symbol.add_declaration(
ast,
docname=self.env.current_document.docname,
line=self.get_source_info()[1],
)
# append the new declaration to the sibling list
assert symbol.siblingAbove is None
assert symbol.siblingBelow is None
symbol.siblingAbove = self.env.current_document.cpp_last_symbol
if symbol.siblingAbove is not None:
assert symbol.siblingAbove.siblingBelow is None
symbol.siblingAbove.siblingBelow = symbol
self.env.current_document.cpp_last_symbol = symbol
except _DuplicateSymbolError as e:
# Assume we are actually in the old symbol,
# instead of the newly created duplicate.
self.env.current_document.cpp_last_symbol = e.symbol
msg = __(
'Duplicate C++ declaration, also defined at %s:%s.\n'
"Declaration is '.. cpp:%s:: %s'."
)
logger.warning(
msg,
e.symbol.docname,
e.symbol.line,
self.display_object_type,
sig,
location=signode,
type='duplicate_declaration',
subtype='cpp',
)
if ast.objectType == 'enumerator':
self._add_enumerator_to_parent(ast)
# note: handle_signature may be called multiple time per directive,
# if it has multiple signatures, so don't mess with the original options.
options = dict(self.options)
options['tparam-line-spec'] = 'tparam-line-spec' in self.options
self.describe_signature(signode, ast, options)
return ast
def before_content(self) -> None:
last_symbol: Symbol = self.env.current_document.cpp_last_symbol
assert last_symbol
self.oldParentSymbol = self.env.current_document.cpp_parent_symbol
self.oldParentKey: LookupKey = self.env.ref_context['cpp:parent_key']
self.env.current_document.cpp_parent_symbol = last_symbol
self.env.ref_context['cpp:parent_key'] = last_symbol.get_lookup_key()
self.env.current_document.cpp_domain_name = (
*self.env.current_document.cpp_domain_name,
last_symbol.identOrOp._stringify(str),
)
def after_content(self) -> None:
self.env.current_document.cpp_parent_symbol = self.oldParentSymbol
self.env.ref_context['cpp:parent_key'] = self.oldParentKey
cpp_domain_name = self.env.current_document.cpp_domain_name
self.env.current_document.cpp_domain_name = cpp_domain_name[:-1]
def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]:
last_symbol: Symbol = self.env.current_document.cpp_last_symbol
return tuple(
s.identOrOp._stringify(str)
for s in last_symbol.get_full_nested_name().names
)
def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''
config = self.config
objtype = sig_node.parent.get('objtype')
if config.add_function_parentheses and objtype in {'function', 'method'}:
parens = '()'
else:
parens = ''
*parents, name = sig_node['_toc_parts']
if config.toc_object_entries_show_parents == 'domain':
return '::'.join((
*self.env.current_document.cpp_domain_name,
name + parens,
))
if config.toc_object_entries_show_parents == 'hide':
return name + parens
if config.toc_object_entries_show_parents == 'all':
return '::'.join([*parents, name + parens])
return ''
| CPPObject |
python | Netflix__metaflow | metaflow/_vendor/click/_winconsole.py | {
"start": 6041,
"end": 10009
} | class ____(object):
"""
Wraps a stream (such as stdout), acting as a transparent proxy for all
attribute access apart from method 'write()' which we wrap to write in
limited chunks due to a Windows limitation on binary console streams.
"""
def __init__(self, wrapped):
# double-underscore everything to prevent clashes with names of
# attributes on the wrapped stream object.
self.__wrapped = wrapped
def __getattr__(self, name):
return getattr(self.__wrapped, name)
def write(self, text):
total_to_write = len(text)
written = 0
while written < total_to_write:
to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)
self.__wrapped.write(text[written : written + to_write])
written += to_write
_wrapped_std_streams = set()
def _wrap_std_stream(name):
# Python 2 & Windows 7 and below
if (
PY2
and sys.getwindowsversion()[:2] <= (6, 1)
and name not in _wrapped_std_streams
):
setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))
_wrapped_std_streams.add(name)
def _get_text_stdin(buffer_stream):
text_stream = _NonClosingTextIOWrapper(
io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return ConsoleStream(text_stream, buffer_stream)
def _get_text_stdout(buffer_stream):
text_stream = _NonClosingTextIOWrapper(
io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return ConsoleStream(text_stream, buffer_stream)
def _get_text_stderr(buffer_stream):
text_stream = _NonClosingTextIOWrapper(
io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
"utf-16-le",
"strict",
line_buffering=True,
)
return ConsoleStream(text_stream, buffer_stream)
if PY2:
def _hash_py_argv():
return zlib.crc32("\x00".join(sys.argv[1:]))
_initial_argv_hash = _hash_py_argv()
def _get_windows_argv():
argc = c_int(0)
argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
if not argv_unicode:
raise WinError()
try:
argv = [argv_unicode[i] for i in range(0, argc.value)]
finally:
LocalFree(argv_unicode)
del argv_unicode
if not hasattr(sys, "frozen"):
argv = argv[1:]
while len(argv) > 0:
arg = argv[0]
if not arg.startswith("-") or arg == "-":
break
argv = argv[1:]
if arg.startswith(("-c", "-m")):
break
return argv[1:]
_stream_factories = {
0: _get_text_stdin,
1: _get_text_stdout,
2: _get_text_stderr,
}
def _is_console(f):
if not hasattr(f, "fileno"):
return False
try:
fileno = f.fileno()
except OSError:
return False
handle = msvcrt.get_osfhandle(fileno)
return bool(GetConsoleMode(handle, byref(DWORD())))
def _get_windows_console_stream(f, encoding, errors):
if (
get_buffer is not None
and encoding in ("utf-16-le", None)
and errors in ("strict", None)
and _is_console(f)
):
func = _stream_factories.get(f.fileno())
if func is not None:
if not PY2:
f = getattr(f, "buffer", None)
if f is None:
return None
else:
# If we are on Python 2 we need to set the stream that we
# deal with to binary mode as otherwise the exercise if a
# bit moot. The same problems apply as for
# get_binary_stdin and friends from _compat.
msvcrt.setmode(f.fileno(), os.O_BINARY)
return func(f)
| WindowsChunkedWriter |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_child_process_executor.py | {
"start": 930,
"end": 1121
} | class ____(ChildProcessCommand):
def execute(self): # pyright: ignore[reportIncompatibleMethodOverride]
# access inner API to simulate hard crash
segfault()
| SegfaultCommand |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/retrievers/test_parent_document.py | {
"start": 406,
"end": 1537
} | class ____(InMemoryVectorStore):
@override
def similarity_search(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> list[Document]:
res = self.store.get(query)
if res is None:
return []
return [res]
@override
def add_documents(self, documents: Sequence[Document], **kwargs: Any) -> list[str]:
print(documents) # noqa: T201
return super().add_documents(
documents,
ids=[f"{i}" for i in range(len(documents))],
)
def test_parent_document_retriever_initialization() -> None:
vectorstore = InMemoryVectorstoreWithSearch()
store = InMemoryStore()
child_splitter = CharacterTextSplitter(chunk_size=400)
documents = [Document(page_content="test document")]
retriever = ParentDocumentRetriever(
vectorstore=vectorstore,
docstore=store,
child_splitter=child_splitter,
)
retriever.add_documents(documents)
results = retriever.invoke("0")
assert len(results) > 0
assert results[0].page_content == "test document"
| InMemoryVectorstoreWithSearch |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py | {
"start": 238,
"end": 6866
} | class ____(BaseToolSpec):
spec_functions = [
"find_similar_companies",
"get_earnings_history",
"get_stocks_with_upcoming_earnings",
"get_current_gainer_stocks",
"get_current_loser_stocks",
"get_current_undervalued_growth_stocks",
"get_current_technology_growth_stocks",
"get_current_most_traded_stocks",
"get_current_undervalued_large_cap_stocks",
"get_current_aggressive_small_cap_stocks",
"get_trending_finance_news",
"get_google_trending_searches",
"get_google_trends_for_query",
"get_latest_news_for_stock",
"get_current_stock_price_info",
]
def __init__(
self,
polygon_api_key: str,
finnhub_api_key: str,
alpha_vantage_api_key: str,
newsapi_api_key: str,
):
self._api_key = {
"ALPHA_VANTAGE": alpha_vantage_api_key,
"POLYGON": polygon_api_key,
"FINNHUB": finnhub_api_key,
"NEWSAPI": newsapi_api_key,
}
def find_similar_companies(self, symbol: str) -> List[str]:
"""Given a stock's ticker symbol, returns a list of similar companies."""
return comparisons.find_similar_companies(self._api_key, symbol)
def get_earnings_history(self, symbol: str) -> pd.DataFrame:
"""Given a stock's ticker symbol, returns a dataframe storing actual and estimated earnings over past K quarterly reports."""
return earnings.get_earnings_history(self._api_key, symbol)
def get_latest_earning_estimate(self, symbol: str) -> float:
"""Given a stock's ticker symbol, returns it's earnings estimate for the upcoming quarterly report."""
return earnings.get_latest_earning_estimate(symbol)
def get_stocks_with_upcoming_earnings(
self, num_days_from_now: int, only_sp500: bool
) -> pd.DataFrame:
"""
Returns a pandas dataframe containing all stocks which are announcing earnings in upcoming days.
Arguments:
num_days_from_now: only returns stocks which announcing earnings from today's date to num_days_from_now.
only_sp500: only returns sp500 stocks.
"""
start_date = datetime.now().strftime("%Y-%m-%d")
end_date = (datetime.now() + timedelta(num_days_from_now)).strftime("%Y-%m-%d")
return earnings.get_upcoming_earnings(
self._api_key,
start_date=start_date,
end_date=end_date,
country="USD",
only_sp500=only_sp500,
)
def get_current_gainer_stocks(self) -> pd.DataFrame:
"""
Return US stocks which are classified as day gainers as per Yahoo Finance.
A US stock is classified as day gainer if %change in price > 3, price >=5, volume > 15_000
"""
return news.get_current_gainer_stocks()
def get_current_loser_stocks(self) -> pd.DataFrame:
"""
Returns US stocks which are classified as day losers as per Yahoo Finance.
A US stock is classified as day loser if %change in price < -2.5, price >=5, volume > 20_000
"""
return news.get_current_loser_stocks()
def get_current_undervalued_growth_stocks(self) -> pd.DataFrame:
"""
Get list of undervalued growth stocks in US market as per Yahoo Finance.
A stock with Price to Earnings ratio between 0-20, Price / Earnings to Growth < 1
"""
return news.get_current_undervalued_growth_stocks()
def get_current_technology_growth_stocks(self) -> pd.DataFrame:
"""
Returns a data frame of growth stocks in technology sector in US market.
If a stocks's quarterly revenue growth YoY% > 25%.
"""
return news.get_current_technology_growth_stocks()
def get_current_most_traded_stocks(self) -> pd.DataFrame:
"""
Returns a dataframe storing stocks which were traded the most in current market.
Stocks are ordered in decreasing order of activity i.e stock traded the most on top.
"""
return news.get_current_most_traded_stocks()
def get_current_undervalued_large_cap_stocks(self) -> pd.DataFrame:
"""Returns a dataframe storing US market large cap stocks with P/E < 20."""
return news.get_current_undervalued_large_cap_stocks()
def get_current_aggressive_small_cap_stocks(self) -> pd.DataFrame:
"""Returns a dataframe storing US market small cap stocks with 1 yr % change in earnings per share > 25."""
return news.get_current_aggressive_small_cap_stocks()
def get_trending_finance_news(self) -> List[str]:
"""Returns a list of top 10 trending news in financial market as per seekingalpha."""
trends = news.get_topk_trending_news()
return [t["title"] for t in trends]
def get_google_trending_searches(self) -> Optional[pd.DataFrame]:
"""
Returns trending searches in US as per google trends.
If unable to find any trends, returns None.
"""
return news.get_google_trending_searches(region="united_states")
def get_google_trends_for_query(self, query: str) -> Optional[pd.DataFrame]:
"""
Finds google search trends for a given query in United States.
Returns None if unable to find any trends.
"""
return news.get_google_trends_for_query(query=query, region="united_states")
def get_latest_news_for_stock(self, stock_id: str) -> List[str]:
"""Given a stock_id representing the name of a company or the stock ticker symbol, Returns a list of news published related to top business articles in US in last 7 days from now."""
articles = news.get_latest_news_for_stock(self._api_key, stock_id=stock_id)
return [a["title"] for a in articles]
def get_current_stock_price_info(
self, stock_ticker_symbol: str
) -> Optional[Dict[str, Any]]:
"""
Given a stock's ticker symbol, returns current price information of the stock.
Returns None if the provided stock ticker symbol is invalid.
"""
price_info = news.get_current_stock_price_info(
self._api_key, stock_ticker_symbol
)
if price_info is not None:
return {
"Current Price": price_info["c"],
"High Price of the day": price_info["h"],
"Low Price of the day": price_info["l"],
"Open Price of the day": price_info["o"],
"Percentage change": price_info["dp"],
}
return None
| FinanceAgentToolSpec |
python | RaRe-Technologies__gensim | gensim/test/test_corpora.py | {
"start": 23437,
"end": 30604
} | class ____(TestTextCorpus):
def setUp(self):
self.corpus_class = wikicorpus.WikiCorpus
self.file_extension = '.xml.bz2'
self.fname = datapath('testcorpus.' + self.file_extension.lstrip('.'))
self.enwiki = datapath('enwiki-latest-pages-articles1.xml-p000000010p000030302-shortened.bz2')
def test_default_preprocessing(self):
expected = ['computer', 'human', 'interface']
corpus = self.corpus_class(self.fname, article_min_tokens=0)
first_text = next(corpus.get_texts())
self.assertEqual(expected, first_text)
def test_len(self):
# When there is no min_token limit all 9 articles must be registered.
corpus = self.corpus_class(self.fname, article_min_tokens=0)
all_articles = corpus.get_texts()
assert (len(list(all_articles)) == 9)
# With a huge min_token limit, all articles should be filtered out.
corpus = self.corpus_class(self.fname, article_min_tokens=100000)
all_articles = corpus.get_texts()
assert (len(list(all_articles)) == 0)
def test_load_with_metadata(self):
corpus = self.corpus_class(self.fname, article_min_tokens=0)
corpus.metadata = True
self.assertEqual(len(corpus), 9)
docs = list(corpus)
self.assertEqual(len(docs), 9)
for i, docmeta in enumerate(docs):
doc, metadata = docmeta
article_no = i + 1 # Counting IDs from 1
self.assertEqual(metadata[0], str(article_no))
self.assertEqual(metadata[1], 'Article%d' % article_no)
def test_load(self):
corpus = self.corpus_class(self.fname, article_min_tokens=0)
docs = list(corpus)
# the deerwester corpus always has nine documents
self.assertEqual(len(docs), 9)
def test_first_element(self):
"""
First two articles in this sample are
1) anarchism
2) autism
"""
corpus = self.corpus_class(self.enwiki, processes=1)
texts = corpus.get_texts()
self.assertTrue(u'anarchism' in next(texts))
self.assertTrue(u'autism' in next(texts))
def test_unicode_element(self):
"""
First unicode article in this sample is
1) папа
"""
bgwiki = datapath('bgwiki-latest-pages-articles-shortened.xml.bz2')
corpus = self.corpus_class(bgwiki)
texts = corpus.get_texts()
self.assertTrue(u'папа' in next(texts))
def test_custom_tokenizer(self):
"""
define a custom tokenizer function and use it
"""
wc = self.corpus_class(self.enwiki, processes=1, tokenizer_func=custom_tokenizer,
token_max_len=16, token_min_len=1, lower=False)
row = wc.get_texts()
list_tokens = next(row)
self.assertTrue(u'Anarchism' in list_tokens)
self.assertTrue(u'collectivization' in list_tokens)
self.assertTrue(u'a' in list_tokens)
self.assertTrue(u'i.e.' in list_tokens)
def test_lower_case_set_true(self):
"""
Set the parameter lower to True and check that upper case 'Anarchism' token doesnt exist
"""
corpus = self.corpus_class(self.enwiki, processes=1, lower=True)
row = corpus.get_texts()
list_tokens = next(row)
self.assertTrue(u'Anarchism' not in list_tokens)
self.assertTrue(u'anarchism' in list_tokens)
def test_lower_case_set_false(self):
"""
Set the parameter lower to False and check that upper case Anarchism' token exists
"""
corpus = self.corpus_class(self.enwiki, processes=1, lower=False)
row = corpus.get_texts()
list_tokens = next(row)
self.assertTrue(u'Anarchism' in list_tokens)
self.assertTrue(u'anarchism' in list_tokens)
def test_min_token_len_not_set(self):
"""
Don't set the parameter token_min_len and check that 'a' as a token doesn't exist
Default token_min_len=2
"""
corpus = self.corpus_class(self.enwiki, processes=1)
self.assertTrue(u'a' not in next(corpus.get_texts()))
def test_min_token_len_set(self):
"""
Set the parameter token_min_len to 1 and check that 'a' as a token exists
"""
corpus = self.corpus_class(self.enwiki, processes=1, token_min_len=1)
self.assertTrue(u'a' in next(corpus.get_texts()))
def test_max_token_len_not_set(self):
"""
Don't set the parameter token_max_len and check that 'collectivisation' as a token doesn't exist
Default token_max_len=15
"""
corpus = self.corpus_class(self.enwiki, processes=1)
self.assertTrue(u'collectivization' not in next(corpus.get_texts()))
def test_max_token_len_set(self):
"""
Set the parameter token_max_len to 16 and check that 'collectivisation' as a token exists
"""
corpus = self.corpus_class(self.enwiki, processes=1, token_max_len=16)
self.assertTrue(u'collectivization' in next(corpus.get_texts()))
def test_removed_table_markup(self):
"""
Check if all the table markup has been removed.
"""
enwiki_file = datapath('enwiki-table-markup.xml.bz2')
corpus = self.corpus_class(enwiki_file)
texts = corpus.get_texts()
table_markup = ["style", "class", "border", "cellspacing", "cellpadding", "colspan", "rowspan"]
for text in texts:
for word in table_markup:
self.assertTrue(word not in text)
def test_get_stream(self):
wiki = self.corpus_class(self.enwiki)
sample_text_wiki = next(wiki.getstream()).decode()[1:14]
self.assertEqual(sample_text_wiki, "mediawiki xml")
# #TODO: sporadic failure to be investigated
# def test_get_texts_returns_generator_of_lists(self):
# corpus = self.corpus_class(self.enwiki)
# l = corpus.get_texts()
# self.assertEqual(type(l), types.GeneratorType)
# first = next(l)
# self.assertEqual(type(first), list)
# self.assertTrue(isinstance(first[0], bytes) or isinstance(first[0], str))
def test_sample_text(self):
# Cannot instantiate WikiCorpus from lines
pass
def test_sample_text_length(self):
# Cannot instantiate WikiCorpus from lines
pass
def test_sample_text_seed(self):
# Cannot instantiate WikiCorpus from lines
pass
def test_empty_input(self):
# An empty file is not legit XML
pass
def test_custom_filterfunction(self):
def reject_all(elem, *args, **kwargs):
return False
corpus = self.corpus_class(self.enwiki, filter_articles=reject_all)
texts = corpus.get_texts()
self.assertFalse(any(texts))
def keep_some(elem, title, *args, **kwargs):
return title[0] == 'C'
corpus = self.corpus_class(self.enwiki, filter_articles=reject_all)
corpus.metadata = True
texts = corpus.get_texts()
for text, (pageid, title) in texts:
self.assertEquals(title[0], 'C')
| TestWikiCorpus |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial010_py310.py | {
"start": 71,
"end": 1569
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where((Hero.age <= 35) | (Hero.age > 90))
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | facebook__pyre-check | client/commands/report_any_expressions.py | {
"start": 2088,
"end": 2930
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
any_expression_count: int
total_expression_count: int
# Records cases where the backend couldn't process the module.
error: Optional[str] = None
@staticmethod
def from_error(
error: str,
) -> ExpressionStatistics:
return ExpressionStatistics(
any_expression_count=0,
total_expression_count=0,
error=error,
)
@staticmethod
def from_coverage_at_path(
coverage_at_path: expression_level_coverage.CoverageAtPath,
) -> ExpressionStatistics:
return ExpressionStatistics(
any_expression_count=len(coverage_at_path.coverage_gaps),
total_expression_count=coverage_at_path.total_expressions,
)
@dataclasses.dataclass(frozen=True)
| ExpressionStatistics |
python | sympy__sympy | sympy/printing/c.py | {
"start": 4506,
"end": 22974
} | class ____(CodePrinter):
"""A printer to convert Python expressions to strings of C code"""
printmethod = "_ccode"
language = "C"
standard = "C89"
reserved_words = set(reserved_words)
_default_settings: dict[str, Any] = dict(CodePrinter._default_settings, **{
'precision': 17,
'user_functions': {},
'contract': True,
'dereference': set(),
'error_on_reserved': False,
})
type_aliases = {
real: float64,
complex_: complex128,
integer: intc
}
type_mappings: dict[Type, Any] = {
real: 'double',
intc: 'int',
float32: 'float',
float64: 'double',
integer: 'int',
bool_: 'bool',
int8: 'int8_t',
int16: 'int16_t',
int32: 'int32_t',
int64: 'int64_t',
uint8: 'int8_t',
uint16: 'int16_t',
uint32: 'int32_t',
uint64: 'int64_t',
}
type_headers = {
bool_: {'stdbool.h'},
int8: {'stdint.h'},
int16: {'stdint.h'},
int32: {'stdint.h'},
int64: {'stdint.h'},
uint8: {'stdint.h'},
uint16: {'stdint.h'},
uint32: {'stdint.h'},
uint64: {'stdint.h'},
}
# Macros needed to be defined when using a Type
type_macros: dict[Type, tuple[str, ...]] = {}
type_func_suffixes = {
float32: 'f',
float64: '',
float80: 'l'
}
type_literal_suffixes = {
float32: 'F',
float64: '',
float80: 'L'
}
type_math_macro_suffixes = {
float80: 'l'
}
math_macros = None
_ns = '' # namespace, C++ uses 'std::'
# known_functions-dict to copy
_kf: dict[str, Any] = known_functions_C89
def __init__(self, settings=None):
settings = settings or {}
if self.math_macros is None:
self.math_macros = settings.pop('math_macros', get_math_macros())
self.type_aliases = dict(chain(self.type_aliases.items(),
settings.pop('type_aliases', {}).items()))
self.type_mappings = dict(chain(self.type_mappings.items(),
settings.pop('type_mappings', {}).items()))
self.type_headers = dict(chain(self.type_headers.items(),
settings.pop('type_headers', {}).items()))
self.type_macros = dict(chain(self.type_macros.items(),
settings.pop('type_macros', {}).items()))
self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
settings.pop('type_func_suffixes', {}).items()))
self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
settings.pop('type_literal_suffixes', {}).items()))
self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
settings.pop('type_math_macro_suffixes', {}).items()))
super().__init__(settings)
self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
self._dereference = set(settings.get('dereference', []))
self.headers = set()
self.libraries = set()
self.macros = set()
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
""" Get code string as a statement - i.e. ending with a semicolon. """
return codestring if codestring.endswith(';') else codestring + ';'
def _get_comment(self, text):
return "/* {} */".format(text)
def _declare_number_const(self, name, value):
type_ = self.type_aliases[real]
var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
decl = Declaration(var)
return self._get_statement(self._print(decl))
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for i in range(rows) for j in range(cols))
@_as_macro_if_defined
def _print_Mul(self, expr, **kwargs):
return super()._print_Mul(expr, **kwargs)
@_as_macro_if_defined
def _print_Pow(self, expr):
if "Pow" in self.known_functions:
return self._print_Function(expr)
PREC = precedence(expr)
suffix = self._get_func_suffix(real)
if equal_valued(expr.exp, -1):
return '%s/%s' % (self._print_Float(Float(1.0)), self.parenthesize(expr.base, PREC))
elif equal_valued(expr.exp, 0.5):
return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
elif expr.exp == S.One/3 and self.standard != 'C89':
return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
else:
return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
self._print(expr.exp))
def _print_Mod(self, expr):
num, den = expr.args
if num.is_integer and den.is_integer:
PREC = precedence(expr)
snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
# % is remainder (same sign as numerator), not modulo (same sign as
# denominator), in C. Hence, % only works as modulo if both numbers
# have the same sign
if (num.is_nonnegative and den.is_nonnegative or
num.is_nonpositive and den.is_nonpositive):
return f"{snum} % {sden}"
return f"(({snum} % {sden}) + {sden}) % {sden}"
# Not guaranteed integer
return self._print_math_func(expr, known='fmod')
def _print_Rational(self, expr):
p, q = int(expr.p), int(expr.q)
suffix = self._get_literal_suffix(real)
return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
def _print_Indexed(self, expr):
# calculate index for 1d array
offset = getattr(expr.base, 'offset', S.Zero)
strides = getattr(expr.base, 'strides', None)
indices = expr.indices
if strides is None or isinstance(strides, str):
dims = expr.shape
shift = S.One
temp = ()
if strides == 'C' or strides is None:
traversal = reversed(range(expr.rank))
indices = indices[::-1]
elif strides == 'F':
traversal = range(expr.rank)
for i in traversal:
temp += (shift,)
shift *= dims[i]
strides = temp
flat_index = sum(x[0]*x[1] for x in zip(indices, strides)) + offset
return "%s[%s]" % (self._print(expr.base.label),
self._print(flat_index))
@_as_macro_if_defined
def _print_NumberSymbol(self, expr):
return super()._print_NumberSymbol(expr)
def _print_Infinity(self, expr):
return 'HUGE_VAL'
def _print_NegativeInfinity(self, expr):
return '-HUGE_VAL'
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if expr.has(Assignment):
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s) {" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else {")
else:
lines.append("else if (%s) {" % self._print(c))
code0 = self._print(e)
lines.append(code0)
lines.append("}")
return "\n".join(lines)
else:
# The piecewise was used in an expression, need to do inline
# operators. This has the downside that inline operators will
# not work for statements that span multiple lines (Matrix or
# Indexed expressions).
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
self._print(e))
for e, c in expr.args[:-1]]
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
def _print_ITE(self, expr):
from sympy.functions import Piecewise
return self._print(expr.rewrite(Piecewise, deep=False))
def _print_MatrixElement(self, expr):
return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
strict=True), expr.j + expr.i*expr.parent.shape[1])
def _print_Symbol(self, expr):
name = super()._print_Symbol(expr)
if expr in self._settings['dereference']:
return '(*{})'.format(name)
else:
return name
def _print_Relational(self, expr):
lhs_code = self._print(expr.lhs)
rhs_code = self._print(expr.rhs)
op = expr.rel_op
return "{} {} {}".format(lhs_code, op, rhs_code)
def _print_For(self, expr):
target = self._print(expr.target)
if isinstance(expr.iterable, Range):
start, stop, step = expr.iterable.args
else:
raise NotImplementedError("Only iterable currently supported is Range")
body = self._print(expr.body)
return ('for ({target} = {start}; {target} < {stop}; {target} += '
'{step}) {{\n{body}\n}}').format(target=target, start=start,
stop=stop, step=step, body=body)
def _print_sign(self, func):
return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
def _print_Max(self, expr):
if "Max" in self.known_functions:
return self._print_Function(expr)
def inner_print_max(args): # The more natural abstraction of creating
if len(args) == 1: # and printing smaller Max objects is slow
return self._print(args[0]) # when there are many arguments.
half = len(args) // 2
return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
'a': inner_print_max(args[:half]),
'b': inner_print_max(args[half:])
}
return inner_print_max(expr.args)
def _print_Min(self, expr):
if "Min" in self.known_functions:
return self._print_Function(expr)
def inner_print_min(args): # The more natural abstraction of creating
if len(args) == 1: # and printing smaller Min objects is slow
return self._print(args[0]) # when there are many arguments.
half = len(args) // 2
return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
'a': inner_print_min(args[:half]),
'b': inner_print_min(args[half:])
}
return inner_print_min(expr.args)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
if isinstance(code, str):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_token = ('{', '(', '{\n', '(\n')
dec_token = ('}', ')')
code = [line.lstrip(' \t') for line in code]
increase = [int(any(map(line.endswith, inc_token))) for line in code]
decrease = [int(any(map(line.startswith, dec_token))) for line in code]
pretty = []
level = 0
for n, line in enumerate(code):
if line in ('', '\n'):
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def _get_func_suffix(self, type_):
return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
def _get_literal_suffix(self, type_):
return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
def _get_math_macro_suffix(self, type_):
alias = self.type_aliases.get(type_, type_)
dflt = self.type_math_macro_suffixes.get(alias, '')
return self.type_math_macro_suffixes.get(type_, dflt)
def _print_Tuple(self, expr):
return '{'+', '.join(self._print(e) for e in expr)+'}'
_print_List = _print_Tuple
def _print_Type(self, type_):
self.headers.update(self.type_headers.get(type_, set()))
self.macros.update(self.type_macros.get(type_, set()))
return self._print(self.type_mappings.get(type_, type_.name))
def _print_Declaration(self, decl):
from sympy.codegen.cnodes import restrict
var = decl.variable
val = var.value
if var.type == untyped:
raise ValueError("C does not support untyped variables")
if isinstance(var, Pointer):
result = '{vc}{t} *{pc} {r}{s}'.format(
vc='const ' if value_const in var.attrs else '',
t=self._print(var.type),
pc=' const' if pointer_const in var.attrs else '',
r='restrict ' if restrict in var.attrs else '',
s=self._print(var.symbol)
)
elif isinstance(var, Variable):
result = '{vc}{t} {s}'.format(
vc='const ' if value_const in var.attrs else '',
t=self._print(var.type),
s=self._print(var.symbol)
)
else:
raise NotImplementedError("Unknown type of var: %s" % type(var))
if val != None: # Must be "!= None", cannot be "is not None"
result += ' = %s' % self._print(val)
return result
def _print_Float(self, flt):
type_ = self.type_aliases.get(real, real)
self.macros.update(self.type_macros.get(type_, set()))
suffix = self._get_literal_suffix(type_)
num = str(flt.evalf(type_.decimal_dig))
if 'e' not in num and '.' not in num:
num += '.0'
num_parts = num.split('e')
num_parts[0] = num_parts[0].rstrip('0')
if num_parts[0].endswith('.'):
num_parts[0] += '0'
return 'e'.join(num_parts) + suffix
@requires(headers={'stdbool.h'})
def _print_BooleanTrue(self, expr):
return 'true'
@requires(headers={'stdbool.h'})
def _print_BooleanFalse(self, expr):
return 'false'
def _print_Element(self, elem):
if elem.strides == None: # Must be "== None", cannot be "is None"
if elem.offset != None: # Must be "!= None", cannot be "is not None"
raise ValueError("Expected strides when offset is given")
idxs = ']['.join((self._print(arg) for arg in elem.indices))
else:
global_idx = sum(i*s for i, s in zip(elem.indices, elem.strides))
if elem.offset != None: # Must be "!= None", cannot be "is not None"
global_idx += elem.offset
idxs = self._print(global_idx)
return "{symb}[{idxs}]".format(
symb=self._print(elem.symbol),
idxs=idxs
)
def _print_CodeBlock(self, expr):
""" Elements of code blocks printed as statements. """
return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
def _print_While(self, expr):
return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
apply=lambda arg: self._print(arg)))
def _print_Scope(self, expr):
return '{\n%s\n}' % self._print_CodeBlock(expr.body)
@requires(headers={'stdio.h'})
def _print_Print(self, expr):
if expr.file == none:
template = 'printf({fmt}, {pargs})'
else:
template = 'fprintf(%(out)s, {fmt}, {pargs})' % {
'out': self._print(expr.file)
}
return template.format(
fmt="%s\n" if expr.format_string == none else self._print(expr.format_string),
pargs=', '.join((self._print(arg) for arg in expr.print_args))
)
def _print_Stream(self, strm):
return strm.name
def _print_FunctionPrototype(self, expr):
pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters))
return "%s %s(%s)" % (
tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,)
)
def _print_FunctionDefinition(self, expr):
return "%s%s" % (self._print_FunctionPrototype(expr),
self._print_Scope(expr))
def _print_Return(self, expr):
arg, = expr.args
return 'return %s' % self._print(arg)
def _print_CommaOperator(self, expr):
return '(%s)' % ', '.join((self._print(arg) for arg in expr.args))
def _print_Label(self, expr):
if expr.body == none:
return '%s:' % str(expr.name)
if len(expr.body.args) == 1:
return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body))
return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body))
def _print_goto(self, expr):
return 'goto %s' % expr.label.name
def _print_PreIncrement(self, expr):
arg, = expr.args
return '++(%s)' % self._print(arg)
def _print_PostIncrement(self, expr):
arg, = expr.args
return '(%s)++' % self._print(arg)
def _print_PreDecrement(self, expr):
arg, = expr.args
return '--(%s)' % self._print(arg)
def _print_PostDecrement(self, expr):
arg, = expr.args
return '(%s)--' % self._print(arg)
def _print_struct(self, expr):
return "%(keyword)s %(name)s {\n%(lines)s}" % {
"keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join(
[self._print(decl) for decl in expr.declarations] + [''])
}
def _print_BreakToken(self, _):
return 'break'
def _print_ContinueToken(self, _):
return 'continue'
_print_union = _print_struct
| C89CodePrinter |
python | lazyprogrammer__machine_learning_examples | rnn_class/rrnn_language.py | {
"start": 526,
"end": 6854
} | class ____:
def __init__(self, D, M, V):
self.D = D # dimensionality of word embedding
self.M = M # hidden layer size
self.V = V # vocabulary size
def fit(self, X, learning_rate=10., mu=0.9, reg=0., activation=T.tanh, epochs=500, show_fig=False):
N = len(X)
D = self.D
M = self.M
V = self.V
# initial weights
We = init_weight(V, D)
Wx = init_weight(D, M)
Wh = init_weight(M, M)
bh = np.zeros(M)
h0 = np.zeros(M)
# z = np.ones(M)
Wxz = init_weight(D, M)
Whz = init_weight(M, M)
bz = np.zeros(M)
Wo = init_weight(M, V)
bo = np.zeros(V)
thX, thY, py_x, prediction = self.set(We, Wx, Wh, bh, h0, Wxz, Whz, bz, Wo, bo, activation)
lr = T.scalar('lr')
cost = -T.mean(T.log(py_x[T.arange(thY.shape[0]), thY]))
grads = T.grad(cost, self.params)
dparams = [theano.shared(p.get_value()*0) for p in self.params]
updates = []
for p, dp, g in zip(self.params, dparams, grads):
new_dp = mu*dp - lr*g
updates.append((dp, new_dp))
new_p = p + new_dp
updates.append((p, new_p))
self.predict_op = theano.function(inputs=[thX], outputs=prediction)
self.train_op = theano.function(
inputs=[thX, thY, lr],
outputs=[cost, prediction],
updates=updates
)
costs = []
for i in range(epochs):
X = shuffle(X)
n_correct = 0
n_total = 0
cost = 0
for j in range(N):
if np.random.random() < 0.1:
input_sequence = [0] + X[j]
output_sequence = X[j] + [1]
else:
input_sequence = [0] + X[j][:-1]
output_sequence = X[j]
n_total += len(output_sequence)
# we set 0 to start and 1 to end
c, p = self.train_op(input_sequence, output_sequence, learning_rate)
# print "p:", p
cost += c
# print "j:", j, "c:", c/len(X[j]+1)
for pj, xj in zip(p, output_sequence):
if pj == xj:
n_correct += 1
print("i:", i, "cost:", cost, "correct rate:", (float(n_correct)/n_total))
if (i + 1) % 500 == 0:
learning_rate /= 2
costs.append(cost)
if show_fig:
plt.plot(costs)
plt.show()
def save(self, filename):
np.savez(filename, *[p.get_value() for p in self.params])
@staticmethod
def load(filename, activation):
# TODO: would prefer to save activation to file too
npz = np.load(filename)
We = npz['arr_0']
Wx = npz['arr_1']
Wh = npz['arr_2']
bh = npz['arr_3']
h0 = npz['arr_4']
Wxz = npz['arr_5']
Whz = npz['arr_6']
bz = npz['arr_7']
Wo = npz['arr_8']
bo = npz['arr_9']
V, D = We.shape
_, M = Wx.shape
rnn = SimpleRNN(D, M, V)
rnn.set(We, Wx, Wh, bh, h0, Wxz, Whz, bz, Wo, bo, activation)
return rnn
def set(self, We, Wx, Wh, bh, h0, Wxz, Whz, bz, Wo, bo, activation):
self.f = activation
# redundant - see how you can improve it
self.We = theano.shared(We)
self.Wx = theano.shared(Wx)
self.Wh = theano.shared(Wh)
self.bh = theano.shared(bh)
self.h0 = theano.shared(h0)
self.Wxz = theano.shared(Wxz)
self.Whz = theano.shared(Whz)
self.bz = theano.shared(bz)
self.Wo = theano.shared(Wo)
self.bo = theano.shared(bo)
self.params = [self.We, self.Wx, self.Wh, self.bh, self.h0, self.Wxz, self.Whz, self.bz, self.Wo, self.bo]
thX = T.ivector('X')
Ei = self.We[thX] # will be a TxD matrix
thY = T.ivector('Y')
def recurrence(x_t, h_t1):
# returns h(t), y(t)
hhat_t = self.f(x_t.dot(self.Wx) + h_t1.dot(self.Wh) + self.bh)
z_t = T.nnet.sigmoid(x_t.dot(self.Wxz) + h_t1.dot(self.Whz) + self.bz)
h_t = (1 - z_t) * h_t1 + z_t * hhat_t
y_t = T.nnet.softmax(h_t.dot(self.Wo) + self.bo)
return h_t, y_t
[h, y], _ = theano.scan(
fn=recurrence,
outputs_info=[self.h0, None],
sequences=Ei,
n_steps=Ei.shape[0],
)
py_x = y[:, 0, :]
prediction = T.argmax(py_x, axis=1)
self.predict_op = theano.function(
inputs=[thX],
outputs=[py_x, prediction],
allow_input_downcast=True,
)
return thX, thY, py_x, prediction
def generate(self, word2idx):
# convert word2idx -> idx2word
idx2word = {v:k for k,v in iteritems(word2idx)}
V = len(word2idx)
# generate 4 lines at a time
n_lines = 0
# why? because using the START symbol will always yield the same first word!
X = [ 0 ]
while n_lines < 4:
# print "X:", X
PY_X, _ = self.predict_op(X)
PY_X = PY_X[-1].flatten()
P = [ np.random.choice(V, p=PY_X)]
X = np.concatenate([X, P]) # append to the sequence
# print "P.shape:", P.shape, "P:", P
P = P[-1] # just grab the most recent prediction
if P > 1:
# it's a real word, not start/end token
word = idx2word[P]
print(word, end=" ")
elif P == 1:
# end token
n_lines += 1
X = [0]
print('')
def train_poetry():
# students: tanh didn't work but you should try it
sentences, word2idx = get_robert_frost()
rnn = SimpleRNN(50, 50, len(word2idx))
rnn.fit(sentences, learning_rate=1e-4, show_fig=True, activation=T.nnet.relu, epochs=2000)
rnn.save('RRNN_D50_M50_epochs2000_relu.npz')
def generate_poetry():
sentences, word2idx = get_robert_frost()
rnn = SimpleRNN.load('RRNN_D50_M50_epochs2000_relu.npz', T.nnet.relu)
rnn.generate(word2idx)
if __name__ == '__main__':
train_poetry()
generate_poetry()
| SimpleRNN |
python | openai__openai-python | src/openai/types/evals/create_eval_completions_run_data_source_param.py | {
"start": 1848,
"end": 2048
} | class ____(TypedDict, total=False):
id: Required[str]
"""The identifier of the file."""
type: Required[Literal["file_id"]]
"""The type of jsonl source. Always `file_id`."""
| SourceFileID |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 15516,
"end": 22369
} | class ____(CompositeModel):
_value_type = None
_data_type = None
def __init__(self, dmm, fe_type, members):
super(StructModel, self).__init__(dmm, fe_type)
if members:
self._fields, self._members = zip(*members)
else:
self._fields = self._members = ()
self._models = tuple([self._dmm.lookup(t) for t in self._members])
def get_member_fe_type(self, name):
"""
StructModel-specific: get the Numba type of the field named *name*.
"""
pos = self.get_field_position(name)
return self._members[pos]
def get_value_type(self):
if self._value_type is None:
self._value_type = ir.LiteralStructType([t.get_value_type()
for t in self._models])
return self._value_type
def get_data_type(self):
if self._data_type is None:
self._data_type = ir.LiteralStructType([t.get_data_type()
for t in self._models])
return self._data_type
def get_argument_type(self):
return tuple([t.get_argument_type() for t in self._models])
def get_return_type(self):
return self.get_data_type()
def _as(self, methname, builder, value):
extracted = []
for i, dm in enumerate(self._models):
extracted.append(getattr(dm, methname)(builder,
self.get(builder, value, i)))
return tuple(extracted)
def _from(self, methname, builder, value):
struct = ir.Constant(self.get_value_type(), ir.Undefined)
for i, (dm, val) in enumerate(zip(self._models, value)):
v = getattr(dm, methname)(builder, val)
struct = self.set(builder, struct, v, i)
return struct
def as_data(self, builder, value):
"""
Converts the LLVM struct in `value` into a representation suited for
storing into arrays.
Note
----
Current implementation rarely changes how types are represented for
"value" and "data". This is usually a pointless rebuild of the
immutable LLVM struct value. Luckily, LLVM optimization removes all
redundancy.
Sample usecase: Structures nested with pointers to other structures
that can be serialized into a flat representation when storing into
array.
"""
elems = self._as("as_data", builder, value)
struct = ir.Constant(self.get_data_type(), ir.Undefined)
for i, el in enumerate(elems):
struct = builder.insert_value(struct, el, [i])
return struct
def from_data(self, builder, value):
"""
Convert from "data" representation back into "value" representation.
Usually invoked when loading from array.
See notes in `as_data()`
"""
vals = [builder.extract_value(value, [i])
for i in range(len(self._members))]
return self._from("from_data", builder, vals)
def load_from_data_pointer(self, builder, ptr, align=None):
values = []
for i, model in enumerate(self._models):
elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i)
val = model.load_from_data_pointer(builder, elem_ptr, align)
values.append(val)
struct = ir.Constant(self.get_value_type(), ir.Undefined)
for i, val in enumerate(values):
struct = self.set(builder, struct, val, i)
return struct
def as_argument(self, builder, value):
return self._as("as_argument", builder, value)
def from_argument(self, builder, value):
return self._from("from_argument", builder, value)
def as_return(self, builder, value):
elems = self._as("as_data", builder, value)
struct = ir.Constant(self.get_data_type(), ir.Undefined)
for i, el in enumerate(elems):
struct = builder.insert_value(struct, el, [i])
return struct
def from_return(self, builder, value):
vals = [builder.extract_value(value, [i])
for i in range(len(self._members))]
return self._from("from_data", builder, vals)
def get(self, builder, val, pos):
"""Get a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
Extracted value
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return builder.extract_value(val, [pos],
name="extracted." + self._fields[pos])
def set(self, builder, stval, val, pos):
"""Set a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
stval:
LLVM struct value
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
A new LLVM struct with the value inserted
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return builder.insert_value(stval, val, [pos],
name="inserted." + self._fields[pos])
def get_field_position(self, field):
try:
return self._fields.index(field)
except ValueError:
raise KeyError("%s does not have a field named %r"
% (self.__class__.__name__, field))
@property
def field_count(self):
return len(self._fields)
def get_type(self, pos):
"""Get the frontend type (numba type) of a field given the position
or the fieldname
Args
----
pos: int or str
field index or field name
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return self._members[pos]
def get_model(self, pos):
"""
Get the datamodel of a field given the position or the fieldname.
Args
----
pos: int or str
field index or field name
"""
return self._models[pos]
def traverse(self, builder):
def getter(k, value):
if value.type != self.get_value_type():
args = self.get_value_type(), value.type
raise TypeError("expecting {0} but got {1}".format(*args))
return self.get(builder, value, k)
return [(self.get_type(k), partial(getter, k)) for k in self._fields]
def inner_models(self):
return self._models
@register_default(types.Complex)
| StructModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 5910,
"end": 9968
} | class ____(parameterized.TestCase, test.TestCase):
def testShapeInferenceNoBatch(self):
self.assertEqual((2, 2), linalg_ops.eye(num_rows=2).shape)
self.assertEqual((2, 3), linalg_ops.eye(num_rows=2, num_columns=3).shape)
def testShapeInferenceStaticBatch(self):
batch_shape = (2, 3)
self.assertEqual(
(2, 3, 2, 2),
linalg_ops.eye(num_rows=2, batch_shape=batch_shape).shape)
self.assertEqual(
(2, 3, 2, 3),
linalg_ops.eye(
num_rows=2, num_columns=3, batch_shape=batch_shape).shape)
@parameterized.named_parameters(
("DynamicRow",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: None),
("DynamicRowStaticColumn",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: 3),
("StaticRowDynamicColumn",
lambda: 2,
lambda: array_ops.placeholder_with_default(3, shape=None)),
("DynamicRowDynamicColumn",
lambda: array_ops.placeholder_with_default(2, shape=None),
lambda: array_ops.placeholder_with_default(3, shape=None)))
def testShapeInferenceStaticBatchWith(self, num_rows_fn, num_columns_fn):
num_rows = num_rows_fn()
num_columns = num_columns_fn()
batch_shape = (2, 3)
identity_matrix = linalg_ops.eye(
num_rows=num_rows,
num_columns=num_columns,
batch_shape=batch_shape)
self.assertEqual(4, identity_matrix.shape.ndims)
self.assertEqual((2, 3), identity_matrix.shape[:2])
if num_rows is not None and not isinstance(num_rows, tensor.Tensor):
self.assertEqual(2, identity_matrix.shape[-2])
if num_columns is not None and not isinstance(num_columns, tensor.Tensor):
self.assertEqual(3, identity_matrix.shape[-1])
@parameterized.parameters(
itertools.product(
# num_rows
[0, 1, 2, 5],
# num_columns
[None, 0, 1, 2, 5],
# batch_shape
[None, [], [2], [2, 3]],
# dtype
[
dtypes.int32,
dtypes.int64,
dtypes.float32,
dtypes.float64,
dtypes.complex64,
dtypes.complex128
])
)
def test_eye_no_placeholder(self, num_rows, num_columns, batch_shape, dtype):
eye_np = np.eye(num_rows, M=num_columns, dtype=dtype.as_numpy_dtype)
if batch_shape is not None:
eye_np = np.tile(eye_np, batch_shape + [1, 1])
eye_tf = self.evaluate(linalg_ops.eye(
num_rows,
num_columns=num_columns,
batch_shape=batch_shape,
dtype=dtype))
self.assertAllEqual(eye_np, eye_tf)
@parameterized.parameters(
itertools.product(
# num_rows
[0, 1, 2, 5],
# num_columns
[0, 1, 2, 5],
# batch_shape
[[], [2], [2, 3]],
# dtype
[
dtypes.int32,
dtypes.int64,
dtypes.float32,
dtypes.float64,
dtypes.complex64,
dtypes.complex128
])
)
@test_util.run_deprecated_v1
def test_eye_with_placeholder(
self, num_rows, num_columns, batch_shape, dtype):
eye_np = np.eye(num_rows, M=num_columns, dtype=dtype.as_numpy_dtype)
eye_np = np.tile(eye_np, batch_shape + [1, 1])
num_rows_placeholder = array_ops.placeholder(
dtypes.int32, name="num_rows")
num_columns_placeholder = array_ops.placeholder(
dtypes.int32, name="num_columns")
batch_shape_placeholder = array_ops.placeholder(
dtypes.int32, name="batch_shape")
eye = linalg_ops.eye(
num_rows_placeholder,
num_columns=num_columns_placeholder,
batch_shape=batch_shape_placeholder,
dtype=dtype)
with self.session() as sess:
eye_tf = sess.run(
eye,
feed_dict={
num_rows_placeholder: num_rows,
num_columns_placeholder: num_columns,
batch_shape_placeholder: batch_shape
})
self.assertAllEqual(eye_np, eye_tf)
| EyeTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 2685,
"end": 3339
} | class ____(graphene.Enum):
LOADING = "LOADING"
LOADED = "LOADED"
class Meta:
name = "RepositoryLocationLoadStatus"
@classmethod
def from_python_status(cls, python_status):
check.inst_param(python_status, "python_status", CodeLocationLoadStatus)
if python_status == CodeLocationLoadStatus.LOADING:
return GrapheneRepositoryLocationLoadStatus.LOADING
elif python_status == CodeLocationLoadStatus.LOADED:
return GrapheneRepositoryLocationLoadStatus.LOADED
else:
check.failed(f"Invalid location load status: {python_status}")
| GrapheneRepositoryLocationLoadStatus |
python | dask__dask | dask/bag/tests/test_bag.py | {
"start": 33109,
"end": 43216
} | class ____(db.Bag):
def get(self, key, default=None):
return self.map(lambda d: d.get(key, default))
def set(self, key, value):
def setter(d):
d[key] = value
return d
return self.map(setter)
def test_bag_class_extend():
dictbag = BagOfDicts(*db.from_sequence([{"a": {"b": "c"}}])._args)
assert dictbag.get("a").get("b").compute()[0] == "c"
assert dictbag.get("a").set("d", "EXTENSIBILITY!!!").compute()[0] == {
"b": "c",
"d": "EXTENSIBILITY!!!",
}
assert isinstance(dictbag.get("a").get("b"), BagOfDicts)
def test_gh715():
bin_data = "\u20ac".encode()
with tmpfile() as fn:
with open(fn, "wb") as f:
f.write(bin_data)
a = db.read_text(fn)
assert a.compute()[0] == bin_data.decode("utf-8")
def test_bag_compute_forward_kwargs():
x = db.from_sequence([1, 2, 3]).map(lambda a: a + 1)
x.compute(bogus_keyword=10)
def test_to_delayed():
b = db.from_sequence([1, 2, 3, 4, 5, 6], npartitions=3)
a, b, c = b.map(inc).to_delayed()
assert all(isinstance(x, Delayed) for x in [a, b, c])
assert b.compute() == [4, 5]
b = db.from_sequence([1, 2, 3, 4, 5, 6], npartitions=3)
t = b.sum().to_delayed()
assert isinstance(t, Delayed)
assert t.compute() == 21
def test_to_delayed_optimize_graph(tmpdir, monkeypatch):
calls = 0
from dask.bag.core import reify
def count_reify(*args, **kwargs):
nonlocal calls
calls += 1
return reify(*args, **kwargs)
monkeypatch.setattr(dask.bag.core, "reify", count_reify)
b = db.from_sequence([1, 2, 3, 4, 5, 6], npartitions=1)
b2 = b.map(inc).map(inc).map(inc)
[d] = b2.to_delayed()
calls = 0
d.compute()
assert calls == 1
calls = 0
b = db.from_sequence([1, 2, 3, 4, 5, 6], npartitions=1)
b2 = b.map(inc).map(inc).map(inc)
[d] = b2.to_delayed()
assert d.__dask_layers__() != b2.__dask_layers__()
[d2] = b2.to_delayed(optimize_graph=False)
assert dict(d2.dask) == dict(b2.dask)
assert d2.__dask_layers__() == b2.__dask_layers__()
calls = 0
result = d.compute()
assert calls == 1
calls = 0
result2 = d2.compute()
assert calls == 3
assert result == result2
x = b2.sum()
d = x.to_delayed()
assert d.__dask_layers__() == x.__dask_layers__()
d2 = x.to_delayed(optimize_graph=False)
assert dict(d2.dask) == dict(x.dask)
assert d2.__dask_layers__() == x.__dask_layers__()
calls = 0
assert d.compute() == d2.compute()
assert calls == 3
calls = 0
[d] = b2.to_textfiles(str(tmpdir), compute=False)
assert calls == 0
def test_from_delayed():
from dask.delayed import delayed
a, b, c = delayed([1, 2, 3]), delayed([4, 5, 6]), delayed([7, 8, 9])
bb = from_delayed([a, b, c])
assert bb.name == from_delayed([a, b, c]).name
assert isinstance(bb, Bag)
assert list(bb) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
asum_value = delayed(sum)(a)
asum_item = db.Item.from_delayed(asum_value)
assert asum_value.compute() == asum_item.compute() == 6
def test_from_delayed_iterator():
from dask.delayed import delayed
def lazy_records(n):
return ({"operations": [1, 2]} for _ in range(n))
delayed_records = delayed(lazy_records, pure=False)
bag = db.from_delayed([delayed_records(5) for _ in range(5)])
assert db.compute(
bag.count(),
bag.pluck("operations").count(),
bag.pluck("operations").flatten().count(),
scheduler="sync",
) == (25, 25, 50)
def test_range():
for npartitions in [1, 7, 10, 28]:
b = db.range(100, npartitions=npartitions)
assert len(b.dask) == npartitions
assert b.npartitions == npartitions
assert list(b) == list(range(100))
@pytest.mark.parametrize("npartitions", [1, 7, 10, 28])
def test_zip(npartitions, hi=1000):
evens = db.from_sequence(range(0, hi, 2), npartitions=npartitions)
odds = db.from_sequence(range(1, hi, 2), npartitions=npartitions)
pairs = db.zip(evens, odds)
assert pairs.npartitions == evens.npartitions
assert pairs.npartitions == odds.npartitions
assert list(pairs) == list(zip(range(0, hi, 2), range(1, hi, 2)))
@pytest.mark.parametrize("nin", [1, 2, 7, 11, 23])
@pytest.mark.parametrize("nout", [1, 2, 5, 12, 23])
def test_repartition_npartitions(nin, nout):
b = db.from_sequence(range(100), npartitions=nin)
c = b.repartition(npartitions=nout)
assert c.npartitions == nout
assert_eq(b, c)
results = dask.get(c.dask, c.__dask_keys__())
assert all(results)
@pytest.mark.parametrize(
"nin, nout",
[
(1, 1),
(2, 1),
(5, 1),
(1, 2),
(2, 2),
(5, 2),
(1, 5),
(2, 5),
(5, 5),
],
)
def test_repartition_partition_size(nin, nout):
b = db.from_sequence(range(1, 100), npartitions=nin)
total_mem = sum(b.map_partitions(total_mem_usage).compute())
c = b.repartition(partition_size=(total_mem // nout))
assert c.npartitions >= nout
assert_eq(b, c)
def test_multiple_repartition_partition_size():
b = db.from_sequence(range(1, 100), npartitions=1)
total_mem = sum(b.map_partitions(total_mem_usage).compute())
c = b.repartition(partition_size=(total_mem // 2))
assert c.npartitions >= 2
assert_eq(b, c)
d = c.repartition(partition_size=(total_mem // 5))
assert d.npartitions >= 5
assert_eq(c, d)
def test_repartition_partition_size_complex_dtypes():
np = pytest.importorskip("numpy")
b = db.from_sequence([np.array(range(100)) for _ in range(4)], npartitions=1)
total_mem = sum(b.map_partitions(total_mem_usage).compute())
new_partition_size = total_mem // 4
c = b.repartition(partition_size=new_partition_size)
assert c.npartitions >= 4
assert_eq(b, c)
def test_repartition_names():
b = db.from_sequence(range(100), npartitions=5)
c = b.repartition(2)
assert b.name != c.name
d = b.repartition(20)
assert b.name != c.name
assert c.name != d.name
c = b.repartition(5)
assert b is c
def test_repartition_input_errors():
with pytest.raises(ValueError):
bag = db.from_sequence(range(10))
bag.repartition(npartitions=5, partition_size="5MiB")
def test_accumulate():
parts = [[1, 2, 3], [4, 5], [], [6, 7]]
dsk = {("test", i): p for (i, p) in enumerate(parts)}
b = db.Bag(dsk, "test", len(parts))
r = b.accumulate(add)
assert r.name == b.accumulate(add).name
assert r.name != b.accumulate(add, -1).name
assert r.compute() == [1, 3, 6, 10, 15, 21, 28]
assert b.accumulate(add, -1).compute() == [-1, 0, 2, 5, 9, 14, 20, 27]
assert b.accumulate(add).map(inc).compute() == [2, 4, 7, 11, 16, 22, 29]
b = db.from_sequence([1, 2, 3], npartitions=1)
assert b.accumulate(add).compute() == [1, 3, 6]
def test_groupby_tasks():
b = db.from_sequence(range(160), npartitions=4)
out = b.groupby(lambda x: x % 10, max_branch=4, shuffle="tasks")
partitions = dask.get(out.dask, out.__dask_keys__())
for a in partitions:
for b in partitions:
if a is not b:
assert not set(pluck(0, a)) & set(pluck(0, b))
b = db.from_sequence(range(1000), npartitions=100)
out = b.groupby(lambda x: x % 123, shuffle="tasks")
assert len(out.dask) < 100**2
partitions = dask.get(out.dask, out.__dask_keys__())
for a in partitions:
for b in partitions:
if a is not b:
assert not set(pluck(0, a)) & set(pluck(0, b))
b = db.from_sequence(range(10000), npartitions=345)
out = b.groupby(lambda x: x % 2834, max_branch=24, shuffle="tasks")
partitions = dask.get(out.dask, out.__dask_keys__())
for a in partitions:
for b in partitions:
if a is not b:
assert not set(pluck(0, a)) & set(pluck(0, b))
def test_groupby_tasks_names():
b = db.from_sequence(range(160), npartitions=4)
func = lambda x: x % 10
func2 = lambda x: x % 20
assert set(b.groupby(func, max_branch=4, shuffle="tasks").dask) == set(
b.groupby(func, max_branch=4, shuffle="tasks").dask
)
assert set(b.groupby(func, max_branch=4, shuffle="tasks").dask) != set(
b.groupby(func, max_branch=2, shuffle="tasks").dask
)
assert set(b.groupby(func, max_branch=4, shuffle="tasks").dask) != set(
b.groupby(func2, max_branch=4, shuffle="tasks").dask
)
@pytest.mark.parametrize(
"size,npartitions,groups", [(1000, 20, 100), (12345, 234, 1042), (100, 1, 50)]
)
def test_groupby_tasks_2(size, npartitions, groups):
func = lambda x: x % groups
b = db.range(size, npartitions=npartitions).groupby(func, shuffle="tasks")
result = b.compute(scheduler="sync")
assert dict(result) == groupby(func, range(size))
def test_groupby_tasks_3():
func = lambda x: x % 10
b = db.range(20, npartitions=5).groupby(func, shuffle="tasks", max_branch=2)
result = b.compute(scheduler="sync")
assert dict(result) == groupby(func, range(20))
# assert b.npartitions == 5
def test_to_textfiles_empty_partitions():
with tmpdir() as d:
b = db.range(5, npartitions=5).filter(lambda x: x == 1).map(str)
b.to_textfiles(os.path.join(d, "*.txt"))
assert len(os.listdir(d)) == 5
def test_reduction_empty():
b = db.from_sequence(range(10), npartitions=100)
assert_eq(b.filter(lambda x: x % 2 == 0).max(), 8)
assert_eq(b.filter(lambda x: x % 2 == 0).min(), 0)
@pytest.mark.parametrize("npartitions", [1, 2, 4])
def test_reduction_empty_aggregate(npartitions):
b = db.from_sequence([0, 0, 0, 1], npartitions=npartitions).filter(None)
assert_eq(b.min(split_every=2), 1)
vals = db.compute(b.min(split_every=2), b.max(split_every=2), scheduler="sync")
assert vals == (1, 1)
with pytest.raises(ValueError):
b = db.from_sequence([0, 0, 0, 0], npartitions=npartitions)
b.filter(None).min(split_every=2).compute(scheduler="sync")
| BagOfDicts |
python | doocs__leetcode | solution/3300-3399/3349.Adjacent Increasing Subarrays Detection I/Solution.py | {
"start": 0,
"end": 338
} | class ____:
def hasIncreasingSubarrays(self, nums: List[int], k: int) -> bool:
mx = pre = cur = 0
for i, x in enumerate(nums):
cur += 1
if i == len(nums) - 1 or x >= nums[i + 1]:
mx = max(mx, cur // 2, min(pre, cur))
pre, cur = cur, 0
return mx >= k
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/resources.py | {
"start": 15599,
"end": 16925
} | class ____(StateBackedDefinitionsLoader[DbtCloudWorkspaceData]):
workspace: DbtCloudWorkspace
translator: DagsterDbtTranslator
select: str
exclude: str
selector: str
@property
def defs_key(self) -> str:
return f"{DBT_CLOUD_RECONSTRUCTION_METADATA_KEY_PREFIX}.{self.workspace.unique_id}"
def fetch_state(self) -> DbtCloudWorkspaceData:
return self.workspace.fetch_workspace_data()
def defs_from_state(self, state: DbtCloudWorkspaceData) -> Definitions:
all_asset_specs, all_check_specs = build_dbt_specs(
manifest=state.manifest,
translator=self.translator,
select=self.select,
exclude=self.exclude,
selector=self.selector,
io_manager_key=None,
project=None,
)
all_asset_specs = [
spec.replace_attributes(kinds={"dbtcloud"} | spec.kinds - {"dbt"})
for spec in all_asset_specs
]
# External facing checks are not supported yet
# https://linear.app/dagster-labs/issue/AD-915/support-external-asset-checks-in-dbt-cloud-v2
@multi_asset_check(specs=all_check_specs)
def _all_asset_checks(): ...
return Definitions(assets=all_asset_specs, asset_checks=[_all_asset_checks])
| DbtCloudWorkspaceDefsLoader |
python | conda__conda | conda/exceptions.py | {
"start": 34145,
"end": 34409
} | class ____(CondaError, MemoryError):
def __init__(self, caused_by: Any, **kwargs):
message = "The conda process ran out of memory. Increase system memory and/or try again."
super().__init__(message, caused_by=caused_by, **kwargs)
| CondaMemoryError |
python | sanic-org__sanic | sanic/models/futures.py | {
"start": 1601,
"end": 1667
} | class ____(NamedTuple):
name: str
func: Callable
| FutureCommand |
python | google__jax | tests/pallas/mgpu_examples_test.py | {
"start": 1342,
"end": 34012
} | class ____:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epilogue_tile_n: int = 64
grid_minor_dim: int = 0
grid_tile_width: int = 1
def matmul0(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem, acc_tmem, acc_smem, consumed_barriers):
mi = lax.axis_index("m")
ni = lax.axis_index("n")
m_slice = pl.ds(mi * tile_m, tile_m)
n_slice = pl.ds(ni * tile_n, tile_n)
def do_mma(idxs, a_smem, b_smem):
(ki,) = idxs
arrive_barrier_slot = ki % 2
wait_barrier_slot = 1 - arrive_barrier_slot
plgpu.tcgen05_mma(
acc_tmem,
a_smem,
b_smem,
barrier=consumed_barriers.at[arrive_barrier_slot],
accumulate=(ki > 0),
)
plgpu.barrier_wait(consumed_barriers.at[wait_barrier_slot])
# Make sure the wait succeeds in the first iteration.
plgpu.barrier_arrive(consumed_barriers.at[1])
block_kwargs = dict(transforms=transforms, delay_release=1)
plgpu.emit_pipeline(
do_mma,
in_specs=[
plgpu.BlockSpec((tile_m, tile_k), lambda ki: (mi, ki), **block_kwargs),
plgpu.BlockSpec((tile_k, tile_n), lambda ki: (ki, ni), **block_kwargs),
],
grid=(k_iters,),
max_concurrent_steps=max_concurrent_steps,
)(a_gmem, b_gmem)
final_barrier = 1 - (k_iters % 2)
plgpu.barrier_wait(consumed_barriers.at[final_barrier])
acc_smem[...] = plgpu.async_load_tmem(acc_tmem).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem, out_gmem.at[m_slice, n_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((tile_m, tile_n), dtype, transforms=transforms),
consumed_barriers=plgpu.Barrier(
num_arrivals=1, num_barriers=2, orders_tensor_core=True
),
),
)
return f(a, b)
def matmul1(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * tile_m, tile_m)
n_slice = pl.ds(n_index * tile_n, tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot]
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot]
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(warp_id == 1)
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier)
plgpu.barrier_wait(mma_done_barrier)
acc_smem[...] = plgpu.async_load_tmem(acc_tmem).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem, out_gmem.at[m_slice, n_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k),
dtype,
transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n),
dtype,
transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((tile_m, tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(
num_arrivals=2, num_barriers=max_concurrent_steps
),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(
num_arrivals=1, num_barriers=1, orders_tensor_core=True
),
),
)
return f(a, b)
def matmul2(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // tile_m
n_iters = n // tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * tile_m, tile_m)
n_slice = pl.ds(n_index * tile_n, tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot]
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot]
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(warp_id == 1)
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier)
plgpu.barrier_wait(mma_done_barrier)
out_gmem_window = out_gmem.at[m_slice, n_slice]
for ni in range(tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms
),
acc_tmem=plgpu.TMEM((tile_m, tile_n), jnp.float32),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
)
)
return f(a, b)
def matmul3(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
is_lead_block = lax.axis_index("cluster") == 0
m_index = lax.axis_index("m")
n_index = lax.axis_index("n")
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(ki >= max_concurrent_steps)
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(mma_done_barrier, collective_axis="cluster")
plgpu.barrier_wait(mma_done_barrier)
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(m_iters, n_iters),
grid_names=("m", "n"),
cluster=(2,),
cluster_names=("cluster",),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
)
)
return f(a, b)
def matmul4(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier):
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters, n_iters), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
m_index, n_index = loop_info.index
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier,
collective_axis="cluster",
)
plgpu.wait_smem_to_gmem(0, wait_read_only=True) # Make sure that previous store is done.
plgpu.barrier_wait(mma_done_barrier)
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before MMA can overwrite TMEM.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1, orders_tensor_core=True),
),
)
return f(a, b)
def matmul5(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier, store_done_barrier):
wg_idx = lax.axis_index("wg")
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters, n_iters), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
m_index, n_index = loop_info.index
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
acc_slot = lax.rem(loop_info.local_index, jnp.int32(2))
mn_acc_tmem = acc_tmem.at[:, pl.ds(acc_slot * cluster_tile_n, cluster_tile_n)]
@pl.when(wg_idx == 0)
def _compute_wg():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
# Wait for store to complete (except for the first two steps).
@pl.when(jnp.logical_and(warp_id == 1, loop_info.local_index >= 2))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
mn_acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis="cluster",
)
@pl.when(wg_idx == 1)
def _store_wg():
# Ensure that copies from the previous mn step have completed.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(mn_acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before we signal.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
num_threads=2,
thread_name="wg",
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms,
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms,
),
acc_tmem=plgpu.TMEM((tile_m, 2 * cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2, orders_tensor_core=True),
store_done_barrier=plgpu.ClusterBarrier(
collective_axes=("cluster",),
num_arrivals=1,
num_barriers=2,
orders_tensor_core=True,
),
),
)
return f(a, b)
def matmul6(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
swizzle = plgpu.find_swizzle(tile_k * jnp.dtype(dtype).itemsize * 8)
swizzle_elems = swizzle // jnp.dtype(dtype).itemsize
transforms = (
plgpu.TilingTransform((8, swizzle_elems)), plgpu.SwizzleTransform(swizzle)
)
if m % tile_m != 0:
raise ValueError(f"{m=} must be divisible by {tile_m=}")
if n % tile_n != 0:
raise ValueError(f"{n=} must be divisible by {tile_n=}")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
cluster_tile_m = 2 * tile_m
cluster_tile_n = 2 * tile_n
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
max_concurrent_steps = config.max_concurrent_steps
def kernel(a_gmem, b_gmem, out_gmem,
a_smem, b_smem, acc_tmem, acc_smem,
load_barriers, consumed_barriers, mma_done_barrier, store_done_barrier):
wg_idx = lax.axis_index("wg")
is_lead_block = lax.axis_index("cluster") == 0
@plgpu.nd_loop((m_iters * n_iters,), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
(lin_idx,) = loop_info.index
m_index, n_index = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
m_slice = pl.ds(m_index * cluster_tile_m, cluster_tile_m)
n_slice = pl.ds(n_index * cluster_tile_n, cluster_tile_n)
acc_slot = lax.rem(loop_info.local_index, jnp.int32(2))
mn_acc_tmem = acc_tmem.at[:, pl.ds(acc_slot * cluster_tile_n, cluster_tile_n)]
@pl.when(wg_idx == 0)
def _compute_wg():
@pl.core_map(plgpu.WarpMesh(axis_name="warp"))
def _per_warp():
warp_id = lax.axis_index("warp")
@pl.when(warp_id == 0)
def _memory():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
@pl.when(jnp.logical_or(ki >= max_concurrent_steps, loop_info.local_index > 0))
def _(): # Make sure the data has been consumed before overwriting.
plgpu.barrier_wait(consumed_barriers.at[slot])
k_slice = pl.ds(ki * tile_k, tile_k)
plgpu.copy_gmem_to_smem(
a_gmem.at[m_slice, k_slice], a_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=0
)
plgpu.copy_gmem_to_smem(
b_gmem.at[k_slice, n_slice], b_smem.at[slot], load_barriers.at[slot],
collective_axes="cluster", partitioned_axis=1
)
lax.fori_loop(0, k_iters, _loop_body, None)
# Wait for store to complete (except for the first two steps).
@pl.when(jnp.logical_and(warp_id == 1, loop_info.local_index >= 2))
def _wait_store():
plgpu.barrier_wait(store_done_barrier.at[acc_slot])
@pl.when(jnp.logical_and(warp_id == 1, is_lead_block))
def _compute():
def _loop_body(ki, _):
slot = lax.rem(ki, max_concurrent_steps)
plgpu.barrier_wait(load_barriers.at[slot]) # Wait for data to arrive.
plgpu.tcgen05_mma(
mn_acc_tmem,
a_smem.at[slot],
b_smem.at[slot],
consumed_barriers.at[slot],
accumulate=(ki > 0),
collective_axis="cluster",
)
lax.fori_loop(0, k_iters, _loop_body, None)
plgpu.tcgen05_commit_arrive(
mma_done_barrier.at[acc_slot],
collective_axis="cluster",
)
@pl.when(wg_idx == 1)
def _store_wg():
# Ensure that copies from the previous mn step have completed.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
plgpu.barrier_wait(mma_done_barrier.at[acc_slot])
out_m_index = m_index * 2 + lax.axis_index("cluster")
out_m_slice = pl.ds(out_m_index * tile_m, tile_m)
out_gmem_window = out_gmem.at[out_m_slice, n_slice]
for ni in range(cluster_tile_n // config.epilogue_tile_n):
acc_smem_ni = acc_smem.at[ni % 2]
ni_slice = pl.ds(ni * config.epilogue_tile_n, config.epilogue_tile_n)
# Make sure that previous copy is done before we overwrite.
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
acc_smem_ni[...] = plgpu.async_load_tmem(mn_acc_tmem.at[:, ni_slice]).astype(dtype)
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(acc_smem_ni, out_gmem_window.at[:, ni_slice])
plgpu.wait_load_tmem() # Load must complete before we signal.
plgpu.barrier_arrive(store_done_barrier.at[acc_slot])
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
num_sms = backend.get_default_device().core_count
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), dtype),
grid=(num_sms // 2,),
grid_names=("cluster_grid",),
cluster=(2,),
cluster_names=("cluster",),
num_threads=2,
thread_name="wg",
scratch_shapes=dict(
a_smem=plgpu.SMEM(
(max_concurrent_steps, tile_m, tile_k), dtype, transforms=transforms
),
b_smem=plgpu.SMEM(
(max_concurrent_steps, tile_k, tile_n), dtype, transforms=transforms
),
acc_tmem=plgpu.TMEM((tile_m, 2 * cluster_tile_n), jnp.float32, collective=True),
acc_smem=plgpu.SMEM((2, tile_m, config.epilogue_tile_n), dtype, transforms=transforms),
load_barriers=plgpu.Barrier(num_arrivals=2, num_barriers=max_concurrent_steps),
consumed_barriers=plgpu.Barrier(
num_arrivals=1,
num_barriers=max_concurrent_steps,
orders_tensor_core=True,
),
mma_done_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=2, orders_tensor_core=True),
store_done_barrier=plgpu.ClusterBarrier(
collective_axes=("cluster",),
num_arrivals=1,
num_barriers=2,
orders_tensor_core=True,
),
)
)
return f(a, b)
@jtu.with_config(jax_traceback_filtering="off")
| TuningConfig |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy_request_response.py | {
"start": 338,
"end": 6077
} | class ____:
def create_asgi_proxy_request(self, scope: dict) -> ASGIProxyRequest:
receive = MagicMock()
send = MagicMock()
return ASGIProxyRequest(scope=scope, receive=receive, send=send)
def test_request_type(self):
"""Test calling request_type on an instance of ASGIProxyRequest.
When the request_type is not passed into the scope, it returns empty string.
When the request_type is passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.request_type == ""
request_type = "fake-request_type"
proxy_request = self.create_asgi_proxy_request(scope={"type": request_type})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.request_type == request_type
def test_client(self):
"""Test calling client on an instance of ASGIProxyRequest.
When the client is not passed into the scope, it returns empty string.
When the request_type is passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.client == ""
client = "fake-client"
proxy_request = self.create_asgi_proxy_request(scope={"client": client})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.client == client
def test_method(self):
"""Test calling method on an instance of ASGIProxyRequest.
When the method is not passed into the scope, it returns "WEBSOCKET". When
the method is passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.method == "WS"
method = "fake-method"
proxy_request = self.create_asgi_proxy_request(scope={"method": method})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.method == method.upper()
def test_root_path(self):
"""Test calling root_path on an instance of ASGIProxyRequest.
When the root_path is not passed into the scope, it returns empty string.
When calling set_root_path, it correctly sets the root_path. When the
root_path is passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.root_path == ""
root_path = "fake-root_path"
proxy_request.set_root_path(root_path)
assert proxy_request.root_path == root_path
proxy_request = self.create_asgi_proxy_request(scope={"root_path": root_path})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.root_path == root_path
def test_path(self):
"""Test calling path on an instance of ASGIProxyRequest.
When the path is not passed into the scope, it returns empty string.
When calling set_path, it correctly sets the path. When the
path is passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.path == ""
path = "fake-path"
proxy_request.set_path(path)
assert proxy_request.path == path
proxy_request = self.create_asgi_proxy_request(scope={"path": path})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.path == path
def test_headers(self):
"""Test calling headers on an instance of ASGIProxyRequest.
When the headers are not passed into the scope, it returns empty list.
When the headers are passed into the scope, it returns the correct value.
"""
proxy_request = self.create_asgi_proxy_request(scope={})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.headers == []
headers = [(b"fake-header-key", b"fake-header-value")]
proxy_request = self.create_asgi_proxy_request(scope={"headers": headers})
assert isinstance(proxy_request, ProxyRequest)
assert proxy_request.headers == headers
def test_is_route_request(self):
"""Test calling is_route_request on an instance of ASGIProxyRequest.
When the is_route_request is called with `/-/routes`, it returns true.
When the is_route_request is called with other path, it returns false.
"""
scope = {"path": "/-/routes"}
proxy_request = self.create_asgi_proxy_request(scope=scope)
assert proxy_request.is_route_request is True
scope = {"path": "/foo"}
proxy_request = self.create_asgi_proxy_request(scope=scope)
assert proxy_request.is_route_request is False
def test_is_health_request(self):
"""Test calling is_health_request on an instance of ASGIProxyRequest.
When the is_health_request is called with `/-/healthz`, it returns true.
When the is_health_request is called with other path, it returns false.
"""
scope = {"path": "/-/healthz"}
proxy_request = self.create_asgi_proxy_request(scope=scope)
assert proxy_request.is_health_request is True
scope = {"path": "/foo"}
proxy_request = self.create_asgi_proxy_request(scope=scope)
assert proxy_request.is_health_request is False
| TestASGIProxyRequest |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_list_tools_param.py | {
"start": 611,
"end": 975
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""The label of the MCP server."""
tools: Required[Iterable[Tool]]
"""The tools available on the server."""
type: Required[Literal["mcp_list_tools"]]
"""The type of the item. Always `mcp_list_tools`."""
id: str
"""The unique ID of the list."""
| RealtimeMcpListToolsParam |
python | pypa__pip | src/pip/_vendor/rich/progress.py | {
"start": 32176,
"end": 32381
} | class ____(NamedTuple):
"""Sample of progress for a given time."""
timestamp: float
"""Timestamp of sample."""
completed: float
"""Number of steps completed."""
@dataclass
| ProgressSample |
python | walkccc__LeetCode | solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py | {
"start": 0,
"end": 488
} | class ____:
def maximumSum(self, nums: list[int]) -> int:
MAX = 9 * 9 # 999,999,999
ans = -1
count = [[] for _ in range(MAX + 1)]
for num in nums:
count[self._getDigitSum(num)].append(num)
for groupNums in count:
if len(groupNums) < 2:
continue
groupNums.sort(reverse=True)
ans = max(ans, groupNums[0] + groupNums[1])
return ans
def _getDigitSum(self, num: int) -> int:
return sum(int(digit) for digit in str(num))
| Solution |
python | neetcode-gh__leetcode | python/1631-path-with-minimum-effort.py | {
"start": 0,
"end": 1024
} | class ____:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m, n = len(heights), len(heights[0])
efforts = [[float('inf')] * n for _ in range(m)]
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
efforts[0][0] = 0
pq = [(0, 0, 0)] # (effort, row, col)
while pq:
curEffort, i, j = heapq.heappop(pq)
# reached the bottom-right corner => return the effort
if i == m - 1 and j == n - 1:
return curEffort
for dx, dy in directions:
x, y = i + dx, j + dy
if 0 <= x < m and 0 <= y < n:
newEffort = max(abs(heights[x][y] - heights[i][j]), curEffort)
if newEffort < efforts[x][y]:
efforts[x][y] = newEffort
heapq.heappush(pq, (newEffort, x, y))
return efforts[m - 1][n - 1] | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 120908,
"end": 121556
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
job_cluster_key: str = Field(
...,
description=(
"A unique name for the job cluster. This field is required and must be"
" unique within the job.\n`JobTaskSettings` may refer to this field to"
" determine which cluster to launch for the task execution."
),
examples=["auto_scaling_cluster"],
max_length=100,
min_length=1,
pattern="^[\\w\\-]+$",
)
new_cluster: Optional[NewCluster] = None
| JobCluster |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py | {
"start": 17168,
"end": 21397
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3OmniMoeThinker`]. It is used to instantiate a
Qwen3-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the thinker component of the Qwen3-Omni
architecture.
e.g. [Qwen/Qwen3-Omni-7B](https://huggingface.co/Qwen/Qwen3-Omni-7B)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
audio_config (`dict`, *optional*):
The config dictionary of the audio backbone.
vision_config (`dict`, *optional*):
The config dictionary of the vision backbone.
text_config (`dict`, *optional*):
The config dictionary of the text backbone.
audio_token_id (`int`, *optional*, defaults to 151646):
The audio token id to encode the audio prompt.
image_token_id (`int`, *optional*, defaults to 151655):
The image token id to encode the image prompt.
video_token_id (`int`, *optional*, defaults to 151656):
The video token id to encode the video prompt.
position_id_per_seconds (`int`, *optional*, defaults to 25):
The increment of position id per second.
audio_start_token_id (`int`, *optional*, defaults to 151647):
The audio start token id to encode the audio prompt.
user_token_id (`int`, *optional*, defaults to 872):
The user token id to encode the user token.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
Example:
```python
>>> from transformers import Qwen3OmniMoeThinkerModel, Qwen3OmniMoeThinkerConfig
>>> # Initializing a default Qwen3OmniMoeThinkerConfig
>>> configuration = Qwen3OmniMoeThinkerConfig()
>>> # Initializing a model (with random weights) from the default configuration
>>> model = Qwen3OmniMoeThinkerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "qwen3_omni_moe_thinker"
# Override parent's attribute_map as we use audio_token_id directly, not audio_token_index
attribute_map = {}
sub_configs = {
"audio_config": Qwen3OmniMoeAudioEncoderConfig,
"vision_config": Qwen3OmniMoeVisionEncoderConfig,
"text_config": Qwen3OmniMoeTextConfig,
}
def __init__(
self,
audio_config=None,
vision_config=None,
text_config=None,
audio_token_id=151646,
image_token_id=151655,
video_token_id=151656,
position_id_per_seconds=25,
audio_start_token_id=151647,
user_token_id=872,
initializer_range=0.02,
**kwargs,
):
self.user_token_id = user_token_id
self.position_id_per_seconds = position_id_per_seconds
self.audio_start_token_id = audio_start_token_id
self.initializer_range = initializer_range
if isinstance(vision_config, dict):
vision_config = Qwen3OmniMoeVisionEncoderConfig(**vision_config)
elif vision_config is None:
vision_config = Qwen3OmniMoeVisionEncoderConfig()
self.vision_config = vision_config
if isinstance(audio_config, dict):
audio_config = Qwen3OmniMoeAudioEncoderConfig(**audio_config)
elif audio_config is None:
audio_config = Qwen3OmniMoeAudioEncoderConfig()
self.audio_config = audio_config
if isinstance(text_config, dict):
text_config = Qwen3OmniMoeTextConfig(**text_config)
elif text_config is None:
text_config = Qwen3OmniMoeTextConfig()
self.text_config = text_config
super().__init__(**kwargs)
self.audio_token_id = audio_token_id
self.image_token_id = image_token_id
self.video_token_id = video_token_id
| Qwen3OmniMoeThinkerConfig |
python | numba__numba | numba/core/intrinsics.py | {
"start": 91,
"end": 2008
} | class ____(ir.Visitor):
def visit_Instruction(self, instr):
if instr.type == ir.IntType(64):
if instr.opname in ['srem', 'urem', 'sdiv', 'udiv']:
name = 'numba_{op}'.format(op=instr.opname)
fn = self.module.globals.get(name)
# Declare the function if it doesn't already exist
if fn is None:
opty = instr.type
sdivfnty = ir.FunctionType(opty, [opty, opty])
fn = ir.Function(self.module, sdivfnty, name=name)
# Replace the operation with a call to the builtin
repl = ir.CallInstr(parent=instr.parent, func=fn,
args=instr.operands, name=instr.name)
instr.parent.replace(instr, repl)
def fix_divmod(mod):
"""Replace division and reminder instructions to builtins calls
"""
_DivmodFixer().visit(mod)
INTR_TO_CMATH = {
"llvm.pow.f32": "powf",
"llvm.pow.f64": "pow",
"llvm.sin.f32": "sinf",
"llvm.sin.f64": "sin",
"llvm.cos.f32": "cosf",
"llvm.cos.f64": "cos",
"llvm.sqrt.f32": "sqrtf",
"llvm.sqrt.f64": "sqrt",
"llvm.exp.f32": "expf",
"llvm.exp.f64": "exp",
"llvm.log.f32": "logf",
"llvm.log.f64": "log",
"llvm.log10.f32": "log10f",
"llvm.log10.f64": "log10",
"llvm.fabs.f32": "fabsf",
"llvm.fabs.f64": "fabs",
"llvm.floor.f32": "floorf",
"llvm.floor.f64": "floor",
"llvm.ceil.f32": "ceilf",
"llvm.ceil.f64": "ceil",
"llvm.trunc.f32": "truncf",
"llvm.trunc.f64": "trunc",
}
OTHER_CMATHS = '''
tan
tanf
sinh
sinhf
cosh
coshf
tanh
tanhf
asin
asinf
acos
acosf
atan
atanf
atan2
atan2f
asinh
asinhf
acosh
acoshf
atanh
atanhf
expm1
expm1f
log1p
log1pf
log10
log10f
fmod
fmodf
round
roundf
'''.split()
INTR_MATH = frozenset(INTR_TO_CMATH.values()) | frozenset(OTHER_CMATHS)
| _DivmodFixer |
python | langchain-ai__langchain | libs/partners/huggingface/langchain_huggingface/embeddings/huggingface_endpoint.py | {
"start": 362,
"end": 5677
} | class ____(BaseModel, Embeddings):
"""HuggingFaceHub embedding models.
To use, you should have the `huggingface_hub` python package installed, and the
environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token, or pass
it as a named parameter to the constructor.
Example:
```python
from langchain_huggingface import HuggingFaceEndpointEmbeddings
model = "sentence-transformers/all-mpnet-base-v2"
hf = HuggingFaceEndpointEmbeddings(
model=model,
task="feature-extraction",
huggingfacehub_api_token="my-api-key",
)
```
"""
client: Any = None
async_client: Any = None
model: str | None = None
"""Model name to use."""
provider: str | None = None
"""Name of the provider to use for inference with the model specified in
`repo_id`. e.g. "sambanova". if not specified, defaults to HF Inference API.
available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
repo_id: str | None = None
"""Huggingfacehub repository id, for backward compatibility."""
task: str | None = "feature-extraction"
"""Task to call the model with."""
model_kwargs: dict | None = None
"""Keyword arguments to pass to the model."""
huggingfacehub_api_token: str | None = Field(
default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
)
model_config = ConfigDict(
extra="forbid",
protected_namespaces=(),
)
@model_validator(mode="after")
def validate_environment(self) -> Self:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = self.huggingfacehub_api_token or os.getenv(
"HF_TOKEN"
)
try:
from huggingface_hub import ( # type: ignore[import]
AsyncInferenceClient,
InferenceClient,
)
if self.model:
self.repo_id = self.model
elif self.repo_id:
self.model = self.repo_id
else:
self.model = DEFAULT_MODEL
self.repo_id = DEFAULT_MODEL
client = InferenceClient(
model=self.model,
token=huggingfacehub_api_token,
provider=self.provider, # type: ignore[arg-type]
)
async_client = AsyncInferenceClient(
model=self.model,
token=huggingfacehub_api_token,
provider=self.provider, # type: ignore[arg-type]
)
if self.task not in VALID_TASKS:
msg = (
f"Got invalid task {self.task}, "
f"currently only {VALID_TASKS} are supported"
)
raise ValueError(msg)
self.client = client
self.async_client = async_client
except ImportError as e:
msg = (
"Could not import huggingface_hub python package. "
"Please install it with `pip install huggingface_hub`."
)
raise ImportError(msg) from e
return self
def embed_documents(self, texts: list[str]) -> list[list[float]]:
"""Call out to HuggingFaceHub's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
# replace newlines, which can negatively affect performance.
texts = [text.replace("\n", " ") for text in texts]
_model_kwargs = self.model_kwargs or {}
# api doc: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/embed
responses = self.client.feature_extraction(text=texts, **_model_kwargs)
return responses.tolist()
async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
"""Async Call to HuggingFaceHub's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
# replace newlines, which can negatively affect performance.
texts = [text.replace("\n", " ") for text in texts]
_model_kwargs = self.model_kwargs or {}
responses = await self.async_client.feature_extraction(
text=texts, **_model_kwargs
)
return responses.tolist()
def embed_query(self, text: str) -> list[float]:
"""Call out to HuggingFaceHub's embedding endpoint for embedding query text.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self.embed_documents([text])[0]
async def aembed_query(self, text: str) -> list[float]:
"""Async Call to HuggingFaceHub's embedding endpoint for embedding query text.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return (await self.aembed_documents([text]))[0]
| HuggingFaceEndpointEmbeddings |
python | ApeWorX__ape | src/ape/api/providers.py | {
"start": 5676,
"end": 7160
} | class ____(BaseModel, ManagerAccessMixin):
"""
The result of a call.
NOTE: Currently, you only get this for reverted calls from ``ProviderAPI``.
"""
revert: Optional[ContractLogicError] = None
"""
The revert, if the call reverted.
"""
returndata: HexBytes
"""
The raw returndata.
"""
@classmethod
def from_revert(cls, revert: ContractLogicError) -> "CallResult":
"""
Factory helper for easily creating a CallResult from a revert error.
Args:
revert (ContractLogicError): The revert error.
Returns:
A new ``CallResult`` instance.
"""
return cls(revert=revert, returndata=HexBytes(revert.revert_message.encode("utf8").hex()))
@property
def reverted(self) -> bool:
"""
``True`` if the call `reverted` (failed).
"""
return self.revert is not None
@property
def revert_message(self) -> Optional[str]:
"""
The revert message, if the call reverted.
"""
return self.revert.revert_message if self.revert else None
def decode(self, method_abi: MethodABI) -> Any:
"""
Decode a Pythonic return value from the call.
Args:
method_abi (``MethodABI``): The method ABI to decode.
Returns:
The decoded result.
"""
return self.provider.network.ecosystem.decode_returndata(method_abi, self.returndata)
| CallResult |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/translate.py | {
"start": 2270,
"end": 2639
} | class ____(Exception):
"""Wait operation not done yet error."""
pass
def _if_exc_is_wait_failed_error(exc: Exception):
return isinstance(exc, WaitOperationNotDoneYetError)
def _check_if_operation_done(operation: Operation):
if not operation.done():
raise WaitOperationNotDoneYetError("Operation is not done yet.")
| WaitOperationNotDoneYetError |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 1960,
"end": 2140
} | class ____(CookiecutterException):
"""
Exception for failed JSON decoding.
Raised when a project's JSON context file can not be decoded.
"""
| ContextDecodingException |
python | RaRe-Technologies__gensim | gensim/interfaces.py | {
"start": 7428,
"end": 9106
} | class ____(utils.SaveLoad):
"""Transformation interface.
A 'transformation' is any object which accepts document in BoW format via the `__getitem__` (notation `[]`)
and returns another sparse document in its stead:
.. sourcecode:: pycon
>>> from gensim.models import LsiModel
>>> from gensim.test.utils import common_dictionary, common_corpus
>>>
>>> model = LsiModel(common_corpus, id2word=common_dictionary)
>>> bow_vector = model[common_corpus[0]] # model applied through __getitem__ on one document from corpus.
>>> bow_corpus = model[common_corpus] # also, we can apply model on the full corpus
"""
def __getitem__(self, vec):
"""Transform a single document, or a whole corpus, from one vector space into another.
Parameters
----------
vec : {list of (int, number), iterable of list of (int, number)}
Document in bag-of-words, or streamed corpus.
"""
raise NotImplementedError('cannot instantiate abstract base class')
def _apply(self, corpus, chunksize=None, **kwargs):
"""Apply the transformation to a whole corpus and get the result as another corpus.
Parameters
----------
corpus : iterable of list of (int, number)
Corpus in sparse Gensim bag-of-words format.
chunksize : int, optional
If provided, a more effective processing will performed.
Returns
-------
:class:`~gensim.interfaces.TransformedCorpus`
Transformed corpus.
"""
return TransformedCorpus(self, corpus, chunksize, **kwargs)
| TransformationABC |
python | streamlit__streamlit | lib/tests/streamlit/elements/space_test.py | {
"start": 819,
"end": 2823
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall space protos."""
def test_space_default(self):
"""Test st.space() with default size."""
st.space()
c = self.get_delta_from_queue().new_element
assert c.space is not None
# Default is "small" = 0.75rem
assert c.width_config.rem_width == 0.75
assert c.height_config.rem_height == 0.75
@parameterized.expand(
[
("small", 0.75),
("medium", 2.5),
("large", 4.25),
]
)
def test_space_rem_sizes(self, size_name, expected_rem):
"""Test space with rem size literals."""
st.space(size_name)
c = self.get_delta_from_queue().new_element
assert c.space is not None
assert c.width_config.rem_width == expected_rem
assert c.height_config.rem_height == expected_rem
def test_space_stretch(self):
"""Test space with stretch size."""
st.space("stretch")
c = self.get_delta_from_queue().new_element
assert c.space is not None
assert c.width_config.use_stretch
assert c.height_config.use_stretch
@parameterized.expand(
[
100,
50,
1,
]
)
def test_space_pixel_sizes(self, pixel_value):
"""Test space with pixel sizes."""
st.space(pixel_value)
c = self.get_delta_from_queue().new_element
assert c.space is not None
assert c.width_config.pixel_width == pixel_value
assert c.height_config.pixel_height == pixel_value
@parameterized.expand(
[
"invalid",
-100,
0,
100.5, # Floats not supported
-50.5,
None,
]
)
def test_space_invalid_sizes(self, invalid_size):
"""Test that invalid size values raise an exception."""
with pytest.raises(StreamlitInvalidSizeError):
st.space(invalid_size)
| SpaceTest |
python | doocs__leetcode | solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.py | {
"start": 0,
"end": 544
} | class ____:
def numPermsDISequence(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
f = [1] + [0] * n
for i, c in enumerate(s, 1):
pre = 0
g = [0] * (n + 1)
if c == "D":
for j in range(i, -1, -1):
pre = (pre + f[j]) % mod
g[j] = pre
else:
for j in range(i + 1):
g[j] = pre
pre = (pre + f[j]) % mod
f = g
return sum(f) % mod
| Solution |
python | django__django | tests/test_runner_apps/sample/tests_sample.py | {
"start": 551,
"end": 700
} | class ____(TestCase):
pass
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(doctests))
return tests
| EmptyTestCase |
python | spack__spack | lib/spack/spack/build_environment.py | {
"start": 58411,
"end": 63186
} | class ____(InstallError):
"""Special exception class for wrapping exceptions from child processes
in Spack's build environment.
The main features of a ChildError are:
1. They're serializable, so when a child build fails, we can send one
of these to the parent and let the parent report what happened.
2. They have a ``traceback`` field containing a traceback generated
on the child immediately after failure. Spack will print this on
failure in lieu of trying to run sys.excepthook on the parent
process, so users will see the correct stack trace from a child.
3. They also contain context, which shows context in the Package
implementation where the error happened. This helps people debug
Python code in their packages. To get it, Spack searches the
stack trace for the deepest frame where ``self`` is in scope and
is an instance of PackageBase. This will generally find a useful
spot in the ``package.py`` file.
The long_message of a ChildError displays one of two things:
1. If the original error was a ProcessError, indicating a command
died during the build, we'll show context from the build log.
2. If the original error was any other type of error, we'll show
context from the Python code.
SpackError handles displaying the special traceback if we're in debug
mode with spack -d.
"""
# List of errors considered "build errors", for which we'll show log
# context instead of Python context.
build_errors = [("spack.util.executable", "ProcessError")]
def __init__(self, msg, module, classname, traceback_string, log_name, log_type, context):
super().__init__(msg)
self.module = module
self.name = classname
self.traceback = traceback_string
self.log_name = log_name
self.log_type = log_type
self.context = context
@property
def long_message(self):
out = io.StringIO()
out.write(self._long_message if self._long_message else "")
have_log = self.log_name and os.path.exists(self.log_name)
if (self.module, self.name) in ChildError.build_errors:
# The error happened in some external executed process. Show
# the log with errors or warnings highlighted.
if have_log:
write_log_summary(out, self.log_type, self.log_name)
else:
# The error happened in the Python code, so try to show
# some context from the Package itself.
if self.context:
out.write("\n")
out.write("\n".join(self.context))
out.write("\n")
if out.getvalue():
out.write("\n")
if have_log:
out.write("See {0} log for details:\n".format(self.log_type))
out.write(" {0}\n".format(self.log_name))
# Also output the test log path IF it exists
if self.context != "test" and have_log:
test_log = join_path(os.path.dirname(self.log_name), spack_install_test_log)
if os.path.isfile(test_log):
out.write("\nSee test log for details:\n")
out.write(" {0}\n".format(test_log))
return out.getvalue()
def __str__(self):
return self.message
def __reduce__(self):
"""__reduce__ is used to serialize (pickle) ChildErrors.
Return a function to reconstruct a ChildError, along with the
salient properties we'll need.
"""
return _make_child_error, (
self.message,
self.module,
self.name,
self.traceback,
self.log_name,
self.log_type,
self.context,
)
def _make_child_error(msg, module, name, traceback, log, log_type, context):
"""Used by __reduce__ in ChildError to reconstruct pickled errors."""
return ChildError(msg, module, name, traceback, log, log_type, context)
def write_log_summary(out, log_type, log, last=None):
errors, warnings = parse_log_events(log)
nerr = len(errors)
nwar = len(warnings)
if nerr > 0:
if last and nerr > last:
errors = errors[-last:]
nerr = last
# If errors are found, only display errors
out.write("\n%s found in %s log:\n" % (plural(nerr, "error"), log_type))
out.write(make_log_context(errors))
elif nwar > 0:
if last and nwar > last:
warnings = warnings[-last:]
nwar = last
# If no errors are found but warnings are, display warnings
out.write("\n%s found in %s log:\n" % (plural(nwar, "warning"), log_type))
out.write(make_log_context(warnings))
| ChildError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/session.py | {
"start": 28201,
"end": 49992
} | class ____(_StateChange, TransactionalContext):
"""A :class:`.Session`-level transaction.
:class:`.SessionTransaction` is produced from the
:meth:`_orm.Session.begin`
and :meth:`_orm.Session.begin_nested` methods. It's largely an internal
object that in modern use provides a context manager for session
transactions.
Documentation on interacting with :class:`_orm.SessionTransaction` is
at: :ref:`unitofwork_transaction`.
.. versionchanged:: 1.4 The scoping and API methods to work with the
:class:`_orm.SessionTransaction` object directly have been simplified.
.. seealso::
:ref:`unitofwork_transaction`
:meth:`.Session.begin`
:meth:`.Session.begin_nested`
:meth:`.Session.rollback`
:meth:`.Session.commit`
:meth:`.Session.in_transaction`
:meth:`.Session.in_nested_transaction`
:meth:`.Session.get_transaction`
:meth:`.Session.get_nested_transaction`
"""
_rollback_exception: Optional[BaseException] = None
_connections: Dict[
Union[Engine, Connection], Tuple[Connection, Transaction, bool, bool]
]
session: Session
_parent: Optional[SessionTransaction]
_state: SessionTransactionState
_new: weakref.WeakKeyDictionary[InstanceState[Any], object]
_deleted: weakref.WeakKeyDictionary[InstanceState[Any], object]
_dirty: weakref.WeakKeyDictionary[InstanceState[Any], object]
_key_switches: weakref.WeakKeyDictionary[
InstanceState[Any], Tuple[Any, Any]
]
origin: SessionTransactionOrigin
"""Origin of this :class:`_orm.SessionTransaction`.
Refers to a :class:`.SessionTransactionOrigin` instance which is an
enumeration indicating the source event that led to constructing
this :class:`_orm.SessionTransaction`.
.. versionadded:: 2.0
"""
nested: bool = False
"""Indicates if this is a nested, or SAVEPOINT, transaction.
When :attr:`.SessionTransaction.nested` is True, it is expected
that :attr:`.SessionTransaction.parent` will be present as well,
linking to the enclosing :class:`.SessionTransaction`.
.. seealso::
:attr:`.SessionTransaction.origin`
"""
def __init__(
self,
session: Session,
origin: SessionTransactionOrigin,
parent: Optional[SessionTransaction] = None,
):
TransactionalContext._trans_ctx_check(session)
self.session = session
self._connections = {}
self._parent = parent
self.nested = nested = origin is SessionTransactionOrigin.BEGIN_NESTED
self.origin = origin
if session._close_state is _SessionCloseState.CLOSED:
raise sa_exc.InvalidRequestError(
"This Session has been permanently closed and is unable "
"to handle any more transaction requests."
)
if nested:
if not parent:
raise sa_exc.InvalidRequestError(
"Can't start a SAVEPOINT transaction when no existing "
"transaction is in progress"
)
self._previous_nested_transaction = session._nested_transaction
elif origin is SessionTransactionOrigin.SUBTRANSACTION:
assert parent is not None
else:
assert parent is None
self._state = SessionTransactionState.ACTIVE
self._take_snapshot()
# make sure transaction is assigned before we call the
# dispatch
self.session._transaction = self
self.session.dispatch.after_transaction_create(self.session, self)
def _raise_for_prerequisite_state(
self, operation_name: str, state: _StateChangeState
) -> NoReturn:
if state is SessionTransactionState.DEACTIVE:
if self._rollback_exception:
raise sa_exc.PendingRollbackError(
"This Session's transaction has been rolled back "
"due to a previous exception during flush."
" To begin a new transaction with this Session, "
"first issue Session.rollback()."
f" Original exception was: {self._rollback_exception}",
code="7s2a",
)
else:
raise sa_exc.InvalidRequestError(
"This session is in 'inactive' state, due to the "
"SQL transaction being rolled back; no further SQL "
"can be emitted within this transaction."
)
elif state is SessionTransactionState.CLOSED:
raise sa_exc.ResourceClosedError("This transaction is closed")
elif state is SessionTransactionState.PROVISIONING_CONNECTION:
raise sa_exc.InvalidRequestError(
"This session is provisioning a new connection; concurrent "
"operations are not permitted",
code="isce",
)
else:
raise sa_exc.InvalidRequestError(
f"This session is in '{state.name.lower()}' state; no "
"further SQL can be emitted within this transaction."
)
@property
def parent(self) -> Optional[SessionTransaction]:
"""The parent :class:`.SessionTransaction` of this
:class:`.SessionTransaction`.
If this attribute is ``None``, indicates this
:class:`.SessionTransaction` is at the top of the stack, and
corresponds to a real "COMMIT"/"ROLLBACK"
block. If non-``None``, then this is either a "subtransaction"
(an internal marker object used by the flush process) or a
"nested" / SAVEPOINT transaction. If the
:attr:`.SessionTransaction.nested` attribute is ``True``, then
this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.
"""
return self._parent
@property
def is_active(self) -> bool:
return (
self.session is not None
and self._state is SessionTransactionState.ACTIVE
)
@property
def _is_transaction_boundary(self) -> bool:
return self.nested or not self._parent
@_StateChange.declare_states(
(SessionTransactionState.ACTIVE,), _StateChangeStates.NO_CHANGE
)
def connection(
self,
bindkey: Optional[Mapper[Any]],
execution_options: Optional[_ExecuteOptions] = None,
**kwargs: Any,
) -> Connection:
bind = self.session.get_bind(bindkey, **kwargs)
return self._connection_for_bind(bind, execution_options)
@_StateChange.declare_states(
(SessionTransactionState.ACTIVE,), _StateChangeStates.NO_CHANGE
)
def _begin(self, nested: bool = False) -> SessionTransaction:
return SessionTransaction(
self.session,
(
SessionTransactionOrigin.BEGIN_NESTED
if nested
else SessionTransactionOrigin.SUBTRANSACTION
),
self,
)
def _iterate_self_and_parents(
self, upto: Optional[SessionTransaction] = None
) -> Iterable[SessionTransaction]:
current = self
result: Tuple[SessionTransaction, ...] = ()
while current:
result += (current,)
if current._parent is upto:
break
elif current._parent is None:
raise sa_exc.InvalidRequestError(
"Transaction %s is not on the active transaction list"
% (upto)
)
else:
current = current._parent
return result
def _take_snapshot(self) -> None:
if not self._is_transaction_boundary:
parent = self._parent
assert parent is not None
self._new = parent._new
self._deleted = parent._deleted
self._dirty = parent._dirty
self._key_switches = parent._key_switches
return
is_begin = self.origin in (
SessionTransactionOrigin.BEGIN,
SessionTransactionOrigin.AUTOBEGIN,
)
if not is_begin and not self.session._flushing:
self.session.flush()
self._new = weakref.WeakKeyDictionary()
self._deleted = weakref.WeakKeyDictionary()
self._dirty = weakref.WeakKeyDictionary()
self._key_switches = weakref.WeakKeyDictionary()
def _restore_snapshot(self, dirty_only: bool = False) -> None:
"""Restore the restoration state taken before a transaction began.
Corresponds to a rollback.
"""
assert self._is_transaction_boundary
to_expunge = set(self._new).union(self.session._new)
self.session._expunge_states(to_expunge, to_transient=True)
for s, (oldkey, newkey) in self._key_switches.items():
# we probably can do this conditionally based on
# if we expunged or not, but safe_discard does that anyway
self.session.identity_map.safe_discard(s)
# restore the old key
s.key = oldkey
# now restore the object, but only if we didn't expunge
if s not in to_expunge:
self.session.identity_map.replace(s)
for s in set(self._deleted).union(self.session._deleted):
self.session._update_impl(s, revert_deletion=True)
assert not self.session._deleted
for s in self.session.identity_map.all_states():
if not dirty_only or s.modified or s in self._dirty:
s._expire(s.dict, self.session.identity_map._modified)
def _remove_snapshot(self) -> None:
"""Remove the restoration state taken before a transaction began.
Corresponds to a commit.
"""
assert self._is_transaction_boundary
if not self.nested and self.session.expire_on_commit:
for s in self.session.identity_map.all_states():
s._expire(s.dict, self.session.identity_map._modified)
statelib.InstanceState._detach_states(
list(self._deleted), self.session
)
self._deleted.clear()
elif self.nested:
parent = self._parent
assert parent is not None
parent._new.update(self._new)
parent._dirty.update(self._dirty)
parent._deleted.update(self._deleted)
parent._key_switches.update(self._key_switches)
@_StateChange.declare_states(
(SessionTransactionState.ACTIVE,), _StateChangeStates.NO_CHANGE
)
def _connection_for_bind(
self,
bind: _SessionBind,
execution_options: Optional[CoreExecuteOptionsParameter],
) -> Connection:
if bind in self._connections:
if execution_options:
util.warn(
"Connection is already established for the "
"given bind; execution_options ignored"
)
return self._connections[bind][0]
self._state = SessionTransactionState.PROVISIONING_CONNECTION
local_connect = False
should_commit = True
try:
if self._parent:
conn = self._parent._connection_for_bind(
bind, execution_options
)
if not self.nested:
return conn
else:
if isinstance(bind, engine.Connection):
conn = bind
if conn.engine in self._connections:
raise sa_exc.InvalidRequestError(
"Session already has a Connection associated "
"for the given Connection's Engine"
)
else:
conn = bind.connect()
local_connect = True
try:
if execution_options:
conn = conn.execution_options(**execution_options)
transaction: Transaction
if self.session.twophase and self._parent is None:
# TODO: shouldn't we only be here if not
# conn.in_transaction() ?
# if twophase is set and conn.in_transaction(), validate
# that it is in fact twophase.
transaction = conn.begin_twophase()
elif self.nested:
transaction = conn.begin_nested()
elif conn.in_transaction():
if local_connect:
_trans = conn.get_transaction()
assert _trans is not None
transaction = _trans
else:
join_transaction_mode = (
self.session.join_transaction_mode
)
if join_transaction_mode == "conditional_savepoint":
if conn.in_nested_transaction():
join_transaction_mode = "create_savepoint"
else:
join_transaction_mode = "rollback_only"
if join_transaction_mode in (
"control_fully",
"rollback_only",
):
if conn.in_nested_transaction():
transaction = (
conn._get_required_nested_transaction()
)
else:
transaction = conn._get_required_transaction()
if join_transaction_mode == "rollback_only":
should_commit = False
elif join_transaction_mode == "create_savepoint":
transaction = conn.begin_nested()
else:
assert False, join_transaction_mode
else:
transaction = conn.begin()
except:
# connection will not not be associated with this Session;
# close it immediately so that it isn't closed under GC
if local_connect:
conn.close()
raise
else:
bind_is_connection = isinstance(bind, engine.Connection)
self._connections[conn] = self._connections[conn.engine] = (
conn,
transaction,
should_commit,
not bind_is_connection,
)
self.session.dispatch.after_begin(self.session, self, conn)
return conn
finally:
self._state = SessionTransactionState.ACTIVE
def prepare(self) -> None:
if self._parent is not None or not self.session.twophase:
raise sa_exc.InvalidRequestError(
"'twophase' mode not enabled, or not root transaction; "
"can't prepare."
)
self._prepare_impl()
@_StateChange.declare_states(
(SessionTransactionState.ACTIVE,), SessionTransactionState.PREPARED
)
def _prepare_impl(self) -> None:
if self._parent is None or self.nested:
self.session.dispatch.before_commit(self.session)
stx = self.session._transaction
assert stx is not None
if stx is not self:
for subtransaction in stx._iterate_self_and_parents(upto=self):
subtransaction.commit()
if not self.session._flushing:
for _flush_guard in range(100):
if self.session._is_clean():
break
self.session.flush()
else:
raise exc.FlushError(
"Over 100 subsequent flushes have occurred within "
"session.commit() - is an after_flush() hook "
"creating new objects?"
)
if self._parent is None and self.session.twophase:
try:
for t in set(self._connections.values()):
cast("TwoPhaseTransaction", t[1]).prepare()
except:
with util.safe_reraise():
self.rollback()
self._state = SessionTransactionState.PREPARED
@_StateChange.declare_states(
(SessionTransactionState.ACTIVE, SessionTransactionState.PREPARED),
SessionTransactionState.CLOSED,
)
def commit(self, _to_root: bool = False) -> None:
if self._state is not SessionTransactionState.PREPARED:
with self._expect_state(SessionTransactionState.PREPARED):
self._prepare_impl()
if self._parent is None or self.nested:
for conn, trans, should_commit, autoclose in set(
self._connections.values()
):
if should_commit:
trans.commit()
self._state = SessionTransactionState.COMMITTED
self.session.dispatch.after_commit(self.session)
self._remove_snapshot()
with self._expect_state(SessionTransactionState.CLOSED):
self.close()
if _to_root and self._parent:
self._parent.commit(_to_root=True)
@_StateChange.declare_states(
(
SessionTransactionState.ACTIVE,
SessionTransactionState.DEACTIVE,
SessionTransactionState.PREPARED,
),
SessionTransactionState.CLOSED,
)
def rollback(
self, _capture_exception: bool = False, _to_root: bool = False
) -> None:
stx = self.session._transaction
assert stx is not None
if stx is not self:
for subtransaction in stx._iterate_self_and_parents(upto=self):
subtransaction.close()
boundary = self
rollback_err = None
if self._state in (
SessionTransactionState.ACTIVE,
SessionTransactionState.PREPARED,
):
for transaction in self._iterate_self_and_parents():
if transaction._parent is None or transaction.nested:
try:
for t in set(transaction._connections.values()):
t[1].rollback()
transaction._state = SessionTransactionState.DEACTIVE
self.session.dispatch.after_rollback(self.session)
except:
rollback_err = sys.exc_info()
finally:
transaction._state = SessionTransactionState.DEACTIVE
transaction._restore_snapshot(
dirty_only=transaction.nested
)
boundary = transaction
break
else:
transaction._state = SessionTransactionState.DEACTIVE
sess = self.session
if not rollback_err and not sess._is_clean():
# if items were added, deleted, or mutated
# here, we need to re-restore the snapshot
util.warn(
"Session's state has been changed on "
"a non-active transaction - this state "
"will be discarded."
)
boundary._restore_snapshot(dirty_only=boundary.nested)
with self._expect_state(SessionTransactionState.CLOSED):
self.close()
if self._parent and _capture_exception:
self._parent._rollback_exception = sys.exc_info()[1]
if rollback_err and rollback_err[1]:
raise rollback_err[1].with_traceback(rollback_err[2])
sess.dispatch.after_soft_rollback(sess, self)
if _to_root and self._parent:
self._parent.rollback(_to_root=True)
@_StateChange.declare_states(
_StateChangeStates.ANY, SessionTransactionState.CLOSED
)
def close(self, invalidate: bool = False) -> None:
if self.nested:
self.session._nested_transaction = (
self._previous_nested_transaction
)
self.session._transaction = self._parent
for connection, transaction, should_commit, autoclose in set(
self._connections.values()
):
if invalidate and self._parent is None:
connection.invalidate()
if should_commit and transaction.is_active:
transaction.close()
if autoclose and self._parent is None:
connection.close()
self._state = SessionTransactionState.CLOSED
sess = self.session
# TODO: these two None sets were historically after the
# event hook below, and in 2.0 I changed it this way for some reason,
# and I remember there being a reason, but not what it was.
# Why do we need to get rid of them at all? test_memusage::CycleTest
# passes with these commented out.
# self.session = None # type: ignore
# self._connections = None # type: ignore
sess.dispatch.after_transaction_end(sess, self)
def _get_subject(self) -> Session:
return self.session
def _transaction_is_active(self) -> bool:
return self._state is SessionTransactionState.ACTIVE
def _transaction_is_closed(self) -> bool:
return self._state is SessionTransactionState.CLOSED
def _rollback_can_be_called(self) -> bool:
return self._state not in (COMMITTED, CLOSED)
| SessionTransaction |
python | apache__airflow | providers/smtp/tests/unit/smtp/operators/test_smtp.py | {
"start": 1075,
"end": 3692
} | class ____:
def setup_method(self):
self.default_op_kwargs = dict(to="to", subject="subject", html_content="content")
@patch("airflow.providers.smtp.hooks.smtp.SmtpHook.get_connection")
@patch(smtplib_string)
def test_loading_sender_email_from_connection(self, mock_smtplib, mock_hook_conn):
"""Check if the EmailOperator is able to load the sender email from the smtp connection."""
custom_retry_limit = 10
custom_timeout = 60
sender_email = "sender_email"
with (
tempfile.NamedTemporaryFile(mode="wt", suffix=".txt") as f_subject,
tempfile.NamedTemporaryFile(mode="wt", suffix=".txt") as f_content,
):
f_subject.write("Task {{ ti.task_id }} failed")
f_subject.flush()
f_content.write("Mock content goes here")
f_content.flush()
mock_hook_conn.return_value = Connection(
conn_id="mock_conn",
conn_type="smtp",
host="smtp_server_address",
login="smtp_user",
password="smtp_password",
port=465,
extra=json.dumps(
dict(
from_email=sender_email,
timeout=custom_timeout,
retry_limit=custom_retry_limit,
subject_template=f_subject.name,
html_content_template=f_content.name,
)
),
)
smtp_client_mock = mock_smtplib.SMTP_SSL()
op = EmailOperator(task_id="test_email", to="to")
op.execute({"ti": MagicMock(task_id="some_id")})
call_args = smtp_client_mock.sendmail.call_args.kwargs
assert call_args["from_addr"] == sender_email
assert "Subject: Task some_id failed" in call_args["msg"]
assert (
base64.b64encode("Mock content goes here".encode("ascii")).decode("ascii") in call_args["msg"]
)
def test_assert_templated_fields(self):
"""Test expected templated fields."""
operator = EmailOperator(task_id="test_assert_templated_fields", **self.default_op_kwargs)
template_fields = (
"to",
"subject",
"html_content",
"from_email",
"files",
"cc",
"bcc",
"mime_subtype",
"mime_charset",
"conn_id",
"custom_headers",
)
assert operator.template_fields == template_fields
| TestEmailOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.