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 | tensorflow__tensorflow | tensorflow/python/ops/control_flow_v2_enable_test.py | {
"start": 1001,
"end": 1221
} | class ____(test.TestCase):
def testIsEnabled(self):
self.assertTrue(tf2.enabled())
self.assertTrue(control_flow_util.ENABLE_CONTROL_FLOW_V2)
if __name__ == "__main__":
googletest.main()
| ControlFlowV2EnableTest |
python | pypa__pip | src/pip/_vendor/resolvelib/resolvers/resolution.py | {
"start": 1729,
"end": 21515
} | class ____(Generic[RT, CT, KT]):
"""Stateful resolution object.
This is designed as a one-off object that holds information to kick start
the resolution process, and holds the results afterwards.
"""
def __init__(
self,
provider: AbstractProvider[RT, CT, KT],
reporter: BaseReporter[RT, CT, KT],
) -> None:
self._p = provider
self._r = reporter
self._states: list[State[RT, CT, KT]] = []
# Optimistic backjumping variables
self._optimistic_backjumping_ratio = _OPTIMISTIC_BACKJUMPING_RATIO
self._save_states: list[State[RT, CT, KT]] | None = None
self._optimistic_start_round: int | None = None
@property
def state(self) -> State[RT, CT, KT]:
try:
return self._states[-1]
except IndexError as e:
raise AttributeError("state") from e
def _push_new_state(self) -> None:
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
base = self._states[-1]
state = State(
mapping=base.mapping.copy(),
criteria=base.criteria.copy(),
backtrack_causes=base.backtrack_causes[:],
)
self._states.append(state)
def _add_to_criteria(
self,
criteria: dict[KT, Criterion[RT, CT]],
requirement: RT,
parent: CT | None,
) -> None:
self._r.adding_requirement(requirement=requirement, parent=parent)
identifier = self._p.identify(requirement_or_candidate=requirement)
criterion = criteria.get(identifier)
if criterion:
incompatibilities = list(criterion.incompatibilities)
else:
incompatibilities = []
matches = self._p.find_matches(
identifier=identifier,
requirements=IteratorMapping(
criteria,
operator.methodcaller("iter_requirement"),
{identifier: [requirement]},
),
incompatibilities=IteratorMapping(
criteria,
operator.attrgetter("incompatibilities"),
{identifier: incompatibilities},
),
)
if criterion:
information = list(criterion.information)
information.append(RequirementInformation(requirement, parent))
else:
information = [RequirementInformation(requirement, parent)]
criterion = Criterion(
candidates=build_iter_view(matches),
information=information,
incompatibilities=incompatibilities,
)
if not criterion.candidates:
raise RequirementsConflicted(criterion)
criteria[identifier] = criterion
def _remove_information_from_criteria(
self, criteria: dict[KT, Criterion[RT, CT]], parents: Collection[KT]
) -> None:
"""Remove information from parents of criteria.
Concretely, removes all values from each criterion's ``information``
field that have one of ``parents`` as provider of the requirement.
:param criteria: The criteria to update.
:param parents: Identifiers for which to remove information from all criteria.
"""
if not parents:
return
for key, criterion in criteria.items():
criteria[key] = Criterion(
criterion.candidates,
[
information
for information in criterion.information
if (
information.parent is None
or self._p.identify(information.parent) not in parents
)
],
criterion.incompatibilities,
)
def _get_preference(self, name: KT) -> Preference:
return self._p.get_preference(
identifier=name,
resolutions=self.state.mapping,
candidates=IteratorMapping(
self.state.criteria,
operator.attrgetter("candidates"),
),
information=IteratorMapping(
self.state.criteria,
operator.attrgetter("information"),
),
backtrack_causes=self.state.backtrack_causes,
)
def _is_current_pin_satisfying(
self, name: KT, criterion: Criterion[RT, CT]
) -> bool:
try:
current_pin = self.state.mapping[name]
except KeyError:
return False
return all(
self._p.is_satisfied_by(requirement=r, candidate=current_pin)
for r in criterion.iter_requirement()
)
def _get_updated_criteria(self, candidate: CT) -> dict[KT, Criterion[RT, CT]]:
criteria = self.state.criteria.copy()
for requirement in self._p.get_dependencies(candidate=candidate):
self._add_to_criteria(criteria, requirement, parent=candidate)
return criteria
def _attempt_to_pin_criterion(self, name: KT) -> list[Criterion[RT, CT]]:
criterion = self.state.criteria[name]
causes: list[Criterion[RT, CT]] = []
for candidate in criterion.candidates:
try:
criteria = self._get_updated_criteria(candidate)
except RequirementsConflicted as e:
self._r.rejecting_candidate(e.criterion, candidate)
causes.append(e.criterion)
continue
# Check the newly-pinned candidate actually works. This should
# always pass under normal circumstances, but in the case of a
# faulty provider, we will raise an error to notify the implementer
# to fix find_matches() and/or is_satisfied_by().
satisfied = all(
self._p.is_satisfied_by(requirement=r, candidate=candidate)
for r in criterion.iter_requirement()
)
if not satisfied:
raise InconsistentCandidate(candidate, criterion)
self._r.pinning(candidate=candidate)
self.state.criteria.update(criteria)
# Put newly-pinned candidate at the end. This is essential because
# backtracking looks at this mapping to get the last pin.
self.state.mapping.pop(name, None)
self.state.mapping[name] = candidate
return []
# All candidates tried, nothing works. This criterion is a dead
# end, signal for backtracking.
return causes
def _patch_criteria(
self, incompatibilities_from_broken: list[tuple[KT, list[CT]]]
) -> bool:
# Create a new state from the last known-to-work one, and apply
# the previously gathered incompatibility information.
for k, incompatibilities in incompatibilities_from_broken:
if not incompatibilities:
continue
try:
criterion = self.state.criteria[k]
except KeyError:
continue
matches = self._p.find_matches(
identifier=k,
requirements=IteratorMapping(
self.state.criteria,
operator.methodcaller("iter_requirement"),
),
incompatibilities=IteratorMapping(
self.state.criteria,
operator.attrgetter("incompatibilities"),
{k: incompatibilities},
),
)
candidates: IterableView[CT] = build_iter_view(matches)
if not candidates:
return False
incompatibilities.extend(criterion.incompatibilities)
self.state.criteria[k] = Criterion(
candidates=candidates,
information=list(criterion.information),
incompatibilities=incompatibilities,
)
return True
def _save_state(self) -> None:
"""Save states for potential rollback if optimistic backjumping fails."""
if self._save_states is None:
self._save_states = [
State(
mapping=s.mapping.copy(),
criteria=s.criteria.copy(),
backtrack_causes=s.backtrack_causes[:],
)
for s in self._states
]
def _rollback_states(self) -> None:
"""Rollback states and disable optimistic backjumping."""
self._optimistic_backjumping_ratio = 0.0
if self._save_states:
self._states = self._save_states
self._save_states = None
def _backjump(self, causes: list[RequirementInformation[RT, CT]]) -> bool:
"""Perform backjumping.
When we enter here, the stack is like this::
[ state Z ]
[ state Y ]
[ state X ]
.... earlier states are irrelevant.
1. No pins worked for Z, so it does not have a pin.
2. We want to reset state Y to unpinned, and pin another candidate.
3. State X holds what state Y was before the pin, but does not
have the incompatibility information gathered in state Y.
Each iteration of the loop will:
1. Identify Z. The incompatibility is not always caused by the latest
state. For example, given three requirements A, B and C, with
dependencies A1, B1 and C1, where A1 and B1 are incompatible: the
last state might be related to C, so we want to discard the
previous state.
2. Discard Z.
3. Discard Y but remember its incompatibility information gathered
previously, and the failure we're dealing with right now.
4. Push a new state Y' based on X, and apply the incompatibility
information from Y to Y'.
5a. If this causes Y' to conflict, we need to backtrack again. Make Y'
the new Z and go back to step 2.
5b. If the incompatibilities apply cleanly, end backtracking.
"""
incompatible_reqs: Iterable[CT | RT] = itertools.chain(
(c.parent for c in causes if c.parent is not None),
(c.requirement for c in causes),
)
incompatible_deps = {self._p.identify(r) for r in incompatible_reqs}
while len(self._states) >= 3:
# Remove the state that triggered backtracking.
del self._states[-1]
# Optimistically backtrack to a state that caused the incompatibility
broken_state = self.state
while True:
# Retrieve the last candidate pin and known incompatibilities.
try:
broken_state = self._states.pop()
name, candidate = broken_state.mapping.popitem()
except (IndexError, KeyError):
raise ResolutionImpossible(causes) from None
if (
not self._optimistic_backjumping_ratio
and name not in incompatible_deps
):
# For safe backjumping only backjump if the current dependency
# is not the same as the incompatible dependency
break
# On the first time a non-safe backjump is done the state
# is saved so we can restore it later if the resolution fails
if (
self._optimistic_backjumping_ratio
and self._save_states is None
and name not in incompatible_deps
):
self._save_state()
# If the current dependencies and the incompatible dependencies
# are overlapping then we have likely found a cause of the
# incompatibility
current_dependencies = {
self._p.identify(d) for d in self._p.get_dependencies(candidate)
}
if not current_dependencies.isdisjoint(incompatible_deps):
break
# Fallback: We should not backtrack to the point where
# broken_state.mapping is empty, so stop backtracking for
# a chance for the resolution to recover
if not broken_state.mapping:
break
# Guard: We need at least two state to remain to both
# backtrack and push a new state
if len(self._states) <= 1:
raise ResolutionImpossible(causes)
incompatibilities_from_broken = [
(k, list(v.incompatibilities)) for k, v in broken_state.criteria.items()
]
# Also mark the newly known incompatibility.
incompatibilities_from_broken.append((name, [candidate]))
self._push_new_state()
success = self._patch_criteria(incompatibilities_from_broken)
# It works! Let's work on this new state.
if success:
return True
# State does not work after applying known incompatibilities.
# Try the still previous state.
# No way to backtrack anymore.
return False
def _extract_causes(
self, criteron: list[Criterion[RT, CT]]
) -> list[RequirementInformation[RT, CT]]:
"""Extract causes from list of criterion and deduplicate"""
return list({id(i): i for c in criteron for i in c.information}.values())
def resolve(self, requirements: Iterable[RT], max_rounds: int) -> State[RT, CT, KT]:
if self._states:
raise RuntimeError("already resolved")
self._r.starting()
# Initialize the root state.
self._states = [
State(
mapping=collections.OrderedDict(),
criteria={},
backtrack_causes=[],
)
]
for r in requirements:
try:
self._add_to_criteria(self.state.criteria, r, parent=None)
except RequirementsConflicted as e:
raise ResolutionImpossible(e.criterion.information) from e
# The root state is saved as a sentinel so the first ever pin can have
# something to backtrack to if it fails. The root state is basically
# pinning the virtual "root" package in the graph.
self._push_new_state()
# Variables for optimistic backjumping
optimistic_rounds_cutoff: int | None = None
optimistic_backjumping_start_round: int | None = None
for round_index in range(max_rounds):
self._r.starting_round(index=round_index)
# Handle if optimistic backjumping has been running for too long
if self._optimistic_backjumping_ratio and self._save_states is not None:
if optimistic_backjumping_start_round is None:
optimistic_backjumping_start_round = round_index
optimistic_rounds_cutoff = int(
(max_rounds - round_index) * self._optimistic_backjumping_ratio
)
if optimistic_rounds_cutoff <= 0:
self._rollback_states()
continue
elif optimistic_rounds_cutoff is not None:
if (
round_index - optimistic_backjumping_start_round
>= optimistic_rounds_cutoff
):
self._rollback_states()
continue
unsatisfied_names = [
key
for key, criterion in self.state.criteria.items()
if not self._is_current_pin_satisfying(key, criterion)
]
# All criteria are accounted for. Nothing more to pin, we are done!
if not unsatisfied_names:
self._r.ending(state=self.state)
return self.state
# keep track of satisfied names to calculate diff after pinning
satisfied_names = set(self.state.criteria.keys()) - set(unsatisfied_names)
if len(unsatisfied_names) > 1:
narrowed_unstatisfied_names = list(
self._p.narrow_requirement_selection(
identifiers=unsatisfied_names,
resolutions=self.state.mapping,
candidates=IteratorMapping(
self.state.criteria,
operator.attrgetter("candidates"),
),
information=IteratorMapping(
self.state.criteria,
operator.attrgetter("information"),
),
backtrack_causes=self.state.backtrack_causes,
)
)
else:
narrowed_unstatisfied_names = unsatisfied_names
# If there are no unsatisfied names use unsatisfied names
if not narrowed_unstatisfied_names:
raise RuntimeError("narrow_requirement_selection returned 0 names")
# If there is only 1 unsatisfied name skip calling self._get_preference
if len(narrowed_unstatisfied_names) > 1:
# Choose the most preferred unpinned criterion to try.
name = min(narrowed_unstatisfied_names, key=self._get_preference)
else:
name = narrowed_unstatisfied_names[0]
failure_criterion = self._attempt_to_pin_criterion(name)
if failure_criterion:
causes = self._extract_causes(failure_criterion)
# Backjump if pinning fails. The backjump process puts us in
# an unpinned state, so we can work on it in the next round.
self._r.resolving_conflicts(causes=causes)
try:
success = self._backjump(causes)
except ResolutionImpossible:
if self._optimistic_backjumping_ratio and self._save_states:
failed_optimistic_backjumping = True
else:
raise
else:
failed_optimistic_backjumping = bool(
not success
and self._optimistic_backjumping_ratio
and self._save_states
)
if failed_optimistic_backjumping and self._save_states:
self._rollback_states()
else:
self.state.backtrack_causes[:] = causes
# Dead ends everywhere. Give up.
if not success:
raise ResolutionImpossible(self.state.backtrack_causes)
else:
# discard as information sources any invalidated names
# (unsatisfied names that were previously satisfied)
newly_unsatisfied_names = {
key
for key, criterion in self.state.criteria.items()
if key in satisfied_names
and not self._is_current_pin_satisfying(key, criterion)
}
self._remove_information_from_criteria(
self.state.criteria, newly_unsatisfied_names
)
# Pinning was successful. Push a new state to do another pin.
self._push_new_state()
self._r.ending_round(index=round_index, state=self.state)
raise ResolutionTooDeep(max_rounds)
| Resolution |
python | tensorflow__tensorflow | tensorflow/python/ops/clustering_ops_test.py | {
"start": 2048,
"end": 2670
} | class ____(test.TestCase):
def runTestWithSeed(self, seed):
with self.cached_session():
distances = np.zeros(1000).astype(np.float32)
distances[6] = 10e7
distances[4] = 10e3
sampled_point = clustering_ops.kmc2_chain_initialization(distances, seed)
self.assertAllEqual(sampled_point, 6)
distances[6] = 0.0
sampled_point = clustering_ops.kmc2_chain_initialization(distances, seed)
self.assertAllEqual(sampled_point, 4)
def testBasic(self):
for seed in range(100):
self.runTestWithSeed(seed)
@test_util.run_all_in_graph_and_eager_modes
| KMC2InitializationTest |
python | wandb__wandb | wandb/sdk/data_types/trace_tree.py | {
"start": 3907,
"end": 4620
} | class ____(_dtypes.Type):
name = "wb_trace_tree"
types = [WBTraceTree]
_dtypes.TypeRegistry.add(_WBTraceTreeFileType)
# generate a deterministic 16 character id based on input string
def _hash_id(s: str) -> str:
return hashlib.md5(s.encode("utf-8")).hexdigest()[:16]
def _fallback_serialize(obj: Any) -> str:
try:
return f"<<non-serializable: {type(obj).__qualname__}>>"
except Exception:
return "<<non-serializable>>"
def _safe_serialize(obj: dict) -> str:
try:
return json.dumps(
_json_helper(obj, None),
skipkeys=True,
default=_fallback_serialize,
)
except Exception:
return "{}"
| _WBTraceTreeFileType |
python | tensorflow__tensorflow | tensorflow/python/ops/stateful_random_ops.py | {
"start": 7523,
"end": 40006
} | class ____(autotrackable.AutoTrackable):
"""Random-number generator.
Example:
Creating a generator from a seed:
>>> g = tf.random.Generator.from_seed(1234)
>>> g.normal(shape=(2, 3))
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[ 0.9356609 , 1.0854305 , -0.93788373],
[-0.5061547 , 1.3169702 , 0.7137579 ]], dtype=float32)>
Creating a generator from a non-deterministic state:
>>> g = tf.random.Generator.from_non_deterministic_state()
>>> g.normal(shape=(2, 3))
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=...>
All the constructors allow explicitly choosing an Random-Number-Generation
(RNG) algorithm. Supported algorithms are `"philox"` and `"threefry"`. For
example:
>>> g = tf.random.Generator.from_seed(123, alg="philox")
>>> g.normal(shape=(2, 3))
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[ 0.8673864 , -0.29899067, -0.9310337 ],
[-1.5828488 , 1.2481191 , -0.6770643 ]], dtype=float32)>
CPU, GPU and TPU with the same algorithm and seed will generate the same
integer random numbers. Float-point results (such as the output of `normal`)
may have small numerical discrepancies between different devices.
This class uses a `tf.Variable` to manage its internal state. Every time
random numbers are generated, the state of the generator will change. For
example:
>>> g = tf.random.Generator.from_seed(1234)
>>> g.state
<tf.Variable ... numpy=array([1234, 0, 0])>
>>> g.normal(shape=(2, 3))
<...>
>>> g.state
<tf.Variable ... numpy=array([2770, 0, 0])>
The shape of the state is algorithm-specific.
There is also a global generator:
>>> g = tf.random.get_global_generator()
>>> g.normal(shape=(2, 3))
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=...>
When creating a generator inside a `tf.distribute.Strategy` scope, each
replica will get a different stream of random numbers.
For example, in this code:
```
strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"])
with strat.scope():
g = tf.random.Generator.from_seed(1)
def f():
return g.normal([])
results = strat.run(f).values
```
`results[0]` and `results[1]` will have different values.
If the generator is seeded (e.g. created via `Generator.from_seed`), the
random numbers will be determined by the seed, even though different replicas
get different numbers. One can think of a random number generated on a
replica as a hash of the replica ID and a "master" random number that may be
common to all replicas. Hence, the whole system is still deterministic.
(Note that the random numbers on different replicas are not correlated, even
if they are deterministically determined by the same seed. They are not
correlated in the sense that no matter what statistics one calculates on them,
there won't be any discernable correlation.)
Generators can be freely saved and restored using `tf.train.Checkpoint`. The
checkpoint can be restored in a distribution strategy with a different number
of replicas than the original strategy. If a replica ID is present in both the
original and the new distribution strategy, its state will be properly
restored (i.e. the random-number stream from the restored point will be the
same as that from the saving point) unless the replicas have already diverged
in their RNG call traces before saving (e.g. one replica has made one RNG call
while another has made two RNG calls). We don't have such guarantee if the
generator is saved in a strategy scope and restored outside of any strategy
scope, or vice versa.
When a generator is created within the scope of
`tf.distribute.experimental.ParameterServerStrategy`, the workers
will share the generator's state (placed on one of the parameter
servers). In this way the workers will still get different
random-number streams, as stated above. (This is similar to replicas
in a `tf.distribute.MirroredStrategy` sequentially accessing a
generator created outside the strategy.) Each RNG call on a worker
will incur a round-trip to a parameter server, which may have
performance impacts. When creating a
`tf.distribute.experimental.ParameterServerStrategy`, please make
sure that the `variable_partitioner` argument won't shard small
variables of shape `[2]` or `[3]` (because generator states must not
be sharded). Ways to avoid sharding small variables include setting
`variable_partitioner` to `None` or to
`tf.distribute.experimental.partitioners.MinSizePartitioner` with a
large enough `min_shard_bytes` (see
`tf.distribute.experimental.ParameterServerStrategy`'s documentation
for more details).
"""
@classmethod
def from_state(cls, state, alg):
"""Creates a generator from a state.
See `__init__` for description of `state` and `alg`.
Args:
state: the new state.
alg: the RNG algorithm.
Returns:
The new generator.
"""
return cls(alg=alg, state=state)
@classmethod
def from_seed(cls, seed, alg=None):
"""Creates a generator from a seed.
A seed is a 1024-bit unsigned integer represented either as a Python
integer or a vector of integers. Seeds shorter than 1024-bit will be
padded. The padding, the internal structure of a seed and the way a seed
is converted to a state are all opaque (unspecified). The only semantics
specification of seeds is that two different seeds are likely to produce
two independent generators (but no guarantee).
Args:
seed: the seed for the RNG.
alg: (optional) the RNG algorithm. If None, it will be auto-selected. See
`__init__` for its possible values.
Returns:
The new generator.
"""
if alg is None:
# TODO(b/170668986): more sophisticated algorithm selection
alg = DEFAULT_ALGORITHM
alg = random_ops_util.convert_alg_to_int(alg)
state = create_rng_state(seed, alg)
return cls(state=state, alg=alg)
@classmethod
def from_non_deterministic_state(cls, alg=None):
"""Creates a generator by non-deterministically initializing its state.
The source of the non-determinism will be platform- and time-dependent.
Args:
alg: (optional) the RNG algorithm. If None, it will be auto-selected. See
`__init__` for its possible values.
Returns:
The new generator.
"""
if config.is_op_determinism_enabled():
raise RuntimeError('"from_non_deterministic_state" cannot be called when ' # pylint: disable=g-doc-exception
"determinism is enabled.")
if alg is None:
# TODO(b/170668986): more sophisticated algorithm selection
alg = DEFAULT_ALGORITHM
alg = random_ops_util.convert_alg_to_int(alg)
state = non_deterministic_ints(shape=[_get_state_size(alg)],
dtype=SEED_TYPE)
return cls(state=state, alg=alg)
@classmethod
def from_key_counter(cls, key, counter, alg):
"""Creates a generator from a key and a counter.
This constructor only applies if the algorithm is a counter-based algorithm.
See method `key` for the meaning of "key" and "counter".
Args:
key: the key for the RNG, a scalar of type STATE_TYPE.
counter: a vector of dtype STATE_TYPE representing the initial counter for
the RNG, whose length is algorithm-specific.,
alg: the RNG algorithm. If None, it will be auto-selected. See
`__init__` for its possible values.
Returns:
The new generator.
"""
counter = _convert_to_state_tensor(counter)
key = _convert_to_state_tensor(key)
alg = random_ops_util.convert_alg_to_int(alg)
counter.shape.assert_is_compatible_with([_get_state_size(alg) - 1])
key.shape.assert_is_compatible_with([])
key = array_ops.reshape(key, [1])
state = array_ops.concat([counter, key], 0)
return cls(state=state, alg=alg)
def __init__(self, copy_from=None, state=None, alg=None):
"""Creates a generator.
The new generator will be initialized by one of the following ways, with
decreasing precedence:
(1) If `copy_from` is not None, the new generator is initialized by copying
information from another generator.
(2) If `state` and `alg` are not None (they must be set together), the new
generator is initialized by a state.
Args:
copy_from: a generator to be copied from.
state: a vector of dtype STATE_TYPE representing the initial state of the
RNG, whose length and semantics are algorithm-specific. If it's a
variable, the generator will reuse it instead of creating a new
variable.
alg: the RNG algorithm. Possible values are
`tf.random.Algorithm.PHILOX` for the Philox algorithm and
`tf.random.Algorithm.THREEFRY` for the ThreeFry algorithm
(see paper 'Parallel Random Numbers: As Easy as 1, 2, 3'
[https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]).
The string names `"philox"` and `"threefry"` can also be used.
Note `PHILOX` guarantees the same numbers are produced (given
the same random state) across all architectures (CPU, GPU, XLA etc).
"""
# TODO(b/175072242): Remove distribution-strategy dependencies in this file.
if distribute_lib.has_strategy():
self._distribution_strategy = distribute_lib.get_strategy()
else:
self._distribution_strategy = None
if copy_from is not None:
# All other arguments should be None
assert (alg or state) is None
self._state_var = self._create_variable(copy_from.state, dtype=STATE_TYPE,
trainable=False)
self._alg = copy_from.algorithm
else:
assert alg is not None and state is not None
alg = random_ops_util.convert_alg_to_int(alg)
if isinstance(state, variables.Variable):
_check_state_shape(state.shape, alg)
self._state_var = state
else:
state = _convert_to_state_tensor(state)
_check_state_shape(state.shape, alg)
self._state_var = self._create_variable(state, dtype=STATE_TYPE,
trainable=False)
self._alg = alg
def _create_variable(self, *args, **kwargs):
"""Creates a variable.
Args:
*args: positional arguments passed along to `variables.Variable.
**kwargs: keyword arguments passed along to `variables.Variable.
Returns:
The created variable.
"""
with ops.name_scope("random_generator"):
# Make sure we don't change this name since Keras was using this name
# to filter out the state variable.
kwargs["name"] = "StateVar"
v = variables.Variable(*args, **kwargs)
if isinstance(v, sharded_variable.ShardedVariable):
# RNG state is an atomic entity representing a 128-bit or
# 192-bit value, so it mustn't be sharded.
raise ValueError(
"tf.random.Generator state is sharded, which is not allowed. When "
"creating a tf.distribute.experimental.ParameterServerStrategy, "
"please make sure that the `variable_partitioner` "
"argument won't shard a "
"small variable of shape [2] or [3]. Ways to avoid sharding small "
"variables include setting `variable_partitioner` to None or to "
"tf.distribute.experimental.partitioners.MinSizePartitioner with a "
"large enough `min_shard_bytes`.")
return v
def reset(self, state):
"""Resets the generator by a new state.
See `__init__` for the meaning of "state".
Args:
state: the new state.
"""
state = _convert_to_state_tensor(state)
state.shape.assert_is_compatible_with([_get_state_size(self.algorithm)])
self._state_var.assign(state)
def reset_from_seed(self, seed):
"""Resets the generator by a new seed.
See `from_seed` for the meaning of "seed".
Args:
seed: the new seed.
"""
state = create_rng_state(seed, self.algorithm)
self._state_var.assign(state)
def reset_from_key_counter(self, key, counter):
"""Resets the generator by a new key-counter pair.
See `from_key_counter` for the meaning of "key" and "counter".
Args:
key: the new key.
counter: the new counter.
"""
counter = _convert_to_state_tensor(counter)
key = _convert_to_state_tensor(key)
counter.shape.assert_is_compatible_with(
[_get_state_size(self.algorithm) - 1])
key.shape.assert_is_compatible_with([])
key = array_ops.reshape(key, [1])
state = array_ops.concat([counter, key], 0)
self._state_var.assign(state)
@property
def state(self):
"""The internal state of the RNG."""
return self._state_var
@property
def algorithm(self):
"""The RNG algorithm id (a Python integer or scalar integer Tensor)."""
return self._alg
def _standard_normal(self, shape, dtype):
key, counter = self._prepare_key_counter(shape)
return gen_stateless_random_ops_v2.stateless_random_normal_v2(
shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)
@property
def key(self):
"""The 'key' part of the state of a counter-based RNG.
For a counter-base RNG algorithm such as Philox and ThreeFry (as
described in paper 'Parallel Random Numbers: As Easy as 1, 2, 3'
[https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]),
the RNG state consists of two parts: counter and key. The output is
generated via the formula: output=hash(key, counter), i.e. a hashing of
the counter parametrized by the key. Two RNGs with two different keys can
be thought as generating two independent random-number streams (a stream
is formed by increasing the counter).
Returns:
A scalar which is the 'key' part of the state, if the RNG algorithm is
counter-based; otherwise it raises a ValueError.
"""
alg = self.algorithm
if alg in (a.value for a in random_ops_util.Algorithm):
return self._state_var[-1]
else:
raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg))
def _skip_single_var(self, var, delta):
resource_variable_ops.variable_accessed(var)
# TODO(wangpeng): Cache the cast algorithm instead of casting everytime.
return gen_stateful_random_ops.rng_read_and_skip(
var.handle,
alg=math_ops.cast(self.algorithm, dtypes.int32),
delta=math_ops.cast(delta, dtypes.uint64))
def skip(self, delta):
"""Advance the counter of a counter-based RNG.
Args:
delta: the amount of advancement. The state of the RNG after
`skip(n)` will be the same as that after `normal([n])`
(or any other distribution). The actual increment added to the
counter is an unspecified implementation detail.
Returns:
A `Tensor` of type `int64`.
"""
def update_fn(v):
return self._skip_single_var(v, delta)
# TODO(b/170515001): Always call strategy.extended.update after calling it
# from both replica context and cross-replica context is supported.
if values_util.is_saving_non_distributed():
# Assumes replica context with replica_id=0, since we only save the first
# replica.
return update_fn(self.state)
if self._distribution_strategy is not None:
with distribute_lib.enter_or_assert_strategy(self._distribution_strategy):
if distribute_lib.in_cross_replica_context():
# Code that operates on all replicas of a variable cannot be saved
# without retracing.
values_util.mark_as_unsaveable()
if (distribute_lib.in_cross_replica_context() or
"CentralStorage" in type(self._distribution_strategy).__name__):
# In cross-replica context we need to use strategy.extended.update.
# In CentralStorageStrategy we also need to use
# strategy.extended.update (even for replica context),
# because variable updates here must be within merge_call.
return distribute_lib.get_strategy().extended.update(
self.state, update_fn)
return update_fn(self.state)
def _preprocess_key(self, key):
if self._distribution_strategy is None:
return key
with distribute_lib.enter_or_assert_strategy(self._distribution_strategy):
replica_id = get_replica_id()
if replica_id is not None:
replica_id = array_ops_stack.stack([replica_id, 0], axis=0)
replica_id = math_ops.cast(replica_id, dtypes.uint64)
# Conceptually: key = hash(key, replica_id)
key = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(
shape=[1], key=key, counter=replica_id, dtype=dtypes.uint64,
alg=self.algorithm)
return key
def _prepare_key_counter(self, shape):
delta = math_ops.reduce_prod(shape)
counter_key = self.skip(delta)
counter_size = _get_counter_size(self.algorithm)
counter = array_ops.bitcast(counter_key[:counter_size], dtypes.uint64)
key = array_ops.bitcast(counter_key[counter_size:counter_size + 1],
dtypes.uint64)
key = self._preprocess_key(key)
return key, counter
# The following functions return a tensor and as a side effect update
# self._state_var.
def normal(self, shape, mean=0.0, stddev=1.0, dtype=dtypes.float32,
name=None):
"""Outputs random values from a normal distribution.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output
tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard
deviation of the normal distribution.
dtype: The type of the output.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random normal values.
"""
with ops.name_scope(name, "stateful_normal", [shape, mean, stddev]) as name:
shape = _shape_tensor(shape)
mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
rnd = self._standard_normal(shape, dtype=dtype)
return math_ops.add(rnd * stddev, mean, name=name)
def _truncated_normal(self, shape, dtype):
key, counter = self._prepare_key_counter(shape)
return gen_stateless_random_ops_v2.stateless_truncated_normal_v2(
shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)
def truncated_normal(self, shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
name=None):
"""Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is more than
2 standard deviations from the mean are dropped and re-picked.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output
tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the
truncated normal distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard
deviation of the normal distribution, before truncation.
dtype: The type of the output.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random truncated normal
values.
"""
with ops.name_scope(
name, "truncated_normal", [shape, mean, stddev]) as name:
shape_tensor = _shape_tensor(shape)
mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
rnd = self._truncated_normal(shape_tensor, dtype=dtype)
mul = rnd * stddev_tensor
return math_ops.add(mul, mean_tensor, name=name)
def _uniform(self, shape, dtype):
key, counter = self._prepare_key_counter(shape)
return gen_stateless_random_ops_v2.stateless_random_uniform_v2(
shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)
def _uniform_full_int(self, shape, dtype, name=None):
key, counter = self._prepare_key_counter(shape)
return gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(
shape=shape,
key=key,
counter=counter,
dtype=dtype,
alg=self.algorithm,
name=name)
def uniform(self, shape, minval=0, maxval=None,
dtype=dtypes.float32, name=None):
"""Outputs random values from a uniform distribution.
The generated values follow a uniform distribution in the range
`[minval, maxval)`. The lower bound `minval` is included in the range, while
the upper bound `maxval` is excluded. (For float numbers especially
low-precision types like bfloat16, because of
rounding, the result may sometimes include `maxval`.)
For floats, the default range is `[0, 1)`. For ints, at least `maxval` must
be specified explicitly.
In the integer case, the random integers are slightly biased unless
`maxval - minval` is an exact power of two. The bias is small for values of
`maxval - minval` significantly smaller than the range of the output (either
`2**32` or `2**64`).
For full-range random integers, pass `minval=None` and `maxval=None` with an
integer `dtype` (for integer dtypes, `minval` and `maxval` must be both
`None` or both not `None`).
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output
tensor.
minval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs
to be a scalar). The lower bound (included) on the range of random
values to generate. Pass `None` for full-range integers. Defaults to 0.
maxval: A Tensor or Python value of type `dtype`, broadcastable with
`shape` (for integer types, broadcasting is not supported, so it needs
to be a scalar). The upper bound (excluded) on the range of random
values to generate. Pass `None` for full-range integers. Defaults to 1
if `dtype` is floating point.
dtype: The type of the output.
name: A name for the operation (optional).
Returns:
A tensor of the specified shape filled with random uniform values.
Raises:
ValueError: If `dtype` is integral and `maxval` is not specified.
"""
dtype = dtypes.as_dtype(dtype)
if dtype.is_integer:
if (minval is None) != (maxval is None):
raise ValueError("For integer dtype {}, minval and maxval must be both "
"`None` or both non-`None`; got minval={} and "
"maxval={}".format(dtype, minval, maxval))
elif maxval is None:
maxval = 1
with ops.name_scope(name, "stateful_uniform",
[shape, minval, maxval]) as name:
shape = _shape_tensor(shape)
if dtype.is_integer and minval is None:
return self._uniform_full_int(shape=shape, dtype=dtype, name=name)
minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")
if dtype.is_integer:
key, counter = self._prepare_key_counter(shape)
return gen_stateless_random_ops_v2.stateless_random_uniform_int_v2(
shape=shape,
key=key,
counter=counter,
minval=minval,
maxval=maxval,
alg=self.algorithm,
name=name)
else:
rnd = self._uniform(shape=shape, dtype=dtype)
return math_ops.add(rnd * (maxval - minval), minval, name=name)
def uniform_full_int(self, shape, dtype=dtypes.uint64, name=None):
"""Uniform distribution on an integer type's entire range.
This method is the same as setting `minval` and `maxval` to `None` in the
`uniform` method.
Args:
shape: the shape of the output.
dtype: (optional) the integer type, default to uint64.
name: (optional) the name of the node.
Returns:
A tensor of random numbers of the required shape.
"""
dtype = dtypes.as_dtype(dtype)
with ops.name_scope(name, "stateful_uniform_full_int",
[shape]) as name:
shape = _shape_tensor(shape)
return self._uniform_full_int(shape=shape, dtype=dtype, name=name)
def binomial(self, shape, counts, probs, dtype=dtypes.int32, name=None):
"""Outputs random values from a binomial distribution.
The generated values follow a binomial distribution with specified count and
probability of success parameters.
Example:
```python
counts = [10., 20.]
# Probability of success.
probs = [0.8]
rng = tf.random.Generator.from_seed(seed=234)
binomial_samples = rng.binomial(shape=[2], counts=counts, probs=probs)
counts = ... # Shape [3, 1, 2]
probs = ... # Shape [1, 4, 2]
shape = [3, 4, 3, 4, 2]
rng = tf.random.Generator.from_seed(seed=1717)
# Sample shape will be [3, 4, 3, 4, 2]
binomial_samples = rng.binomial(shape=shape, counts=counts, probs=probs)
```
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output
tensor.
counts: Tensor. The counts of the binomial distribution. Must be
broadcastable with `probs`, and broadcastable with the rightmost
dimensions of `shape`.
probs: Tensor. The probability of success for the
binomial distribution. Must be broadcastable with `counts` and
broadcastable with the rightmost dimensions of `shape`.
dtype: The type of the output. Default: tf.int32
name: A name for the operation (optional).
Returns:
samples: A Tensor of the specified shape filled with random binomial
values. For each i, each samples[i, ...] is an independent draw from
the binomial distribution on counts[i] trials with probability of
success probs[i].
"""
dtype = dtypes.as_dtype(dtype)
with ops.name_scope(name, "binomial", [shape, counts, probs]) as name:
counts = ops.convert_to_tensor(counts, name="counts")
probs = ops.convert_to_tensor(probs, name="probs")
shape_tensor = _shape_tensor(shape)
return gen_stateful_random_ops.stateful_random_binomial(
self.state.handle,
self.algorithm,
shape=shape_tensor,
counts=counts,
probs=probs,
dtype=dtype,
name=name)
# TODO(wangpeng): implement other distributions
def _make_int64_keys(self, shape=()):
# New independent keys are generated via
# `new_key[i] = hash(old_key, counter+i)`, which is exactly what
# `uniform_full_int(dtype=int64)` does for PhiloxRandom_64_128_128 and
# ThreeFry_64_64_64.
return self.uniform_full_int(shape=shape, dtype=dtypes.int64)
def make_seeds(self, count=1):
"""Generates seeds for stateless random ops.
For example:
```python
seeds = get_global_generator().make_seeds(count=10)
for i in range(10):
seed = seeds[:, i]
numbers = stateless_random_normal(shape=[2, 3], seed=seed)
...
```
Args:
count: the number of seed pairs (note that stateless random ops need a
pair of seeds to invoke).
Returns:
A tensor of shape [2, count] and dtype int64.
"""
alg = self.algorithm
if alg in (a.value for a in random_ops_util.Algorithm):
keys = self._make_int64_keys(shape=[count])
# The two seeds for stateless random ops don't have individual semantics
# and are scrambled together, so setting one to zero is fine.
zeros = array_ops.zeros_like(keys)
return array_ops_stack.stack([keys, zeros])
else:
raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg))
def split(self, count=1):
"""Returns a list of independent `Generator` objects.
Two generators are independent of each other in the sense that the
random-number streams they generate don't have statistically detectable
correlations. The new generators are also independent of the old one.
The old generator's state will be changed (like other random-number
generating methods), so two calls of `split` will return different
new generators.
For example:
```python
gens = get_global_generator().split(count=10)
for gen in gens:
numbers = gen.normal(shape=[2, 3])
# ...
gens2 = get_global_generator().split(count=10)
# gens2 will be different from gens
```
The new generators will be put on the current device (possible different
from the old generator's), for example:
```python
with tf.device("/device:CPU:0"):
gen = Generator(seed=1234) # gen is on CPU
with tf.device("/device:GPU:0"):
gens = gen.split(count=10) # gens are on GPU
```
Args:
count: the number of generators to return.
Returns:
A list (length `count`) of `Generator` objects independent of each other.
The new generators have the same RNG algorithm as the old one.
"""
def _key_to_state(alg, key):
# Padding with zeros on the left. The zeros will be the counter.
return [0] * (_get_state_size(alg) - 1) + [key]
alg = self.algorithm
if alg in (a.value for a in random_ops_util.Algorithm):
keys = self._make_int64_keys(shape=[count])
return [Generator(state=_key_to_state(alg, key), alg=alg)
for key in array_ops_stack.unstack(keys, num=count)]
else:
raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg))
# It's not safe to create TF ops before `init_google` is called, so this is
# initialized to None and get a value the first time `get_global_generator` is
# called.
global_generator = None
@tf_export("random.get_global_generator",
"random.experimental.get_global_generator")
def get_global_generator():
"""Retrieves the global generator.
This function will create the global generator the first time it is called,
and the generator will be placed at the default device at that time, so one
needs to be careful when this function is first called. Using a generator
placed on a less-ideal device will incur performance regression.
Returns:
The global `tf.random.Generator` object.
"""
global global_generator
if global_generator is None:
if config.is_op_determinism_enabled():
raise RuntimeError('"get_global_generator" cannot be called if ' # pylint: disable=g-doc-exception
"determinism is enabled, unless "
'"set_global_generator" has already been called. '
'Please call "set_global_generator" first.')
with ops.init_scope():
global_generator = Generator.from_non_deterministic_state()
return global_generator
@tf_export("random.set_global_generator",
"random.experimental.set_global_generator")
def set_global_generator(generator):
"""Replaces the global generator with another `Generator` object.
This function replaces the global generator with the provided `generator`
object.
A random number generator utilizes a `tf.Variable` object to store its state.
The user shall be aware of caveats how `set_global_generator` interacts with
`tf.function`:
- tf.function puts restrictions on Variable creation thus one cannot freely
create a new random generator instance inside `tf.function`.
To call `set_global_generator` inside `tf.function`, the generator instance
must have already been created eagerly.
- tf.function captures the Variable during trace-compilation, thus a compiled
f.function will not be affected `set_global_generator` as demonstrated by
random_test.py/RandomTest.testResetGlobalGeneratorBadWithDefun .
For most use cases, avoid calling `set_global_generator` after program
initialization, and prefer to reset the state of the existing global generator
instead, such as,
>>> rng = tf.random.get_global_generator()
>>> rng.reset_from_seed(30)
Args:
generator: the new `Generator` object.
"""
global global_generator
global_generator = generator
| Generator |
python | django__django | tests/serializers/models/data.py | {
"start": 6001,
"end": 6081
} | class ____(models.Model):
data = models.TimeField(primary_key=True)
| TimePKData |
python | getsentry__sentry | tests/sentry/api/serializers/test_group_stream.py | {
"start": 565,
"end": 3494
} | class ____(
TestCase, BaseMetricsTestCase, SearchIssueTestMixin, PerformanceIssueTestCase
):
def test_environment(self) -> None:
group = self.group
environment = Environment.get_or_create(group.project, "production")
with mock.patch(
"sentry.tsdb.backend.get_range", side_effect=tsdb.backend.get_range
) as get_range:
serialize(
[group],
serializer=StreamGroupSerializer(
environment_func=lambda: environment, stats_period="14d"
),
)
assert get_range.call_count == 1
for args, kwargs in get_range.call_args_list:
assert kwargs["environment_ids"] == [environment.id]
def get_invalid_environment() -> None:
raise Environment.DoesNotExist()
with mock.patch(
"sentry.tsdb.backend.make_series",
side_effect=tsdb.backend.make_series,
) as make_series:
serialize(
[group],
serializer=StreamGroupSerializer(
environment_func=get_invalid_environment, stats_period="14d"
),
)
assert make_series.call_count == 1
@freeze_time(before_now(days=1).replace(hour=13, minute=30, second=0, microsecond=0))
def test_perf_issue(self) -> None:
event = self.create_performance_issue()
group = event.group
serialized = serialize(
group,
serializer=StreamGroupSerializerSnuba(stats_period="24h", organization_id=1),
request=self.make_request(),
)
assert serialized["count"] == "1"
assert serialized["issueCategory"] == "db_query"
assert serialized["issueType"] == "performance_n_plus_one_db_queries"
assert [stat[1] for stat in serialized["stats"]["24h"][:-1]] == [0] * 23
assert serialized["stats"]["24h"][-1][1] == 1
@freeze_time(before_now(days=1).replace(hour=13, minute=30, second=0, microsecond=0))
def test_profiling_issue(self) -> None:
proj = self.create_project()
cur_time = before_now(minutes=5)
event, occurrence, group_info = self.store_search_issue(
proj.id, 1, [f"{ProfileFileIOGroupType.type_id}-group100"], None, cur_time
)
assert group_info
serialized = serialize(
group_info.group,
serializer=StreamGroupSerializerSnuba(stats_period="24h", organization_id=1),
request=self.make_request(),
)
assert serialized["count"] == "1"
assert serialized["issueCategory"] == str(GroupCategory.MOBILE.name).lower()
assert serialized["issueType"] == str(ProfileFileIOGroupType.slug)
assert [stat[1] for stat in serialized["stats"]["24h"][:-1]] == [0] * 23
assert serialized["stats"]["24h"][-1][1] == 1
| StreamGroupSerializerTestCase |
python | encode__django-rest-framework | tests/test_negotiation.py | {
"start": 530,
"end": 606
} | class ____(BaseRenderer):
media_type = 'application/json'
| MockJSONRenderer |
python | tensorflow__tensorflow | tensorflow/lite/python/interpreter_test.py | {
"start": 1703,
"end": 3798
} | class ____(test_util.TensorFlowTestCase):
def testRegistererByName(self):
interpreter = interpreter_wrapper.InterpreterWithCustomOps(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'),
custom_op_registerers=['TF_TestRegisterer'])
self.assertTrue(interpreter._safe_to_run())
self.assertEqual(test_registerer.get_num_test_registerer_calls(), 1)
def testRegistererByFunc(self):
interpreter = interpreter_wrapper.InterpreterWithCustomOps(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'),
custom_op_registerers=[test_registerer.TF_TestRegisterer])
self.assertTrue(interpreter._safe_to_run())
self.assertEqual(test_registerer.get_num_test_registerer_calls(), 1)
def testRegistererFailure(self):
bogus_name = 'CompletelyBogusRegistererName'
with self.assertRaisesRegex(
ValueError, 'Looking up symbol \'' + bogus_name + '\' failed'):
interpreter_wrapper.InterpreterWithCustomOps(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'),
custom_op_registerers=[bogus_name])
# Register GenAI Ops is only supported when using LiteRT wheel.
def testRegisterGenAIOpsFailure(self):
genai_ops_name = 'pywrap_genai_ops.GenAIOpsRegisterer'
with self.assertRaisesRegex(
ValueError,
"Loading library 'pywrap_genai_ops.so' failed with error"
" 'pywrap_genai_ops.so: cannot open shared object file: No such file or"
" directory'",
):
interpreter_wrapper.InterpreterWithCustomOps(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'
),
custom_op_registerers=[genai_ops_name],
)
def testNoCustomOps(self):
interpreter = interpreter_wrapper.InterpreterWithCustomOps(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'))
self.assertTrue(interpreter._safe_to_run())
| InterpreterCustomOpsTest |
python | ansible__ansible | test/units/executor/test_playbook_executor.py | {
"start": 1066,
"end": 6402
} | class ____(unittest.TestCase):
def setUp(self):
# Reset command line args for every test
co.GlobalCLIArgs._Singleton__instance = None
def tearDown(self):
# And cleanup after ourselves too
co.GlobalCLIArgs._Singleton__instance = None
def test_get_serialized_batches(self):
fake_loader = DictDataLoader({
'no_serial.yml': """
- hosts: all
gather_facts: no
tasks:
- debug: var=inventory_hostname
""",
'serial_int.yml': """
- hosts: all
gather_facts: no
serial: 2
tasks:
- debug: var=inventory_hostname
""",
'serial_pct.yml': """
- hosts: all
gather_facts: no
serial: 20%
tasks:
- debug: var=inventory_hostname
""",
'serial_list.yml': """
- hosts: all
gather_facts: no
serial: [1, 2, 3]
tasks:
- debug: var=inventory_hostname
""",
'serial_list_mixed.yml': """
- hosts: all
gather_facts: no
serial: [1, "20%", -1]
tasks:
- debug: var=inventory_hostname
""",
})
mock_inventory = MagicMock()
mock_var_manager = MagicMock()
templar = TemplateEngine(loader=fake_loader)
pbe = PlaybookExecutor(
playbooks=['no_serial.yml', 'serial_int.yml', 'serial_pct.yml', 'serial_list.yml', 'serial_list_mixed.yml'],
inventory=mock_inventory,
variable_manager=mock_var_manager,
loader=fake_loader,
passwords=[],
)
playbook = Playbook.load(pbe._playbooks[0], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])
playbook = Playbook.load(pbe._playbooks[1], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(
pbe._get_serialized_batches(play),
[['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
)
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(
pbe._get_serialized_batches(play),
[['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
)
playbook = Playbook.load(pbe._playbooks[3], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(
pbe._get_serialized_batches(play),
[['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5'], ['host6', 'host7', 'host8'], ['host9']]
)
playbook = Playbook.load(pbe._playbooks[4], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
self.assertEqual(pbe._get_serialized_batches(play), [['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])
# Test when serial percent is under 1.0
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2']
self.assertEqual(pbe._get_serialized_batches(play), [['host0'], ['host1'], ['host2']])
# Test when there is a remainder for serial as a percent
playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
play = playbook.get_plays()[0]
play.post_validate(templar)
mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9', 'host10']
self.assertEqual(
pbe._get_serialized_batches(play),
[['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9'], ['host10']]
)
| TestPlaybookExecutor |
python | facebook__pyre-check | tools/playground/application.py | {
"start": 4756,
"end": 11221
} | class ____:
def __init__(
self, input: str, model: str = "", use_builtin_pysa_models: bool = False
) -> None:
self._directory: Path = Path(tempfile.mkdtemp())
self._stubs: Path = Path(tempfile.mkdtemp())
self.input: str = input
self.model: str = model
LOG.debug(f"Intializing Pysa in `{self._directory}`...")
pyre_configuration = json.dumps(
{
"source_directories": ["."],
"taint_models_path": (
[
str(self._stubs),
os.environ["PYSA_PLAYGROUND_TAINT_MODELS"],
]
if use_builtin_pysa_models
else str(self._stubs)
),
"search_path": [str(self._stubs), os.environ["PYSA_PLAYGROUND_STUBS"]],
}
)
LOG.debug(f"Writing configuration:\n{pyre_configuration}")
pyre_configuration_path = self._directory / PYRE_CONFIG_FILE
pyre_configuration_path.write_text(pyre_configuration)
if model:
LOG.debug("Writing custom model to pysa file")
model_path = self._stubs / CUSTOM_PYSA_MODEL_FILE
model_path.write_text(model)
LOG.debug(f"Writing code:\n{input}")
code_path = self._directory / INPUT_FILE
code_path.write_text(input)
def analyze(self) -> None:
LOG.debug("Running pysa")
with subprocess.Popen(
["pyre", "-n", "analyze"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=self._directory,
text=True,
) as process:
model_verification_errors = []
cache_lines = ""
# pyre-fixme[16]: process.stderr is marked as Optional
for line in iter(process.stderr.readline, b""):
line = line.rstrip()
if line == "":
break
elif "ERROR" in line and "is not part of the environment" in line:
model_verification_errors.append(line)
elif "INFO" in line or "ERROR" in line:
if model_verification_errors:
# Emit all model verification lines together to prevent
# network overhead.
model_verification_error_output = "\n".join(
model_verification_errors
)
emit(
"pysa_results_channel",
{
"type": "output",
"line": model_verification_error_output,
},
)
LOG.debug(model_verification_error_output)
model_verification_errors = []
emit("pysa_results_channel", {"type": "output", "line": line})
LOG.debug(line)
cache_lines += line + "\n"
return_code = process.wait()
if return_code != 0:
result = {"type": "finished", "result": "error"}
else:
result = {"type": "finished", "result": "ok"}
emit("pysa_results_channel", result)
# write to cache now:
with _get_cache_file_path(self.input, self.model).open("w") as cache_file:
cache_file.write(str(return_code) + "\n")
cache_file.write(cache_lines)
def get_server():
application = Flask(__name__)
# You may need to modify the origin to the pyre-check website
# before deployment.
CORS(application)
socketio = SocketIO(application, cors_allowed_origins="*")
LOG.info("Initializizing the pyre server")
pyre = Pyre()
LOG.info("Pyre server is initialized, configuring application routes")
@application.route("/check", methods=["GET", "POST"])
def check() -> Response:
input = (
# pyre-ignore[16] - Request attributes are missing from stub
request.args.get("input")
# pyre-ignore[16] - Request attributes are missing from stub
or request.form.get("input")
# pyre-ignore[16] - Request attributes are missing from stub
or request.json.get("input")
)
if input is None:
return jsonify(errors=["Input not provided"])
LOG.info(f"Checking `{input}`...")
return pyre.check(input)
@socketio.on("analyze", namespace="/analyze")
def analyze(json) -> None:
input = json.get("input", None)
use_builtin_pysa_models = json.get("use_builtin_pysa_models", False)
model = json.get("model", "")
if input is None:
emit(
"pysa_results_channel",
{
"type": "finished",
"result": "error",
"reason": "No code given to analyze.",
},
)
else:
cache_file_path = _get_cache_file_path(input, model)
if cache_file_path.exists():
LOG.info(f"Using cache `{cache_file_path}`...")
cache_contents = _get_cache_contents(cache_file_path).split("\n")
run_status = cache_contents.pop(0)
emit(
"pysa_results_channel",
{
"type": "output",
"line": "\n".join(cache_contents),
},
)
if run_status != "0":
result = {"type": "finished", "result": "error"}
else:
result = {"type": "finished", "result": "ok"}
emit("pysa_results_channel", result)
else:
pysa = Pysa(input, model, use_builtin_pysa_models)
LOG.info(f"Checking `{input}`...")
pysa.analyze()
@application.route("/")
def index() -> str:
return "404"
return application, socketio
def run_server(debug: bool) -> None:
application, socketio = get_server()
socketio.run(application, debug=debug)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--debug", action="store_true")
arguments: argparse.Namespace = parser.parse_args()
run_server(debug=arguments.debug)
| Pysa |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1019344,
"end": 1020162
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
UpdateEnterpriseMembersCanChangeRepositoryVisibilitySetting
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "enterprise", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise")
"""The enterprise with the updated members can change repository
visibility setting.
"""
message = sgqlc.types.Field(String, graphql_name="message")
"""A message confirming the result of updating the members can change
repository visibility setting.
"""
| UpdateEnterpriseMembersCanChangeRepositoryVisibilitySettingPayload |
python | doocs__leetcode | solution/2400-2499/2465.Number of Distinct Averages/Solution.py | {
"start": 0,
"end": 171
} | class ____:
def distinctAverages(self, nums: List[int]) -> int:
nums.sort()
return len(set(nums[i] + nums[-i - 1] for i in range(len(nums) >> 1)))
| Solution |
python | pdm-project__pdm | src/pdm/cli/commands/config.py | {
"start": 348,
"end": 7699
} | class ____(BaseCommand):
"""Display the current configuration"""
ui: termui.UI
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-l",
"--local",
action="store_true",
help="Set config in the project's local configuration file",
)
parser.add_argument("-d", "--delete", action="store_true", help="Unset a configuration key")
parser.add_argument(
"-e",
"--edit",
action="store_true",
help="Edit the configuration file in the default editor(defined by EDITOR env var)",
)
parser.add_argument("key", help="Config key", nargs="?")
parser.add_argument("value", help="Config value", nargs="?")
@staticmethod
def get_editor() -> str:
for key in "VISUAL", "EDITOR":
rv = os.getenv(key)
if rv:
return rv
if os.name == "nt":
return "notepad"
for editor in "sensible-editor", "vim", "nano":
if os.system(f"which {editor} >/dev/null 2>&1") == 0:
return editor
return "vi"
def edit_file(self, path: Path) -> None:
import subprocess
editor = self.get_editor()
proc = subprocess.Popen(f'{editor} "{path}"', shell=True)
if proc.wait() != 0:
raise PdmUsageError(f"Editor {editor} exited abnormally")
def handle(self, project: Project, options: argparse.Namespace) -> None:
self.ui = project.core.ui
if options.edit:
if options.key:
raise PdmUsageError("Cannot specify an argument when `--edit` is given")
if options.delete:
raise PdmUsageError("`--delete` doesn't work when `--edit` is given")
config = project.project_config if options.local else project.global_config
config_path = config.config_file
config_path.parent.mkdir(parents=True, exist_ok=True)
return self.edit_file(config_path)
if options.delete:
self._delete_config(project, options)
elif options.value:
self._set_config(project, options)
elif options.key:
self._get_config(project, options)
else:
self._list_config(project, options)
def _get_config(self, project: Project, options: argparse.Namespace) -> None:
from findpython import ALL_PROVIDERS
if options.key in project.project_config.deprecated: # pragma: no cover
project.core.ui.warn(
f"[warning]DEPRECATED:[/] the config has been renamed to {project.project_config.deprecated[options.key]}",
)
options.key = project.project_config.deprecated[options.key]
try:
value = project.project_config[options.key]
except KeyError:
value = project.global_config[options.key]
if options.key.endswith(".password"):
value = "[i]<hidden>[/i]"
elif options.key == "python.providers" and not value:
value = ["venv", *ALL_PROVIDERS]
project.core.ui.echo(value)
def _set_config(self, project: Project, options: argparse.Namespace) -> None:
config = project.project_config if options.local else project.global_config
if options.key in config.deprecated: # pragma: no cover
project.core.ui.warn(
f"[warning]DEPRECATED:[/] the config has been renamed to {config.deprecated[options.key]}",
)
config[options.key] = options.value
def _show_config(self, config: Mapping[str, Any], supersedes: Mapping[str, Any]) -> None:
from findpython import ALL_PROVIDERS
assert Config.site is not None
for key in sorted(config):
deprecated = ""
canonical_key = key
superseded = key in supersedes
if key in Config.site.deprecated: # pragma: no cover
canonical_key = Config.site.deprecated[key]
if canonical_key in supersedes:
superseded = True
deprecated = f"[error](deprecating: {key})[/]"
elif key not in Config._config_map and not (key.startswith("pypi.") or key.startswith(REPOSITORY)):
continue
extra_style = "dim" if superseded else None
if canonical_key not in Config._config_map:
prefix, name = key.split(".", 1)
if prefix in (SOURCE, REPOSITORY):
title = "non-default PyPI index" if prefix == SOURCE else "custom repository"
self.ui.echo(
f"[warning]# Configuration of {title} `{name}`",
style=extra_style,
verbosity=termui.Verbosity.DETAIL,
)
repository = RepositoryConfig(**config[key], config_prefix=prefix, name=name)
if not repository.url and name in DEFAULT_REPOSITORIES:
repository.url = DEFAULT_REPOSITORIES[name]
self.ui.echo(repository)
continue
config_item = Config._config_map[canonical_key]
self.ui.echo(
f"[warning]# {config_item.description}",
style=extra_style,
verbosity=termui.Verbosity.DETAIL,
)
if key.endswith("password"):
value: Any = "[i]<hidden>[/i]"
else:
value = config[key]
if key == "python.providers" and not value:
value = ["venv", *ALL_PROVIDERS]
self.ui.echo(
f"[primary]{canonical_key}[/]{deprecated} = {value}",
style=extra_style,
)
def _list_config(self, project: Project, options: argparse.Namespace) -> None:
assert Config.site is not None
site_title = "Site/default configuration"
if Config.site.config_file.exists():
site_title += f" ([success]{Config.site.config_file}[/])"
self.ui.echo(site_title, style="bold")
self._show_config(
Config.get_defaults(),
{**project.global_config.self_data, **project.project_config.self_data},
)
if project.global_config.self_data:
self.ui.echo(
f"\nHome configuration ([success]{project.global_config.config_file}[/]):",
style="bold",
)
self._show_config(project.global_config.self_data, project.project_config.self_data)
if project.project_config.self_data:
self.ui.echo(
f"\nProject configuration ([success]{project.project_config.config_file}[/]):",
style="bold",
)
self._show_config(project.project_config.self_data, {})
def _delete_config(self, project: Project, options: argparse.Namespace) -> None:
config = project.project_config if options.local else project.global_config
if options.key in config.deprecated: # pragma: no cover
project.core.ui.warn(
f"[warning]DEPRECATED:[/] the config has been renamed to {config.deprecated[options.key]}",
)
del config[options.key]
| Command |
python | joke2k__faker | faker/providers/address/ta_IN/__init__.py | {
"start": 45,
"end": 9529
} | class ____(AddressProvider):
city_formats = ("{{city_name}}",)
street_name_formats = (
"{{first_name}} {{last_name}}",
"{{last_name}}",
)
street_address_formats = ("{{building_number}} {{street_name}}",)
address_formats = (
"{{street_address}}\n{{city}} {{postcode}}",
"{{street_address}}\n{{city}}-{{postcode}}",
)
building_number_formats = (
"####",
"###",
"##",
"#",
"#/#",
"##/##",
"##/###",
"##/####",
)
postcode_formats = ("######",)
# Source: https://ta.wikipedia.org/wiki/மக்கள்_தொகை_மிகுந்த_இந்திய_நகரங்கள்
cities = (
"சென்னை",
"கோயம்புத்தூர்",
"மதுரை",
"திருச்சிராப்பள்ளி",
"திருப்பூர்",
"சேலம்",
"ஈரோடு",
"திருநெல்வேலி",
"வேலூர்",
"தூத்துக்குடி",
"திண்டுக்கல்",
"தஞ்சாவூர்",
"இராணிப்பேட்டை",
"சிவகாசி",
"கரூர் (கரூர் மாவட்டம்)",
"உதகமண்டலம்",
"ஓசூர்",
"நாகர்கோவில்",
"காஞ்சிபுரம்",
"குமாரபாளையம்",
"காரைக்குடி",
"நெய்வேலி",
"கடலூர்",
"கும்பகோணம்",
"திருவண்ணாமலை",
"பொள்ளாச்சி",
"இராஜபாளையம், விருதுநகர் மாவட்டம்",
"குடியாத்தம்",
"புதுக்கோட்டை",
"வாணியம்பாடி",
"ஆம்பூர்",
"நாகப்பட்டினம்",
"மும்பை பெருநகர்",
"தில்லி",
"கொல்கத்தா பெருநகர்",
"சென்னை பெருநகர்",
"பெங்களூரு",
"ஐதராபாத்",
"புனே",
"அகமதாபாத்",
"கான்பூர்",
"சூரத்",
"ஜெய்ப்பூர்",
"லக்னோ",
"பாட்னா",
"நாக்பூர்",
"இந்தோர்",
"மீரட்",
"நாசிக்",
"போபால்",
"லூதியானா",
"ஆக்ரா",
"வதோதரா",
"புவனேசுவர்",
"கோயம்புத்தூர்",
"ராஜ்கோட்",
"கொச்சி",
"விசாகப்பட்டினம்",
"வாரணாசி",
"மதுரை",
"ஆசன்சோல்",
"அலகாபாத்",
"மைசூர்",
"ஜபல்பூர்",
"ஜம்சேத்பூர்",
"அவுரங்கபாத்",
"அம்ரித்சர்",
"தன்பாத்",
"விஜயவாடா",
"சோலாப்பூர்",
"பிலாய்",
"ஸ்ரீநகர்",
"ராஞ்சி",
"திருவனந்தபுரம்",
"சண்டிகர்",
"குவஹாத்தி",
"கோழிக்கோடு",
"ஜோத்பூர்",
"குவாலியர்",
"ஜலந்தர்",
"திருச்சிராப்பள்ளி",
"பரேலி",
"ஹுப்ளி-தர்வாத்",
"அலிகார்",
"கோட்டா",
"மொரதாபாத்",
"ராய்ப்பூர்",
"தேராதூன்",
"கோரக்பூர்",
"ஜம்மு",
"அமராவதி",
"வாரங்கல்",
"ஜாம்நகர்",
"பிகானேர்",
"சாங்கலி",
"திருப்பூர்",
"பாவ்நகர்",
"மங்களூர்",
"அஜ்மீர்",
"பொகாரோ",
"பெல்காம்",
"புதுச்சேரி",
"சிலிகுரி",
"கண்ணூர்",
"கோலாப்பூர்",
"நான்தேட்",
"ரூர்கேலா",
"துர்காபூர்",
"குல்பர்கா",
"குண்டூர்",
"ஜான்சி",
"சகாரன்பூர்",
"கரக்பூர்",
"கயா",
"ஜல்கான்",
"மதுரா",
"கொல்லம்",
"கோர்பா",
"பிரோசாபாத்",
"திருநெல்வேலி",
"உஜ்ஜைன்",
"அகமத்நகர்",
"நெல்லூர்",
"ராமகுண்டம்",
"ராஜமுந்திரி",
"மாலேகான்",
"உதயப்பூர்",
"அகோலா",
"தாவண்கரே",
"வேலூர்",
"திருவண்ணாமலை",
"காஜுவாகா",
)
# Source: https://ta.wikipedia.org/wiki/இந்தியாவின்_மாநிலங்களும்_ஆட்சிப்பகுதிகளும்
states = (
"ஆந்திரப் பிரதேசம்",
"அருணாச்சலப் பிரதேசம்",
"அசாம்",
"பீகார்",
"சத்தீஸ்கர்",
"கோவா",
"குஜராத்",
"அரியானா",
"இமாச்சலப் பிரதேசம்",
"சம்மு காசுமீர்",
"ஜார்கண்ட்",
"கர்நாடகா",
"கேரளா",
"மத்தியப் பிரதேசம்",
"மகாராஷ்டிரா",
"மணிப்பூர்",
"மேகாலயா",
"மிசோரம்",
"நாகலாந்து",
"ஒரிசா",
"பஞ்சாப்",
"ராஜஸ்தான்",
"சிக்கிம்",
"தமிழ்நாடு",
"தெலுங்கானா",
"திரிபுரா",
"உத்தரப்பிரதேசம்",
"உத்தரகண்ட்",
"மேற்கு வங்கம்",
)
# Source: https://ta.wikipedia.org/wiki/பிறப்பு_விகித_அடிப்படையில்_நாடுகளின்_பட்டியல்
countries = (
"ஆப்கானித்தான்",
"அல்பேனியா",
"அல்ஜீரியா",
"அந்தோரா",
"அங்கோலா",
"அன்டிகுவா பர்புடா",
"அர்கெந்தீனா",
"ஆர்மீனியா",
"ஆத்திரேலியா",
"ஆஸ்திரியா",
"அசர்பைஜான்",
"பஹமாஸ்",
"பகுரைன்",
"வங்காளதேசம்",
"பார்படோசு",
"பெலருஸ்",
"பெல்ஜியம்",
"பெலீசு",
"பெனின்",
"பூட்டான்",
"பொலிவியா",
"பொசுனியா எர்செகோவினா",
"போட்சுவானா",
"பிரேசில்",
"புரூணை",
"பல்கேரியா",
"புர்க்கினா பாசோ",
"புருண்டி",
"கம்போடியா",
"கமரூன்",
"கனடா",
"கேப் வர்டி",
"மத்திய ஆப்பிரிக்கக் குடியரசு",
"சாட்",
"சிலி",
"சீனா",
"கொலம்பியா",
"கொமொரோசு",
"காங்கோ மக்களாட்சிக் குடியரசு",
"காங்கோ மக்களாட்சிக் குடியரசு",
"கோஸ்ட்டா ரிக்கா",
"ஐவரி கோஸ்ட்",
"குரோவாசியா",
"கியூபா",
"சைப்பிரசு",
"செக் குடியரசு",
"டென்மார்க்",
"சீபூத்தீ",
"டொமினிக்கா",
"டொமினிக்கன் குடியரசு",
"எக்குவடோர்",
"எகிப்து",
"எல் சல்வடோர",
"எக்குவடோரியல் கினி",
"எரித்திரியா",
"எசுத்தோனியா",
"எதியோப்பியா",
"பிஜி",
"பின்லாந்து",
"பிரான்சு",
"காபொன்",
"கம்பியா",
"சியார்சியா",
"செருமனி",
"கானா",
"கிரேக்க நாடு",
"கிரெனடா",
"குவாத்தமாலா",
"கினியா",
"கினி-பிசாவு",
"கயானா",
"எயிட்டி",
"ஒண்டுராசு",
"அங்கேரி",
"ஐசுலாந்து",
"இந்தியா",
"இந்தோனேசியா",
"ஈரான்",
"ஈராக்",
"அயர்லாந்து",
"இசுரேல்",
"இத்தாலி",
"ஜமேக்கா",
"சப்பான்",
"யோர்தான்",
"கசக்கஸ்தான்",
"கென்யா",
"கிரிபட்டி",
"வட கொரியா",
"தென் கொரியா",
"குவைத்",
"கிர்கிசுத்தான்",
"லாவோஸ்",
"லாத்வியா",
"லெபனான்",
"லெசோத்தோ",
"லைபீரியா",
"லிபியா",
"லீக்கின்ஸ்டைன்",
"லித்துவேனியா",
"லக்சம்பர்க்",
"மாக்கடோனியக் குடியரசு",
"மடகாசுகர்",
"மலாவி",
"மலேசியா",
"மாலைத்தீவுகள்",
"மாலி",
"மால்ட்டா",
"மார்சல் தீவுகள்",
"மூரித்தானியா",
"மொரிசியசு",
"மெக்சிக்கோ",
"மைக்குரோனீசியக் கூட்டு நாடுகள்",
"மல்தோவா",
"மொனாகோ",
"மங்கோலியா",
"மொண்டெனேகுரோ",
"மொரோக்கோ",
"மொசாம்பிக்",
"மியான்மர்",
"நமீபியா",
"நவூரு",
"நேபாளம்",
"நெதர்லாந்து",
"நியூசிலாந்து",
"நிக்கராகுவா",
"நைஜர்",
"நைஜீரியா",
"நோர்வே",
"ஓமான்",
"பாக்கித்தான்",
"பலாவு",
"பலத்தீன்",
"பனாமா",
"பப்புவா நியூ கினி",
"பரகுவை",
"பெரு",
"பிலிப்பீன்சு",
"போலந்து",
"போர்த்துகல்",
"கட்டார்",
"உருமேனியா",
"உருசியா",
"ருவாண்டா",
"செயிண்ட். கிட்ஸ் நெவிஸ்",
"செயிண்ட். லூசியா",
"செயின்ட் வின்செண்டு மற்றும் கிரெனடீன்கள்",
"சமோவா",
"சான் மரீனோ",
"சாவோ தொமே மற்றும் பிரின்சிப்பி",
"சவூதி அரேபியா",
"செனிகல்",
"செர்பியா",
"சீசெல்சு",
"சியேரா லியோனி",
"சிங்கப்பூர்",
"சிலவாக்கியா",
"சுலோவீனியா",
"சொலமன் தீவுகள்",
"சோமாலியா",
"தென்னாப்பிரிக்கா",
"தெற்கு சூடான்",
"எசுப்பானியா",
"இலங்கை",
"சூடான்",
"சுரிநாம்",
"சுவாசிலாந்து",
"சுவீடன்",
"சுவிட்சர்லாந்து",
"சிரியா",
"சீனக் குடியரசு",
"தாஜிக்ஸ்தான்",
"தன்சானியா",
"தாய்லாந்து",
"கிழக்குத் திமோர்",
"டோகோ",
"தொங்கா",
"டிரினிடாட் மற்றும் டொபாகோ",
"தூனிசியா",
"துருக்கி",
"துருக்மெனிஸ்தான்",
"துவாலு",
"உகாண்டா",
"உக்ரைன்",
"ஐக்கிய அரபு அமீரகம்",
"ஐக்கிய இராச்சியம்",
"ஐக்கிய அமெரிக்கா",
"உருகுவை",
"உஸ்பெகிஸ்தான்",
"வனுவாட்டு",
"வெனிசுவேலா",
"வியட்நாம்",
"மேற்கு சகாரா (Sahrawi)",
"யேமன்",
"சாம்பியா",
"சிம்பாப்வே",
"அங்கியுலா (UK)",
"அரூபா (Netherlands)",
"பெர்முடா (UK)",
"கேமன் தீவுகள் (UK)",
"குயெர்ன்சி (கால்வாய் தீவுகள், UK)",
"யேர்சி (கால்வாய் தீவுகள், UK)",
"குக் தீவுகள் (New Zealand)",
"குராசோ (Netherlands)",
"போக்லாந்து தீவுகள்/Malvinas",
"பரோயே தீவுகள் (Denmark)",
"கிப்ரல்டார் (UK)",
"கிறீன்லாந்து (Denmark)",
"குவாதலூப்பு (France)",
"குவாம் (USA)",
"பிரெஞ்சு கயானா",
"ஆங்காங்",
"மாண் தீவு (UK)",
"கொசோவோ",
"மக்காவு",
"மர்தினிக்கு (France)",
"மயோட்டே (France)",
"மொன்செராட்",
)
def city_name(self) -> str:
return self.random_element(self.cities)
def administrative_unit(self) -> str:
return self.random_element(self.states)
state = administrative_unit
| Provider |
python | kamyu104__LeetCode-Solutions | Python/removing-stars-from-a-string.py | {
"start": 37,
"end": 332
} | class ____(object):
def removeStars(self, s):
"""
:type s: str
:rtype: str
"""
result = []
for c in s:
if c == '*':
result.pop()
else:
result.append(c)
return "".join(result)
| Solution |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 35497,
"end": 36165
} | class ____(BooleanFunction):
"""
Logical NOR function.
It evaluates its arguments in order, giving False immediately if any
of them are True, and True if they are all False.
Returns False if any argument is True
Returns True if all arguments are False
Examples
========
>>> from sympy.logic.boolalg import Nor
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Nor(True, False)
False
>>> Nor(True, True)
False
>>> Nor(False, True)
False
>>> Nor(False, False)
True
>>> Nor(x, y)
~(x | y)
"""
@classmethod
def eval(cls, *args):
return Not(Or(*args))
| Nor |
python | django__django | tests/serializers/models/base.py | {
"start": 355,
"end": 783
} | class ____(models.Model):
kind = models.CharField(max_length=10)
name = models.CharField(max_length=10)
value = models.CharField(max_length=10)
objects = CategoryMetaDataManager()
class Meta:
unique_together = (("kind", "name"),)
def __str__(self):
return "[%s:%s]=%s" % (self.kind, self.name, self.value)
def natural_key(self):
return (self.kind, self.name)
| CategoryMetaData |
python | openai__openai-python | src/openai/resources/fine_tuning/alpha/graders.py | {
"start": 9801,
"end": 10140
} | class ____:
def __init__(self, graders: AsyncGraders) -> None:
self._graders = graders
self.run = _legacy_response.async_to_raw_response_wrapper(
graders.run,
)
self.validate = _legacy_response.async_to_raw_response_wrapper(
graders.validate,
)
| AsyncGradersWithRawResponse |
python | dask__distributed | distributed/comm/ucx.py | {
"start": 1633,
"end": 2110
} | class ____(Backend):
def get_connector(self):
return UCXConnector()
def get_listener(self, loc, handle_comm, deserialize, **connection_args):
return UCXListener(loc, handle_comm, deserialize, **connection_args)
def get_address_host(self, loc):
_raise_deprecated()
def resolve_address(self, loc):
_raise_deprecated()
def get_local_address_for(self, loc):
_raise_deprecated()
backends["ucx"] = UCXBackend()
| UCXBackend |
python | instagram__MonkeyType | tests/test_tracing.py | {
"start": 3587,
"end": 3754
} | class ____:
@property
def meaning_of_life(self) -> int:
return 42
@pytest.fixture
def collector() -> TraceCollector:
return TraceCollector()
| Oracle |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 479214,
"end": 479814
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"oauth_application_name",
"oauth_application_resource_path",
"oauth_application_url",
)
oauth_application_name = sgqlc.types.Field(
String, graphql_name="oauthApplicationName"
)
oauth_application_resource_path = sgqlc.types.Field(
URI, graphql_name="oauthApplicationResourcePath"
)
oauth_application_url = sgqlc.types.Field(URI, graphql_name="oauthApplicationUrl")
| OauthApplicationAuditEntryData |
python | kamyu104__LeetCode-Solutions | Python/count-submatrices-with-all-ones.py | {
"start": 908,
"end": 1655
} | class ____(object):
def numSubmat(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
def count(heights):
dp, stk = [0]*len(heights), []
for i in xrange(len(heights)):
while stk and heights[stk[-1]] >= heights[i]:
stk.pop()
dp[i] = dp[stk[-1]] + heights[i]*(i-stk[-1]) if stk else heights[i]*(i-(-1))
stk.append(i)
return sum(dp)
result = 0
heights = [0]*len(mat[0])
for i in xrange(len(mat)):
for j in xrange(len(mat[0])):
heights[j] = heights[j]+1 if mat[i][j] == 1 else 0
result += count(heights)
return result
| Solution2 |
python | numpy__numpy | numpy/linalg/lapack_lite/make_lite.py | {
"start": 2673,
"end": 5002
} | class ____:
"""Container for a bunch of Fortran routines.
"""
def __init__(self, src_dirs):
self._src_dirs = src_dirs
self.names_to_routines = {}
def _findRoutine(self, rname):
rname = rname.lower()
for s in self._src_dirs:
ffilename = os.path.join(s, rname + '.f')
if os.path.exists(ffilename):
return self._newFortranRoutine(rname, ffilename)
return UnknownFortranRoutine(rname)
def _newFortranRoutine(self, rname, filename):
return FortranRoutine(rname, filename)
def addIgnorableRoutine(self, rname):
"""Add a routine that we don't want to consider when looking at
dependencies.
"""
rname = rname.lower()
routine = UnknownFortranRoutine(rname)
self.names_to_routines[rname] = routine
def addRoutine(self, rname):
"""Add a routine to the library.
"""
self.getRoutine(rname)
def getRoutine(self, rname):
"""Get a routine from the library. Will add if it's not found.
"""
unique = []
rname = rname.lower()
routine = self.names_to_routines.get(rname, unique)
if routine is unique:
routine = self._findRoutine(rname)
self.names_to_routines[rname] = routine
return routine
def allRoutineNames(self):
"""Return the names of all the routines.
"""
return list(self.names_to_routines.keys())
def allRoutines(self):
"""Return all the routines.
"""
return list(self.names_to_routines.values())
def resolveAllDependencies(self):
"""Try to add routines to the library to satisfy all the dependencies
for each routine in the library.
Returns a set of routine names that have the dependencies unresolved.
"""
done_this = set()
last_todo = set()
while True:
todo = set(self.allRoutineNames()) - done_this
if todo == last_todo:
break
for rn in todo:
r = self.getRoutine(rn)
deps = r.dependencies()
for d in deps:
self.addRoutine(d)
done_this.add(rn)
last_todo = todo
return todo
| FortranLibrary |
python | cython__cython | Cython/Debugger/Tests/test_libcython_in_gdb.py | {
"start": 7166,
"end": 7497
} | class ____(DebugTestCase):
def step(self, varnames_and_values, source_line=None, lineno=None):
gdb.execute(self.command)
for varname, value in varnames_and_values:
self.assertEqual(self.read_var(varname), value, self.local_info())
self.lineno_equals(source_line, lineno)
| DebugStepperTestCase |
python | jazzband__django-pipeline | pipeline/finders.py | {
"start": 833,
"end": 1455
} | class ____(BaseFinder):
def find(self, path, **kwargs):
"""
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
"""
matches = []
for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()):
if normpath(elem["output_filename"]) == normpath(path):
match = safe_join(settings.PIPELINE_ROOT, path)
if not kwargs.get("find_all", kwargs.get("all", False)):
return match
matches.append(match)
return matches
def list(self, *args):
return []
| ManifestFinder |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 10138,
"end": 13059
} | class ____(SubscriptMixin, UsesOnlyOneItemMixin, TestCase):
SUPPORTS_PUTTING_WITHOUT_GETTING = False
def _getFUT(self):
return queue.Channel
def test_get_nowait_unlock_channel(self):
# get_nowait runs fine in the hub, and
# it switches to a waiting putter if needed.
result = []
q = self._makeOne()
p = gevent.spawn(q.put, 5)
def store_result(func, *args):
result.append(func(*args))
self.assertTrue(q.empty())
self.assertTrue(q.full())
gevent.sleep(0.001)
self.assertTrue(q.empty())
self.assertTrue(q.full())
get_hub().loop.run_callback(store_result, q.get_nowait)
gevent.sleep(0.001)
self.assertTrue(q.empty())
self.assertTrue(q.full())
self.assertEqual(result, [5])
self.assertTrue(p.ready())
self.assertTrue(p.dead)
self.assertTrue(q.empty())
def test_zero_max_size(self):
q = self._makeOne()
def sender(evt, q):
q.put('hi')
evt.set('done')
def receiver(evt, q):
x = q.get()
evt.set(x)
e1 = AsyncResult()
e2 = AsyncResult()
p1 = gevent.spawn(sender, e1, q)
gevent.sleep(0.001)
self.assertTrue(not e1.ready())
p2 = gevent.spawn(receiver, e2, q)
self.assertEqual(e2.get(), 'hi')
self.assertEqual(e1.get(), 'done')
with gevent.Timeout(0):
gevent.joinall([p1, p2])
def test_send(self):
channel = self._makeOne()
events = []
def another_greenlet():
events.append(channel.get())
events.append(channel.get())
g = gevent.spawn(another_greenlet)
events.append('sending')
channel.put('hello')
events.append('sent hello')
channel.put('world')
events.append('sent world')
self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events)
g.get()
def test_wait(self):
channel = self._makeOne()
events = []
def another_greenlet():
events.append('sending hello')
channel.put('hello')
events.append('sending world')
channel.put('world')
events.append('sent world')
g = gevent.spawn(another_greenlet)
events.append('waiting')
events.append(channel.get())
events.append(channel.get())
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events)
gevent.sleep(0)
self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events)
g.get()
def test_iterable(self):
channel = self._makeOne()
gevent.spawn(channel.put, StopIteration)
r = list(channel)
self.assertEqual(r, [])
| TestChannel |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/tests/cloud/test_runs.py | {
"start": 285,
"end": 1592
} | class ____:
async def test_get_dbt_cloud_run_info(self, dbt_cloud_credentials):
with respx.mock(using="httpx") as respx_mock:
respx_mock.get(
"https://cloud.getdbt.com/api/v2/accounts/123456789/runs/12/",
headers={"Authorization": "Bearer my_api_key"},
).mock(return_value=Response(200, json={"data": {"id": 10000}}))
response = await get_dbt_cloud_run_info.fn(
dbt_cloud_credentials=dbt_cloud_credentials,
run_id=12,
)
assert response == {"id": 10000}
async def test_get_nonexistent_run(self, dbt_cloud_credentials):
with respx.mock(using="httpx") as respx_mock:
respx_mock.get(
"https://cloud.getdbt.com/api/v2/accounts/123456789/runs/12/",
headers={"Authorization": "Bearer my_api_key"},
).mock(
return_value=Response(
404, json={"status": {"user_message": "Not found!"}}
)
)
with pytest.raises(DbtCloudGetRunFailed, match="Not found!"):
await get_dbt_cloud_run_info.fn(
dbt_cloud_credentials=dbt_cloud_credentials,
run_id=12,
)
| TestGetDbtCloudRunInfo |
python | facebookresearch__faiss | tests/test_clustering.py | {
"start": 343,
"end": 5332
} | class ____(unittest.TestCase):
def test_clustering(self):
d = 64
n = 1000
rs = np.random.RandomState(123)
x = rs.uniform(size=(n, d)).astype('float32')
x *= 10
km = faiss.Kmeans(d, 32, niter=10)
err32 = km.train(x)
# check that objective is decreasing
prev = 1e50
for o in km.obj:
self.assertGreater(prev, o)
prev = o
km = faiss.Kmeans(d, 64, niter=10)
err64 = km.train(x)
# check that 64 centroids give a lower quantization error than 32
self.assertGreater(err32, err64)
km = faiss.Kmeans(d, 32, niter=10, int_centroids=True)
err_int = km.train(x)
# check that integer centoids are not as good as float ones
self.assertGreater(err_int, err32)
self.assertTrue(np.all(km.centroids == np.floor(km.centroids)))
def test_nasty_clustering(self):
d = 2
rs = np.random.RandomState(123)
x = np.zeros((100, d), dtype='float32')
for i in range(5):
x[i * 20:i * 20 + 20] = rs.uniform(size=d)
# we have 5 distinct points but ask for 10 centroids...
km = faiss.Kmeans(d, 10, niter=10, verbose=True)
km.train(x)
def test_1ptpercluster(self):
# https://github.com/facebookresearch/faiss/issues/842
X = np.random.randint(0, 1, (5, 10)).astype('float32')
k = 5
niter = 10
verbose = True
kmeans = faiss.Kmeans(X.shape[1], k, niter=niter, verbose=verbose)
kmeans.train(X)
l2_distances, I = kmeans.index.search(X, 1)
def test_weighted(self):
d = 32
sigma = 0.1
# Data is naturally clustered in 10 clusters.
# 5 clusters have 100 points
# 5 clusters have 10 points
# run k-means with 5 clusters
ccent = faiss.randn((10, d), 123)
faiss.normalize_L2(ccent)
x = [ccent[i] + sigma * faiss.randn((100, d), 1234 + i) for i in range(5)]
x += [ccent[i] + sigma * faiss.randn((10, d), 1234 + i) for i in range(5, 10)]
x = np.vstack(x)
clus = faiss.Clustering(d, 5)
index = faiss.IndexFlatL2(d)
clus.train(x, index)
cdis1, perm1 = index.search(ccent, 1)
# distance^2 of ground-truth centroids to clusters
cdis1_first = cdis1[:5].sum()
cdis1_last = cdis1[5:].sum()
# now assign weight 0.1 to the 5 first clusters and weight 10
# to the 5 last ones and re-run k-means
weights = np.ones(100 * 5 + 10 * 5, dtype='float32')
weights[:100 * 5] = 0.1
weights[100 * 5:] = 10
clus = faiss.Clustering(d, 5)
index = faiss.IndexFlatL2(d)
clus.train(x, index, weights=weights)
cdis2, perm2 = index.search(ccent, 1)
# distance^2 of ground-truth centroids to clusters
cdis2_first = cdis2[:5].sum()
cdis2_last = cdis2[5:].sum()
# with the new clustering, the last should be much (*2) closer
# to their centroids
self.assertGreater(cdis1_last, cdis1_first * 2)
self.assertGreater(cdis2_first, cdis2_last * 2)
def test_encoded(self):
d = 32
k = 5
xt, xb, xq = get_dataset_2(d, 1000, 0, 0)
# make sure that training on a compressed then decompressed
# dataset gives the same result as decompressing on-the-fly
codec = faiss.IndexScalarQuantizer(d, faiss.ScalarQuantizer.QT_4bit)
codec.train(xt)
codes = codec.sa_encode(xt)
xt2 = codec.sa_decode(codes)
clus = faiss.Clustering(d, k)
# clus.verbose = True
clus.niter = 0
index = faiss.IndexFlatL2(d)
clus.train(xt2, index)
ref_centroids = faiss.vector_to_array(clus.centroids).reshape(-1, d)
_, ref_errs = index.search(xt2, 1)
clus = faiss.Clustering(d, k)
# clus.verbose = True
clus.niter = 0
clus.decode_block_size = 120
index = faiss.IndexFlatL2(d)
clus.train_encoded(codes, codec, index)
new_centroids = faiss.vector_to_array(clus.centroids).reshape(-1, d)
_, new_errs = index.search(xt2, 1)
# It's the same operation, so should be bit-exact the same
self.assertTrue(np.all(ref_centroids == new_centroids))
def test_init(self):
d = 32
k = 5
xt, xb, xq = get_dataset_2(d, 1000, 0, 0)
km = faiss.Kmeans(d, k, niter=4)
km.train(xt)
km2 = faiss.Kmeans(d, k, niter=4)
km2.train(xt, init_centroids=km.centroids)
# check that the initial objective is better for km2 than km
self.assertGreater(km.obj[0], km2.obj[0] * 1.01)
def test_stats(self):
d = 32
k = 5
xt, xb, xq = get_dataset_2(d, 1000, 0, 0)
km = faiss.Kmeans(d, k, niter=4)
km.train(xt)
assert list(km.obj) == [st['obj'] for st in km.iteration_stats]
| TestClustering |
python | pytorch__pytorch | test/mobile/lightweight_dispatch/tests_setup.py | {
"start": 2278,
"end": 2615
} | class ____(torch.nn.Module):
def forward(self, index):
values = torch.tensor([[4.0, 1.0, 1.0, 16.0]])
return values[torch.tensor(0), index]
# conv2d(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1,
# int groups=1) -> Tensor
@save_model
| ModelWithListOfOptionalTensors |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/range_test.py | {
"start": 1290,
"end": 6519
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStop(self, output_type):
stop = 5
dataset = dataset_ops.Dataset.range(stop, output_type=output_type)
expected_output = np.arange(stop, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStartStop(self, output_type):
start, stop = 2, 5
dataset = dataset_ops.Dataset.range(start, stop, output_type=output_type)
expected_output = np.arange(start, stop, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStartStopStep(self, output_type):
start, stop, step = 2, 10, 2
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
expected_output = np.arange(
start, stop, step, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testZeroStep(self, output_type):
start, stop, step = 2, 10, 0
with self.assertRaises(errors.InvalidArgumentError):
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
self.evaluate(dataset._variant_tensor)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testNegativeStep(self, output_type):
start, stop, step = 2, 10, -1
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
expected_output = np.arange(
start, stop, step, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStopLessThanStart(self, output_type):
start, stop = 10, 2
dataset = dataset_ops.Dataset.range(start, stop, output_type=output_type)
expected_output = np.arange(start, stop, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStopLessThanStartWithPositiveStep(self, output_type):
start, stop, step = 10, 2, 2
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
expected_output = np.arange(
start, stop, step, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(output_type=[
dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64
])))
def testStopLessThanStartWithNegativeStep(self, output_type):
start, stop, step = 10, 2, -1
dataset = dataset_ops.Dataset.range(
start, stop, step, output_type=output_type)
expected_output = np.arange(
start, stop, step, dtype=output_type.as_numpy_dtype)
self.assertDatasetProduces(dataset, expected_output=expected_output)
self.assertEqual(output_type, dataset_ops.get_legacy_output_types(dataset))
@combinations.generate(test_base.default_test_combinations())
def testName(self):
dataset = dataset_ops.Dataset.range(5, name="range")
self.assertDatasetProduces(dataset, list(range(5)))
| RangeTest |
python | python-openxml__python-docx | tests/image/test_bmp.py | {
"start": 198,
"end": 1108
} | class ____:
def it_can_construct_from_a_bmp_stream(self, Bmp__init__):
cx, cy, horz_dpi, vert_dpi = 26, 43, 200, 96
bytes_ = (
b"fillerfillerfiller\x1a\x00\x00\x00\x2b\x00\x00\x00"
b"fillerfiller\xb8\x1e\x00\x00\x00\x00\x00\x00"
)
stream = io.BytesIO(bytes_)
bmp = Bmp.from_stream(stream)
Bmp__init__.assert_called_once_with(ANY, cx, cy, horz_dpi, vert_dpi)
assert isinstance(bmp, Bmp)
def it_knows_its_content_type(self):
bmp = Bmp(None, None, None, None)
assert bmp.content_type == MIME_TYPE.BMP
def it_knows_its_default_ext(self):
bmp = Bmp(None, None, None, None)
assert bmp.default_ext == "bmp"
# fixtures -------------------------------------------------------
@pytest.fixture
def Bmp__init__(self, request):
return initializer_mock(request, Bmp)
| DescribeBmp |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_nbagg.py | {
"start": 5149,
"end": 7919
} | class ____:
"""
Manages the Comm connection between IPython and the browser (client).
Comms are 2 way, with the CommSocket being able to publish a message
via the send_json method, and handle a message with on_message. On the
JS side figure.send_message and figure.ws.onmessage do the sending and
receiving respectively.
"""
def __init__(self, manager):
self.supports_binary = None
self.manager = manager
self.uuid = str(uuid.uuid4())
# Publish an output area with a unique ID. The javascript can then
# hook into this area.
display(HTML("<div id=%r></div>" % self.uuid))
try:
self.comm = Comm('matplotlib', data={'id': self.uuid})
except AttributeError as err:
raise RuntimeError('Unable to create an IPython notebook Comm '
'instance. Are you in the IPython '
'notebook?') from err
self.comm.on_msg(self.on_message)
manager = self.manager
self._ext_close = False
def _on_close(close_message):
self._ext_close = True
manager.remove_comm(close_message['content']['comm_id'])
manager.clearup_closed()
self.comm.on_close(_on_close)
def is_open(self):
return not (self._ext_close or self.comm._closed)
def on_close(self):
# When the socket is closed, deregister the websocket with
# the FigureManager.
if self.is_open():
try:
self.comm.close()
except KeyError:
# apparently already cleaned it up?
pass
def send_json(self, content):
self.comm.send({'data': json.dumps(content)})
def send_binary(self, blob):
if self.supports_binary:
self.comm.send({'blob': 'image/png'}, buffers=[blob])
else:
# The comm is ASCII, so we send the image in base64 encoded data
# URL form.
data = b64encode(blob).decode('ascii')
data_uri = f"data:image/png;base64,{data}"
self.comm.send({'data': data_uri})
def on_message(self, message):
# The 'supports_binary' message is relevant to the
# websocket itself. The other messages get passed along
# to matplotlib as-is.
# Every message has a "type" and a "figure_id".
message = json.loads(message['content']['data'])
if message['type'] == 'closing':
self.on_close()
self.manager.clearup_closed()
elif message['type'] == 'supports_binary':
self.supports_binary = message['value']
else:
self.manager.handle_json(message)
@_Backend.export
| CommSocket |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 40101,
"end": 40671
} | class ____(Sky2PixProjection, HEALPix):
r"""
HEALPix projection - sky to pixel.
Corresponds to the ``HPX`` projection in FITS WCS.
Parameters
----------
H : float
The number of facets in longitude direction.
X : float
The number of facets in latitude direction.
"""
_separable = True
H = _ParameterDS(
default=4.0, description="The number of facets in longitude direction."
)
X = _ParameterDS(
default=3.0, description="The number of facets in latitude direction."
)
| Sky2Pix_HEALPix |
python | getsentry__sentry | src/sentry/api/endpoints/broadcast_index.py | {
"start": 1129,
"end": 8291
} | class ____(ControlSiloOrganizationEndpoint):
owner = ApiOwner.UNOWNED
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (OrganizationPermission,)
def _get_serializer(self, request: Request):
if request.access.has_permission("broadcasts.admin"):
return AdminBroadcastSerializer
return BroadcastSerializer
def _serialize_objects(self, items, request):
serializer_cls = self._get_serializer(request)
return serialize(items, request.user, serializer=serializer_cls())
def _secondary_filtering(self, request: Request, organization_slug, queryset):
# used in the SAAS product
return list(queryset)
def convert_args(self, request: Request, *args, **kwargs):
organization_id_or_slug: int | str | None = None
if args and args[0] is not None:
organization_id_or_slug = args[0]
# Required so it behaves like the original convert_args, where organization_id_or_slug was another parameter
# TODO: Remove this once we remove the old `organization_slug` parameter from getsentry
args = args[1:]
else:
organization_id_or_slug = kwargs.pop("organization_id_or_slug", None) or kwargs.pop(
"organization_slug", None
)
if organization_id_or_slug:
args, kwargs = super().convert_args(request, organization_id_or_slug)
return (args, kwargs)
def get(
self, request: Request, organization: RpcOrganization | None = None, **kwargs
) -> Response:
if request.GET.get("show") == "all" and request.access.has_permission("broadcasts.admin"):
# superusers can slice and dice
queryset = Broadcast.objects.all().order_by("-date_added")
else:
# only allow active broadcasts if they're not a superuser
queryset = Broadcast.objects.filter(
Q(date_expires__isnull=True) | Q(date_expires__gt=timezone.now()), is_active=True
).order_by("-date_added")
query = request.GET.get("query")
if query:
tokens = tokenize_query(query)
for key, value in tokens.items():
if key == "query":
value_str = " ".join(value)
queryset = queryset.filter(
Q(title__icontains=value_str)
| Q(message__icontains=value_str)
| Q(link__icontains=value_str)
)
elif key == "id":
queryset = queryset.filter(id__in=value)
elif key == "link":
queryset = queryset.filter(in_icontains("link", value))
elif key == "status":
filters = []
for v in value:
v = v.lower()
if v == "active":
filters.append(
Q(date_expires__isnull=True, is_active=True)
| Q(date_expires__gt=timezone.now(), is_active=True)
)
elif v == "inactive":
filters.append(Q(date_expires__lt=timezone.now()) | Q(is_active=False))
else:
queryset = queryset.none()
if filters:
queryset = queryset.filter(reduce(or_, filters))
else:
queryset = queryset.none()
if organization:
data = self._secondary_filtering(request, organization, queryset)
return self.respond(self._serialize_objects(data, request))
sort_by = request.GET.get("sortBy")
if sort_by == "expires":
order_by = "-date_expires"
paginator_cls = DateTimePaginator
else:
order_by = "-date_added"
paginator_cls = DateTimePaginator
return self.paginate(
request=request,
queryset=queryset,
order_by=order_by,
on_results=lambda x: self._serialize_objects(x, request),
paginator_cls=paginator_cls,
)
def put(self, request: Request) -> Response:
if not request.user.is_authenticated:
return Response(status=401)
validator = BroadcastValidator(data=request.data, partial=True)
if not validator.is_valid():
return self.respond(validator.errors, status=400)
result = validator.validated_data
queryset = Broadcast.objects.filter(is_active=True)
ids = request.GET.getlist("id")
if ids:
queryset = queryset.filter(id__in=ids)
if result.get("hasSeen"):
if ids:
unseen_queryset = queryset
else:
unseen_queryset = queryset.exclude(
id__in=queryset.filter(broadcastseen__user_id=request.user.id).values("id")
)
for broadcast in unseen_queryset:
try:
with transaction.atomic(using=router.db_for_write(BroadcastSeen)):
BroadcastSeen.objects.create(broadcast=broadcast, user_id=request.user.id)
except IntegrityError:
pass
return self.respond(result)
def post(self, request: Request) -> Response:
if not request.user.is_authenticated:
return Response(status=400)
if not request.access.has_permission("broadcasts.admin"):
return self.respond(status=401)
validator = AdminBroadcastValidator(data=request.data)
if not validator.is_valid():
return self.respond(validator.errors, status=400)
result = validator.validated_data
with transaction.atomic(using=router.db_for_write(Broadcast)):
broadcast = Broadcast.objects.create(
title=result["title"],
message=result["message"],
link=result["link"],
is_active=result.get("isActive") or False,
date_expires=result.get("dateExpires"),
media_url=result.get("mediaUrl"),
category=result.get("category"),
created_by_id=User.objects.get(id=request.user.id),
)
logger.info(
"broadcasts.create",
extra={
"ip_address": request.META["REMOTE_ADDR"],
"user_id": request.user.id,
"broadcast_id": broadcast.id,
},
)
if result.get("hasSeen"):
try:
with transaction.atomic(using=router.db_for_write(BroadcastSeen)):
BroadcastSeen.objects.create(broadcast=broadcast, user_id=request.user.id)
except IntegrityError:
pass
return self.respond(self._serialize_objects(broadcast, request))
| BroadcastIndexEndpoint |
python | networkx__networkx | networkx/classes/tests/test_multigraph.py | {
"start": 17218,
"end": 17775
} | class ____(nx.MultiGraph):
node_dict_factory = CustomDictClass # type: ignore[assignment]
node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
| MultiGraphSubClass |
python | jina-ai__jina | jina/logging/logger.py | {
"start": 1903,
"end": 2449
} | class ____(_RichHandler):
"""Override the original rich handler for more compact layout."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._log_render = _MyLogRender(
show_time=self._log_render.show_time,
show_level=self._log_render.show_level,
show_path=self._log_render.show_path,
time_format=self._log_render.time_format,
omit_repeated_times=self._log_render.omit_repeated_times,
level_width=None,
)
| RichHandler |
python | django-debug-toolbar__django-debug-toolbar | tests/test_utils.py | {
"start": 974,
"end": 1852
} | class ____(unittest.TestCase):
def test_importlib_path_issue_1612(self):
trace = [
("/server/app.py", 1, "foo", ["code line 1", "code line 2"], {"foo": "bar"})
]
result = render_stacktrace(trace)
self.assertIn('<span class="djdt-path">/server/</span>', result)
self.assertIn('<span class="djdt-file">app.py</span> in', result)
trace = [
(
"<frozen importlib._bootstrap>",
1,
"foo",
["code line 1", "code line 2"],
{"foo": "bar"},
)
]
result = render_stacktrace(trace)
self.assertIn('<span class="djdt-path"></span>', result)
self.assertIn(
'<span class="djdt-file"><frozen importlib._bootstrap></span> in',
result,
)
| RenderStacktraceTestCase |
python | langchain-ai__langchain | libs/langchain/langchain_classic/output_parsers/structured.py | {
"start": 930,
"end": 3465
} | class ____(BaseOutputParser[dict[str, Any]]):
"""Parse the output of an LLM call to a structured output."""
response_schemas: list[ResponseSchema]
"""The schemas for the response."""
@classmethod
def from_response_schemas(
cls,
response_schemas: list[ResponseSchema],
) -> StructuredOutputParser:
"""Create a StructuredOutputParser from a list of ResponseSchema.
Args:
response_schemas: The schemas for the response.
Returns:
An instance of StructuredOutputParser.
"""
return cls(response_schemas=response_schemas)
def get_format_instructions(
self,
only_json: bool = False, # noqa: FBT001,FBT002
) -> str:
"""Get format instructions for the output parser.
Example:
```python
from langchain_classic.output_parsers.structured import (
StructuredOutputParser, ResponseSchema
)
response_schemas = [
ResponseSchema(
name="foo",
description="a list of strings",
type="List[string]"
),
ResponseSchema(
name="bar",
description="a string",
type="string"
),
]
parser = StructuredOutputParser.from_response_schemas(response_schemas)
print(parser.get_format_instructions()) # noqa: T201
output:
# The output should be a Markdown code snippet formatted in the following
# schema, including the leading and trailing "```json" and "```":
#
# ```json
# {
# "foo": List[string] // a list of strings
# "bar": string // a string
# }
# ```
Args:
only_json: If `True`, only the json in the Markdown code snippet
will be returned, without the introducing text.
"""
schema_str = "\n".join(
[_get_sub_string(schema) for schema in self.response_schemas],
)
if only_json:
return STRUCTURED_FORMAT_SIMPLE_INSTRUCTIONS.format(format=schema_str)
return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_str)
@override
def parse(self, text: str) -> dict[str, Any]:
expected_keys = [rs.name for rs in self.response_schemas]
return parse_and_check_json_markdown(text, expected_keys)
@property
def _type(self) -> str:
return "structured"
| StructuredOutputParser |
python | getsentry__sentry | tests/sentry/workflow_engine/migrations/test_0099_backfill_metric_issue_detectorgroup.py | {
"start": 414,
"end": 3663
} | class ____(TestMigrations, OccurrenceTestMixin):
migrate_from = "0098_detectorgroup_detector_set_null"
migrate_to = "0099_backfill_metric_issue_detectorgroup"
app = "workflow_engine"
def setup_initial_state(self) -> None:
self.detector = Detector.objects.create(
project=self.project,
name="Test Detector",
type=MetricIssue.slug,
config={"detection_type": AlertRuleDetectionType.STATIC.value},
)
occurrence_data = self.build_occurrence_data(
event_id=self.event.event_id,
project_id=self.project.id,
fingerprint=[f"detector-{self.detector.id}"],
evidence_data={"detector_id": self.detector.id},
type=MetricIssue.type_id,
)
self.occurrence, group_info = save_issue_occurrence(occurrence_data, self.event)
assert group_info is not None
self.metric_issue = group_info.group
deleted_detector = Detector.objects.create(
project=self.project,
name="Test Detector 2",
type=MetricIssue.slug,
config={"detection_type": AlertRuleDetectionType.STATIC.value},
)
event = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": before_now(seconds=1).isoformat(),
},
project_id=self.project.id,
)
occurrence_data = self.build_occurrence_data(
event_id=event.event_id,
project_id=self.project.id,
fingerprint=[f"detector-{deleted_detector.id}"],
evidence_data={"detector_id": deleted_detector.id},
type=MetricIssue.type_id,
)
_, group_info = save_issue_occurrence(occurrence_data, event)
assert group_info is not None
self.metric_issue_deleted_detector = group_info.group
deleted_detector.delete()
self.metric_issue_no_occurrence = self.create_group(
project=self.project, type=MetricIssue.type_id
)
self.metric_issue_existing_detectorgroup = self.create_group(
project=self.project, type=MetricIssue.type_id
)
self.detector2 = Detector.objects.create(
project=self.project,
name="Test Detector 2",
type=MetricIssue.slug,
config={"detection_type": AlertRuleDetectionType.STATIC.value},
)
DetectorGroup.objects.all().delete()
DetectorGroup.objects.create(
group=self.metric_issue_existing_detectorgroup,
detector=self.detector2,
)
def test_migration(self) -> None:
assert DetectorGroup.objects.filter(
group=self.metric_issue, detector=self.detector
).exists()
assert DetectorGroup.objects.filter(
group=self.metric_issue_deleted_detector, detector=None
).exists()
assert DetectorGroup.objects.filter(
group=self.metric_issue_no_occurrence,
detector=None,
).exists()
assert DetectorGroup.objects.filter(
group=self.metric_issue_existing_detectorgroup, detector=self.detector2
).exists()
| BackfillMetricIssueDetectorGroupTest |
python | jazzband__django-model-utils | tests/test_choices.py | {
"start": 2686,
"end": 6010
} | class ____(TestCase, ChoicesTestsMixin[str]):
def setUp(self) -> None:
self.STATUS = Choices(
('DRAFT', 'is draft'),
('PUBLISHED', 'is published'),
'DELETED',
)
def test_iteration(self) -> None:
self.assertEqual(tuple(self.STATUS), (
('DRAFT', 'is draft'),
('PUBLISHED', 'is published'),
('DELETED', 'DELETED'),
))
def test_reversed(self) -> None:
self.assertEqual(tuple(reversed(self.STATUS)), (
('DELETED', 'DELETED'),
('PUBLISHED', 'is published'),
('DRAFT', 'is draft'),
))
def test_indexing(self) -> None:
self.assertEqual(self.STATUS['PUBLISHED'], 'is published')
def test_default(self) -> None:
self.assertEqual(self.STATUS.DELETED, 'DELETED')
def test_provided(self) -> None:
self.assertEqual(self.STATUS.DRAFT, 'DRAFT')
def test_len(self) -> None:
self.assertEqual(len(self.STATUS), 3)
def test_equality(self) -> None:
self.assertEqual(self.STATUS, Choices(
('DRAFT', 'is draft'),
('PUBLISHED', 'is published'),
'DELETED',
))
def test_inequality(self) -> None:
self.assertNotEqual(self.STATUS, [
('DRAFT', 'is draft'),
('PUBLISHED', 'is published'),
'DELETED'
])
self.assertNotEqual(self.STATUS, Choices('DRAFT'))
def test_repr(self) -> None:
self.assertEqual(repr(self.STATUS), "Choices" + repr((
('DRAFT', 'DRAFT', 'is draft'),
('PUBLISHED', 'PUBLISHED', 'is published'),
('DELETED', 'DELETED', 'DELETED'),
)))
def test_contains_value(self) -> None:
self.assertTrue('PUBLISHED' in self.STATUS)
self.assertTrue('DRAFT' in self.STATUS)
# This should be True, because both the display value
# and the internal representation are both DELETED.
self.assertTrue('DELETED' in self.STATUS)
def test_doesnt_contain_value(self) -> None:
self.assertFalse('UNPUBLISHED' in self.STATUS)
def test_doesnt_contain_display_value(self) -> None:
self.assertFalse('is draft' in self.STATUS)
def test_composability(self) -> None:
self.assertEqual(
Choices(('DRAFT', 'is draft',)) + Choices(('PUBLISHED', 'is published'), 'DELETED'),
self.STATUS
)
self.assertEqual(
(('DRAFT', 'is draft',),) + Choices(('PUBLISHED', 'is published'), 'DELETED'),
self.STATUS
)
self.assertEqual(
Choices(('DRAFT', 'is draft',)) + (('PUBLISHED', 'is published'), 'DELETED'),
self.STATUS
)
def test_option_groups(self) -> None:
if TYPE_CHECKING:
c = Choices[int](
('group a', [(1, 'one'), (2, 'two')]),
('group b', ((3, 'three'),))
)
else:
c = Choices(
('group a', [(1, 'one'), (2, 'two')]),
['group b', ((3, 'three'),)]
)
self.assertEqual(
list(c),
[
('group a', [(1, 'one'), (2, 'two')]),
('group b', [(3, 'three')]),
],
)
| LabelChoicesTests |
python | python-poetry__poetry | src/poetry/inspection/lazy_wheel.py | {
"start": 1441,
"end": 1528
} | class ____(LazyWheelUnsupportedError):
"""Unsupported wheel."""
| UnsupportedWheelError |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0042_version_state.py | {
"start": 629,
"end": 1256
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0041_track_task_id"),
]
operations = [
migrations.AddField(
model_name="version",
name="state",
field=models.CharField(
blank=True,
choices=[("open", "Open"), ("closed", "Closed")],
help_text="State of the PR/MR associated to this version.",
max_length=20,
null=True,
verbose_name="State",
),
),
migrations.RunPython(forwards_func),
]
| Migration |
python | ray-project__ray | rllib/algorithms/dreamerv3/dreamerv3.py | {
"start": 20545,
"end": 33651
} | class ____(Algorithm):
"""Implementation of the model-based DreamerV3 RL algorithm described in [1]."""
# TODO (sven): Deprecate/do-over the Algorithm.compute_single_action() API.
@override(Algorithm)
def compute_single_action(self, *args, **kwargs):
raise NotImplementedError(
"DreamerV3 does not support the `compute_single_action()` API. Refer to the"
" README here (https://github.com/ray-project/ray/tree/master/rllib/"
"algorithms/dreamerv3) to find more information on how to run action "
"inference with this algorithm."
)
@classmethod
@override(Algorithm)
def get_default_config(cls) -> DreamerV3Config:
return DreamerV3Config()
@override(Algorithm)
def setup(self, config: AlgorithmConfig):
super().setup(config)
# Share RLModule between EnvRunner and single (local) Learner instance.
# To avoid possibly expensive weight synching step.
# if self.config.share_module_between_env_runner_and_learner:
# assert self.env_runner.module is None
# self.env_runner.module = self.learner_group._learner.module[
# DEFAULT_MODULE_ID
# ]
# Create a replay buffer for storing actual env samples.
self.replay_buffer = EpisodeReplayBuffer(
capacity=self.config.replay_buffer_config["capacity"],
batch_size_B=self.config.batch_size_B,
batch_length_T=self.config.batch_length_T,
)
@override(Algorithm)
def training_step(self) -> None:
# Push enough samples into buffer initially before we start training.
if self.training_iteration == 0:
logger.info(
"Filling replay buffer so it contains at least "
f"{self.config.batch_size_B * self.config.batch_length_T} timesteps "
"(required for a single train batch)."
)
# Have we sampled yet in this `training_step()` call?
have_sampled = False
with self.metrics.log_time((TIMERS, SAMPLE_TIMER)):
# Continue sampling from the actual environment (and add collected samples
# to our replay buffer) as long as we:
while (
# a) Don't have at least batch_size_B x batch_length_T timesteps stored
# in the buffer. This is the minimum needed to train.
self.replay_buffer.get_num_timesteps()
< (self.config.batch_size_B * self.config.batch_length_T)
# b) The computed `training_ratio` is >= the configured (desired)
# training ratio (meaning we should continue sampling).
or self.training_ratio >= self.config.training_ratio
# c) we have not sampled at all yet in this `training_step()` call.
or not have_sampled
):
# Sample using the env runner's module.
episodes, env_runner_results = synchronous_parallel_sample(
worker_set=self.env_runner_group,
max_agent_steps=(
self.config.rollout_fragment_length
* self.config.num_envs_per_env_runner
),
sample_timeout_s=self.config.sample_timeout_s,
_uses_new_env_runners=True,
_return_metrics=True,
)
self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS)
# Add ongoing and finished episodes into buffer. The buffer will
# automatically take care of properly concatenating (by episode IDs)
# the different chunks of the same episodes, even if they come in via
# separate `add()` calls.
self.replay_buffer.add(episodes=episodes)
have_sampled = True
# We took B x T env steps.
env_steps_last_regular_sample = sum(len(eps) for eps in episodes)
total_sampled = env_steps_last_regular_sample
# If we have never sampled before (just started the algo and not
# recovered from a checkpoint), sample B random actions first.
if (
self.metrics.peek(
(ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME),
default=0,
)
== 0
):
_episodes, _env_runner_results = synchronous_parallel_sample(
worker_set=self.env_runner_group,
max_agent_steps=(
self.config.batch_size_B * self.config.batch_length_T
- env_steps_last_regular_sample
),
sample_timeout_s=self.config.sample_timeout_s,
random_actions=True,
_uses_new_env_runners=True,
_return_metrics=True,
)
self.metrics.aggregate(_env_runner_results, key=ENV_RUNNER_RESULTS)
self.replay_buffer.add(episodes=_episodes)
total_sampled += sum(len(eps) for eps in _episodes)
# Summarize environment interaction and buffer data.
report_sampling_and_replay_buffer(
metrics=self.metrics, replay_buffer=self.replay_buffer
)
# Get the replay buffer metrics.
replay_buffer_results = self.local_replay_buffer.get_metrics()
self.metrics.aggregate([replay_buffer_results], key=REPLAY_BUFFER_RESULTS)
# Use self.spaces for the environment spaces of the env-runners
single_observation_space, single_action_space = self.spaces[
INPUT_ENV_SINGLE_SPACES
]
# Continue sampling batch_size_B x batch_length_T sized batches from the buffer
# and using these to update our models (`LearnerGroup.update()`)
# until the computed `training_ratio` is larger than the configured one, meaning
# we should go back and collect more samples again from the actual environment.
# However, when calculating the `training_ratio` here, we use only the
# trained steps in this very `training_step()` call over the most recent sample
# amount (`env_steps_last_regular_sample`), not the global values. This is to
# avoid a heavy overtraining at the very beginning when we have just pre-filled
# the buffer with the minimum amount of samples.
replayed_steps_this_iter = sub_iter = 0
while (
replayed_steps_this_iter / env_steps_last_regular_sample
) < self.config.training_ratio:
# Time individual batch updates.
with self.metrics.log_time((TIMERS, LEARN_ON_BATCH_TIMER)):
logger.info(f"\tSub-iteration {self.training_iteration}/{sub_iter})")
# Draw a new sample from the replay buffer.
sample = self.replay_buffer.sample(
batch_size_B=self.config.batch_size_B,
batch_length_T=self.config.batch_length_T,
)
replayed_steps = self.config.batch_size_B * self.config.batch_length_T
replayed_steps_this_iter += replayed_steps
if isinstance(single_action_space, gym.spaces.Discrete):
sample["actions_ints"] = sample[Columns.ACTIONS]
sample[Columns.ACTIONS] = one_hot(
sample["actions_ints"],
depth=single_action_space.n,
)
# Perform the actual update via our learner group.
learner_results = self.learner_group.update(
batch=SampleBatch(sample).as_multi_agent(),
# TODO(sven): Maybe we should do this broadcase of global timesteps
# at the end, like for EnvRunner global env step counts. Maybe when
# we request the state from the Learners, we can - at the same
# time - send the current globally summed/reduced-timesteps.
timesteps={
NUM_ENV_STEPS_SAMPLED_LIFETIME: self.metrics.peek(
(ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME),
default=0,
)
},
)
self.metrics.aggregate(learner_results, key=LEARNER_RESULTS)
sub_iter += 1
self.metrics.log_value(NUM_GRAD_UPDATES_LIFETIME, 1, reduce="sum")
# Log videos showing how the decoder produces observation predictions
# from the posterior states.
# Only every n iterations and only for the first sampled batch row
# (videos are `config.batch_length_T` frames long).
report_predicted_vs_sampled_obs(
# TODO (sven): DreamerV3 is single-agent only.
metrics=self.metrics,
sample=sample,
batch_size_B=self.config.batch_size_B,
batch_length_T=self.config.batch_length_T,
symlog_obs=do_symlog_obs(
single_observation_space,
self.config.symlog_obs,
),
do_report=(
self.config.report_images_and_videos
and self.training_iteration % 100 == 0
),
)
# Log videos showing some of the dreamed trajectories and compare them with the
# actual trajectories from the train batch.
# Only every n iterations and only for the first sampled batch row AND first ts.
# (videos are `config.horizon_H` frames long originating from the observation
# at B=0 and T=0 in the train batch).
report_dreamed_eval_trajectory_vs_samples(
metrics=self.metrics,
sample=sample,
burn_in_T=0,
dreamed_T=self.config.horizon_H + 1,
dreamer_model=self.env_runner.module.dreamer_model,
symlog_obs=do_symlog_obs(
single_observation_space,
self.config.symlog_obs,
),
do_report=(
self.config.report_dream_data and self.training_iteration % 100 == 0
),
framework=self.config.framework_str,
)
# Update weights - after learning on the LearnerGroup - on all EnvRunner
# workers.
with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)):
# Only necessary if RLModule is not shared between (local) EnvRunner and
# (local) Learner.
# if not self.config.share_module_between_env_runner_and_learner:
self.metrics.log_value(NUM_SYNCH_WORKER_WEIGHTS, 1, reduce="sum")
self.env_runner_group.sync_weights(
from_worker_or_learner_group=self.learner_group,
inference_only=True,
)
# Add train results and the actual training ratio to stats. The latter should
# be close to the configured `training_ratio`.
self.metrics.log_value("actual_training_ratio", self.training_ratio, window=1)
@property
def training_ratio(self) -> float:
"""Returns the actual training ratio of this Algorithm (not the configured one).
The training ratio is copmuted by dividing the total number of steps
trained thus far (replayed from the buffer) over the total number of actual
env steps taken thus far.
"""
eps = 0.0001
return self.metrics.peek(NUM_ENV_STEPS_TRAINED_LIFETIME, default=0) / (
(
self.metrics.peek(
(ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME),
default=eps,
)
or eps
)
)
# TODO (sven): Remove this once DreamerV3 is on the new SingleAgentEnvRunner.
@PublicAPI
def __setstate__(self, state) -> None:
"""Sts the algorithm to the provided state
Args:
state: The state dictionary to restore this `DreamerV3` instance to.
`state` may have been returned by a call to an `Algorithm`'s
`__getstate__()` method.
"""
# Call the `Algorithm`'s `__setstate__()` method.
super().__setstate__(state=state)
# Assign the module to the local `EnvRunner` if sharing is enabled.
# Note, in `Learner.restore_from_path()` the module is first deleted
# and then a new one is built - therefore the worker has no
# longer a copy of the learner.
if self.config.share_module_between_env_runner_and_learner:
assert id(self.env_runner.module) != id(
self.learner_group._learner.module[DEFAULT_MODULE_ID]
)
self.env_runner.module = self.learner_group._learner.module[
DEFAULT_MODULE_ID
]
| DreamerV3 |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 150469,
"end": 153947
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Qwen3OmniMoeCode2WavConfig, layer_idx):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
self.rotary_fn = apply_rotary_pos_emb
self.q_norm = nn.Identity()
self.k_norm = nn.Identity()
self.sliding_window = config.sliding_window
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
sliding_window=self.sliding_window, # diff with Llama
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| Qwen3OmniMoeCode2WavAttention |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/test_dependency/package.py | {
"start": 216,
"end": 492
} | class ____(Package):
"""Represent a dependency that is pulled-in to allow testing other
packages.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/tdep-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
| TestDependency |
python | doocs__leetcode | solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/Solution.py | {
"start": 0,
"end": 594
} | class ____:
def maxPalindromes(self, s: str, k: int) -> int:
@cache
def dfs(i):
if i >= n:
return 0
ans = dfs(i + 1)
for j in range(i + k - 1, n):
if dp[i][j]:
ans = max(ans, 1 + dfs(j + 1))
return ans
n = len(s)
dp = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = s[i] == s[j] and dp[i + 1][j - 1]
ans = dfs(0)
dfs.cache_clear()
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 278693,
"end": 279334
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of RemoveReaction"""
__schema__ = github_schema
__field_names__ = ("subject_id", "content", "client_mutation_id")
subject_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subjectId")
"""The Node ID of the subject to modify."""
content = sgqlc.types.Field(sgqlc.types.non_null(ReactionContent), graphql_name="content")
"""The name of the emoji reaction to remove."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| RemoveReactionInput |
python | joke2k__faker | faker/providers/person/or_IN/__init__.py | {
"start": 44,
"end": 21830
} | class ____(PersonProvider):
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{first_name_unisex}} {{last_name}}",
"{{prefix_female}} {{first_name_unisex}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
)
formats_male = (
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{middle_name}} {{last_name}}",
"{{first_name_unisex}} {{middle_name}} {{last_name}}",
"{{prefix_male}} {{first_name_male}} {{last_name}}",
)
formats = formats_female + formats_male
# All the names are extracted from Odia Wikipedia by Soumendra Kumar Sahoo.
# 1. https://or.wikipedia.org/s/1duk and
# 2. https://or.wikipedia.org/s/3vz
first_names_female = (
"ଅଜୟନ୍ତୀ",
"ଅଞ୍ଜଳି",
"ଅନିଶା",
"ଅନୀତା",
"ଅନୁ",
"ଅନୁପ୍ରିୟା",
"ଅନୁଭା",
"ଅପରାଜିତା",
"ଅମିତା",
"ଅମିୟବାଳା",
"ଅର୍ଚ୍ଚିତା",
"ଅର୍ପିତା",
"ଅସୀମା",
"ଆଞ୍ଚଲ",
"ଆନିଷା",
"ଆମେଲି",
"ଇନ୍ଦୁ",
"ଇନ୍ଦୁରାଣୀ",
"ଇନ୍ଦ୍ରାଣୀ",
"ଇରାନି",
"ଇଲା",
"ଉଷସୀ",
"ଉଷା",
"ଏଲିନା",
"କନକଲତା",
"କବିତା",
"କମଳା",
"କଲ୍ୟାଣୀ",
"କାଜଲ",
"କୁମୁଦ",
"କୁସୁମ",
"କୋଏଲ",
"ଗାର୍ଗୀ",
"ଗାୟତ୍ରୀବାଳା",
"ଗୀତା",
"ଗୁନ୍ ଗୁନ୍",
"ଗୌରୀ",
"ଗ୍ଲୋରିଆ",
"ଚନ୍ଦ୍ରମା",
"ଛବି",
"ଜିନା",
"ଜ୍ୟୋତିର୍ମୟୀ",
"ଜ୍ୟୋତ୍ସ୍ନା",
"ଜୟନ୍ତୀ",
"ଝରଣା",
"ଝିଲିକ୍",
"ଟୁକୁନି",
"ତନ୍ଦ୍ରା",
"ତମନ୍ନା",
"ତୃପ୍ତି",
"ତ୍ରିପୁରା",
"ଦୀପା",
"ଦୀପ୍ତିରେଖା",
"ଦେବଯାନୀ",
"ଦେବୀ",
"ନନ୍ଦିତା",
"ନନ୍ଦିନୀ",
"ନମିତା",
"ନମ୍ରତା",
"ନଳିନୀ",
"ନାଜିଆ",
"ନିକିତା",
"ନିବେଦିତା",
"ନିର୍ମଳା",
"ନିହାରିକା",
"ନୀତୁ",
"ନୈନା",
"ପଦ୍ମିନୀ",
"ପାର୍ବତୀ",
"ପିଙ୍କି",
"ପୁନମ",
"ପୁପୁଲ",
"ପୁଷ୍ପା",
"ପ୍ରକୃତି",
"ପ୍ରତିଜ୍ଞା",
"ପ୍ରମିଳା",
"ପ୍ରିୟଙ୍କା",
"ପ୍ରିୟମ୍ବଦା",
"ପ୍ରିୟା",
"ପ୍ରେମଲତା",
"ଫୁଲମଣି",
"ବନଜା",
"ବନ୍ଦିତା",
"ବବ୍ଲି",
"ବର୍ଣ୍ଣାଳୀ",
"ବର୍ଷା",
"ବାସନ୍ତି",
"ବାସନ୍ତୀ",
"ବିଜୟଲକ୍ଷ୍ମୀ",
"ବିଜୟିନୀ",
"ବିଦୁସ୍ମିତା",
"ବିନୋଦିନୀ",
"ବିରଜା",
"ବିଷ୍ଣୁପ୍ରିୟା",
"ବୀଣା",
"ବୈଶାଳୀ",
"ଭଗବତୀ",
"ଭବାନୀ",
"ଭାନୁମତୀ",
"ଭାସ୍ୱତୀ",
"ଭୂମିକା",
"ମଙ୍ଗଳା",
"ମଞ୍ଜୁଲତା",
"ମଞ୍ଜୁଳା",
"ମଣିମାଳା",
"ମନ୍ଦାକିନୀ",
"ମମତା",
"ମହାଶ୍ୱେତା",
"ମାଧୁରୀ",
"ମାମିନା",
"ମିନତି",
"ମିନାକ୍ଷୀ",
"ମେଘନା",
"ମେଘା",
"ଯଶୋଦା",
"ରଚନା",
"ରଜନୀ",
"ରଞ୍ଜିତା",
"ରତ୍ନପ୍ରଭା",
"ରଶ୍ମୀରେଖା",
"ରାକ୍ଷୀ",
"ରାଜଶ୍ରୀ",
"ରାଧାରାଣୀ",
"ରାଲି",
"ରାସମଞ୍ଜରୀ",
"ରାସେଶ୍ୱରୀ",
"ରିନା",
"ରିୟା",
"ରୀତା",
"ରୀତାରାଣୀ",
"ରୁକ୍ମଣୀ",
"ରୁନୁ",
"ରୋଜା",
"ରୋଷନୀ",
"ରୋସନାରା",
"ଲକ୍ଷ୍ମୀ",
"ଲକ୍ଷ୍ମୀପ୍ରିୟା",
"ଲତିକା",
"ଲିପି",
"ଲିପିକା",
"ଲିପ୍ସା",
"ଲୀଳା",
"ଲେଖା",
"ଲେସ୍ଲି",
"ଶିବାନୀ",
"ଶୀତଲ",
"ଶୁଭଶ୍ରୀ",
"ଶେଫାଳୀ",
"ଶୈରିନ୍ଦ୍ରୀ",
"ଶ୍ରୀମତି",
"ଶ୍ରୀମତୀ",
"ସଂଘମିତ୍ରା",
"ସଞ୍ଚିତା",
"ସନ୍ମିରା",
"ସରସ୍ୱତୀ",
"ସସ୍ମିତା",
"ସାବିତ୍ରୀ",
"ସିପ୍ରା",
"ସୀମାରାଣୀ",
"ସୁଚିତ୍ରା",
"ସୁଜାତା",
"ସୁନନ୍ଦା",
"ସୁପ୍ରିୟା",
"ସୁମନୀ",
"ସୁରମା",
"ସୋନିକା",
"ସୋଫିଆ",
"ସୌଦାମିନୀ",
"ସୌମ୍ୟା",
"ସ୍ନିଗ୍ଧା",
"ସ୍ନେହାଙ୍ଗିନୀ",
"ସ୍ମିତା",
"ସ୍ୱାଗତିକା",
)
first_names_unisex = (
"ଅଶ୍ୱିନୀ",
"ଅଶ୍ୱିନୀ",
"କବି",
"ଗୀତା",
"ଜ୍ୟୋତି",
"ଦୁର୍ଗା",
"ଦେବୀ",
"ପଦ୍ମ",
"ପୁପୁଲ",
"ପ୍ରିୟଦର୍ଶୀ",
"ମକର",
"ମଙ୍ଗଳା",
"ମୌସଦୀ",
"ରତି",
"ରଶ୍ମି",
"ଶାନ୍ତି",
"ସିମନ୍",
"ସୁଧାଂଶୁମାଳିନୀ",
"ସୁମନ",
"ସ୍ନିତି",
)
first_names_male = (
"ଅଂଶୁମାନ",
"ଅକ୍ଷୟ",
"ଅଖିଳ",
"ଅଗସ୍ତି",
"ଅଙ୍ଗଦ",
"ଅଚ୍ୟୁତାନନ୍ଦ",
"ଅଜିତ",
"ଅଜୟ",
"ଅତନୁ",
"ଅଦ୍ୱୈତ",
"ଅଧିରାଜ",
"ଅନନ୍ତ",
"ଅନାଦି",
"ଅନାଦୀ",
"ଅନିରୁଦ୍ଧ",
"ଅନିଲ",
"ଅନୀଲ",
"ଅନୁଭବ",
"ଅନ୍ତର୍ଯ୍ୟାମୀ",
"ଅପୂର୍ବ",
"ଅଭିନ୍ନ",
"ଅଭିମନ୍ୟୁ",
"ଅଭିରାମ",
"ଅଭିଷେକ",
"ଅଭୟ",
"ଅମର",
"ଅମରନାଥ",
"ଅମରେନ୍ଦ୍ର",
"ଅମିନୂଲ",
"ଅମ୍ଳାନ",
"ଅରକ୍ଷିତ",
"ଅରବିନ୍ଦ",
"ଅରିନ୍ଦମ",
"ଅରୁଣ",
"ଅର୍କ",
"ଅର୍ଜୁନ",
"ଅଲେଖ",
"ଅଶୋକ",
"ଅଶ୍ରୁମୋଚନ",
"ଅସୀତ",
"ଆକାଶ",
"ଆକୁଳାନନ୍ଦ",
"ଆଦିତ୍ୟ",
"ଆନନ୍ଦ",
"ଆପଲସ୍ୱାମୀ",
"ଆରତି",
"ଆର୍ଯ୍ୟନ",
"ଆଲୋକ",
"ଆଶ୍ରିତ",
"ଆସଫ",
"ଇତିସ",
"ଇନ୍ଦ୍ରମଣି",
"ଇରାଶିଷ",
"ଇଶ୍ୱର",
"ଉତ୍କଳ",
"ଉତ୍ତମ",
"ଉତ୍ସବ",
"ଉଧାର",
"ଉପେନ୍ଦ୍ର",
"ଉପେନ୍ଦ୍ରନାଥ",
"ଉମାକାନ୍ତ",
"ଉମାବଲ୍ଲଭ",
"ଉମାଶଙ୍କର",
"ଓଡ଼ିଆ",
"ଓମପ୍ରକାଶ",
"ଓମ୍",
"କନକବର୍ଦ୍ଧନ",
"କପିଳ",
"କମଳାକାନ୍ତ",
"କରୁଣାକର",
"କରେନ୍ଦ୍ର",
"କଳିଙ୍ଗ",
"କଳ୍ପତରୁ",
"କହ୍ନେଇ",
"କାଙ୍ଗାଳି",
"କାଙ୍ଗୋଇ",
"କାର୍ତ୍ତିକ",
"କାର୍ତ୍ତିକେଶ୍ୱର",
"କାଳନ୍ଦୀ",
"କାଳିଆ",
"କାଳୁଖଣ୍ଡାୟତ",
"କାଶୀନାଥ",
"କାହ୍ନୁ",
"କାହ୍ନୁରାମ",
"କିରଣ",
"କିଶୋରଚନ୍ଦ୍ର",
"କିଶୋରୀମଣି",
"କୁଞ୍ଜବିହାରୀ",
"କୁଣାଳ",
"କୁନା",
"କୁମୁଦ",
"କୁଳମଣି",
"କୃଷ୍ଣ",
"କୃଷ୍ଣଚନ୍ଦ୍ର",
"କେଦାର",
"କେଦାରନାଥ",
"କେଶବ",
"କୈଳାଶ",
"କୈଳାସ",
"କ୍ଷୀରୋଦ",
"କ୍ଷେତ୍ର",
"ଖଗେଶ୍ୱର",
"ଖାରବେଳ",
"ଗଙ୍ଗାଧର",
"ଗଣେଶରାମ",
"ଗଣେଶ୍ୱର",
"ଗଦାଧର",
"ଗିରିଜା",
"ଗିରିଶ",
"ଗିରୀଶ",
"ଗୁରୁ",
"ଗୁରୁକୃଷ୍ଣ",
"ଗୁରୁଚରଣ",
"ଗୈାତମ",
"ଗୋକୁଳାନନ୍ଦ",
"ଗୋପନାରାୟଣ",
"ଗୋପାଳ",
"ଗୋପାଳବଲ୍ଲଭ",
"ଗୋପୀନାଥ",
"ଗୋବିନ୍ଦ",
"ଗୋଲକ",
"ଗୌତମ",
"ଗୌର",
"ଗୌରହରି",
"ଘଣ୍ଟେଶ୍ୱର",
"ଘନଶ୍ୟାମ",
"ଘାସିରାମ",
"ଚକ୍ରଧର",
"ଚକ୍ରମଣି",
"ଚନ୍ଦନ",
"ଚନ୍ଦ୍ରମଣି",
"ଚନ୍ଦ୍ରଶେଖର",
"ଚନ୍ଦ୍ରସେନ",
"ଚିତରଂଜନ",
"ଚିତ୍ତରଞ୍ଜନ",
"ଚିନ୍ତାମଣି",
"ଚିନ୍ମୟ",
"ଚିରଂଜୀବ",
"ଚୈତନ୍ୟ",
"ଛତିଶ",
"ଛୋଟରାୟ",
"ଜଗତେଶ୍ୱର",
"ଜଗଦାନନ୍ଦ",
"ଜଗଦିଶ",
"ଜଗନ୍ନାଥ",
"ଜଗବନ୍ଧୁ",
"ଜନାର୍ଦନ",
"ଜର୍ଜ",
"ଜଲାଲ",
"ଜିତୁ",
"ଜୀବନ",
"ଜୀବନାନନ୍ଦ",
"ଜ୍ଞାନ",
"ଜ୍ୟୋତି",
"ଜ୍ୟୋତିନ୍ଦ୍ର",
"ଜ୍ୟୋତିପ୍ରକାଶ",
"ଜ୍ୟୋତିରିନ୍ଦ୍ର",
"ଜୟକୃଷ୍ଣ",
"ଜୟଦେବ",
"ଜୟନାରାୟଣ",
"ଜୟନ୍ତ",
"ଜୟରାମ",
"ଜୟୀରାମ",
"ଝିନ୍ନ",
"ତନ୍ମୟ",
"ତପନ",
"ତପୁ",
"ତାନସେନ",
"ତାରାପ୍ରସାଦ",
"ତୁଷାରକାନ୍ତି",
"ତ୍ରିନାଥ",
"ତ୍ରିଲୋଚନ",
"ଦାମୋଦର",
"ଦାଶରଥୀ",
"ଦିଗମ୍ବର",
"ଦିନେଶ",
"ଦିବାକରନାଥ",
"ଦିବ୍ୟଶଙ୍କର",
"ଦିଲୀପ",
"ଦିଲ୍ଲୀପ",
"ଦୀନବନ୍ଧୁ",
"ଦୀପକ",
"ଦୀପ୍ତିରଞ୍ଜନ",
"ଦୁଃଖୀରାମ",
"ଦୁଃଶାସନ",
"ଦୁତିଅ",
"ଦୁର୍ଯ୍ୟୋଧନ",
"ଦୁର୍ଲଭ",
"ଦୁଷ୍ମନ୍ତ",
"ଦେବଦାସ",
"ଦେବନାରାୟଣ",
"ଦେବରାଜ",
"ଦେବାଶିଷ",
"ଦେବୀରଞ୍ଜନ",
"ଦେବୁ",
"ଦେବେନ",
"ଦେବେନ୍ଦ୍ର",
"ଦେବେନ୍ଦ୍ରନାଥ",
"ଦେବେଶ",
"ଦୈତାରି",
"ଦୈତାରୀ",
"ଦୋଳଗୋବିନ୍ଦ",
"ଧନଞ୍ଜୟ",
"ଧନୁର୍ଜୟ",
"ଧନେଶ୍ୱର",
"ଧରଣୀଧର",
"ଧର୍ମାନନ୍ଦ",
"ଧାମରାଜ",
"ଧୀର",
"ଧୃବ",
"ଧ୍ରୁବ",
"ନଗେନ",
"ନଗେନ୍ଦ୍ର",
"ନଟରାଜ",
"ନନ୍ଦକିଶୋର",
"ନବ",
"ନବକିଶୋର",
"ନବଘନ",
"ନବଜ୍ୟୋତି",
"ନବୀନ",
"ନରସିଂ",
"ନରସିଂହ",
"ନରେନ",
"ନରେନ୍ଦ୍ର",
"ନାଉରୀ",
"ନିଜାମ",
"ନିତାଇ",
"ନିତ୍ୟାନନ୍ଦ",
"ନିପନ୍",
"ନିରଞ୍ଜନ",
"ନିହାର",
"ନୀରଦ",
"ନୀଳମଣୀ",
"ନୀଳମାଧବ",
"ନୀଳାଦ୍ରି",
"ନୀଳାମ୍ବର",
"ନୃସିଂହ",
"ନେତ୍ରାନନ୍ଦ",
"ନୟନ",
"ପଞ୍ଚାନନ",
"ପଠାଣି",
"ପଦ",
"ପଦ୍ମଚରଣ",
"ପଦ୍ମନ",
"ପଦ୍ମନାଭ",
"ପଦ୍ମଲୋଚନ",
"ପପୁ",
"ପବିତ୍ର",
"ପରମା",
"ପରମାନନ୍ଦ",
"ପରମେଶ୍ୱର",
"ପର୍ଶୁରାମ",
"ପାଟ୍ଟ",
"ପାଡୁ",
"ପାଣୁ",
"ପିଣ୍ଟୁ",
"ପିଣ୍ଡାକୀ",
"ପୀତାମ୍ବର",
"ପୁଣ୍ୟପ୍ରଭା",
"ପୁପିନ୍ଦର",
"ପୁରୁଷୋତ୍ତମ",
"ପୂର୍ଣଚନ୍ଦ୍ର",
"ପୂର୍ଣ୍ଣଚନ୍ଦ୍ର",
"ପୂର୍ଣ୍ଣବାସୀ",
"ପୂର୍ଣ୍ଣାନନ୍ଦ",
"ପୃଥ୍ୱୀରାଜ",
"ପ୍ରଜ୍ଞାନ",
"ପ୍ରଣବ",
"ପ୍ରଦିପ୍ତ",
"ପ୍ରଦୀପ୍ତ",
"ପ୍ରଦ୍ୟୁମ୍ନ",
"ପ୍ରଫୁଲ",
"ପ୍ରଫୁଲ୍ଲ",
"ପ୍ରଫେସର",
"ପ୍ରବୀଣ",
"ପ୍ରଭାକର",
"ପ୍ରଭାତ",
"ପ୍ରଭାସ",
"ପ୍ରଭୁ",
"ପ୍ରମୋଦ",
"ପ୍ରଶାନ୍ତ",
"ପ୍ରହଲ୍ଲାଦ",
"ପ୍ରାଣ",
"ପ୍ରିୟନାଥ",
"ପ୍ରିୟା",
"ପ୍ରୀତମ୍",
"ପ୍ରୀତିରଞ୍ଜନ",
"ପ୍ରେମାନନ୍ଦ",
"ପ୍ୟାରୀମୋହନ",
"ଫକୀର",
"ବଂଶୀଧର",
"ବଟକୃଷ୍ଣ",
"ବଦ୍ରି",
"ବଦ୍ରିନାରାୟଣ",
"ବନବାସୀ",
"ବନମାଳି",
"ବନମାଳୀ",
"ବବି",
"ବରେନ୍ଦ୍ର",
"ବଳଭଦ୍ର",
"ବଳରାମ",
"ବସେନ",
"ବାଇକୋଳି",
"ବାଇଧର",
"ବାଙ୍କ",
"ବାବୁ",
"ବାବୁଶାନ୍",
"ବାଳକୃଷ୍ଣ",
"ବାଳକ୍ରିଷ୍ଣ",
"ବାଳଗୋପାଳ",
"ବାସୁଦେବ",
"ବିକଳାନନ୍ଦ",
"ବିକ୍ରମ",
"ବିଜୁ",
"ବିଜୟ",
"ବିଜୟରଞ୍ଜନ",
"ବିଜୟଶ୍ରୀ",
"ବିଜୟାନନ୍ଦ",
"ବିଧୁ",
"ବିଧୁଭୂଷଣ",
"ବିନୋଦ",
"ବିପିନ",
"ବିପ୍ଳବ",
"ବିଭୁତି",
"ବିଭୁଦତ୍ତ",
"ବିଭୁଧେନ୍ଦ୍ର",
"ବିଭୂତି",
"ବିଭୂତିଭୂଷଣ",
"ବିମଳ",
"ବିରେନ",
"ବିରେନ୍",
"ବିଶ୍ୱଜିତ",
"ବିଶ୍ୱନାଥ",
"ବିଶ୍ୱଭୂଷଣ",
"ବିଶ୍ୱରଞ୍ଜନ",
"ବିଷ୍ଣୁ",
"ବିଷ୍ଣୁବ୍ରତ",
"ବିସ୍ମୟ",
"ବୀର",
"ବୀରକିଶୋର",
"ବୀରଭଦ୍ର",
"ବୀରେନ",
"ବୀରେନ୍ଦ୍ରନାଥ",
"ବୁଦ୍ଧାଦିତ୍ୟ",
"ବୁଧନ",
"ବୃନ୍ଦାବନ",
"ବେଣୀମାଧବ",
"ବେଣୁଧର",
"ବେଦ",
"ବେଦବ୍ୟାସ",
"ବେଦାଙ୍ଗଦାସ",
"ବୈଦ୍ୟନାଥ",
"ବୈରାଗୀ",
"ବୈଷ୍ଣବ",
"ବୋନାଜ",
"ବ୍ରଜ",
"ବ୍ରହ୍ମାନନ୍ଦ",
"ବ୍ୟୋମକେଶ",
"ଭଗୀରଥ",
"ଭଜମନ",
"ଭବାନୀଶଙ୍କର",
"ଭବେନ୍ଦ୍ରନାଥ",
"ଭାଇଗା",
"ଭାଗବତ",
"ଭାଗିରଥୀ",
"ଭାଗୀରଥି",
"ଭାଦବ",
"ଭାନୁଚରଣ",
"ଭାବଗ୍ରାହୀ",
"ଭାସ୍କର",
"ଭୀମ",
"ଭୁବନାନନ୍ଦ",
"ଭୁବନେଶ୍ୱର",
"ଭୂଜବଳ",
"ଭୂପିନ୍ଦର",
"ଭୂବନାନନ୍ଦ",
"ଭୋକାଲି",
"ମଙ୍ଗରାଜ",
"ମଙ୍ଗଳ",
"ମଦନ",
"ମଦନମୋହନ",
"ମଧୁସୂଦନ",
"ମନମୋହନ",
"ମନୋଜ",
"ମନୋରଞ୍ଜନ",
"ମନୋହର",
"ମନ୍ମଥ",
"ମହମ୍ମଦ",
"ମହାଦେବ",
"ମହୀଧର",
"ମହେନ୍ଦ୍ର",
"ମହେଶ",
"ମହେଶ୍ୱର",
"ମାଖନଲାଲ",
"ମାଧବ",
"ମାଧବାନନ୍ଦ",
"ମାନସ",
"ମାର୍କଣ୍ଡ",
"ମାଲା",
"ମାୟାଧର",
"ମିତ୍ରଭାନୁ",
"ମିଲନ",
"ମିହିର",
"ମୀନକେତନ",
"ମୁକୁନ୍ଦ",
"ମୁକେଶ",
"ମୁନ୍ନା",
"ମୁରଲୀ",
"ମୂରଲୀଧର",
"ମୃଣାଳ",
"ମୃତ୍ୟୁଞ୍ଜୟ",
"ମେହମୁଦ",
"ମୋଚିରାମ",
"ମୋହନ",
"ଯଦୁମଣି",
"ଯଦୁମଣୀ",
"ଯାଦବ",
"ଯୁଗଳ",
"ଯୁଧିଷ୍ଠିର",
"ଯୋଗେନ୍ଦ୍ର",
"ଯୋଗେଶ",
"ରଂଜନ",
"ରଘୁନନ୍ଦନ",
"ରଘୁନାଥ",
"ରଘୁରାମ",
"ରଜନୀ",
"ରଜନୀକାନ୍ତ",
"ରଞ୍ଜିତ",
"ରଞ୍ଜୀବ",
"ରଣେନ୍ଦ୍ର",
"ରତ୍ନ",
"ରତ୍ନାକର",
"ରଥ",
"ରବି",
"ରବିନାରାୟଣ",
"ରବିନ୍ଦ୍ର",
"ରବୀନ୍ଦ୍ର",
"ରମାକାନ୍ତ",
"ରମେଶ",
"ରସାନନ୍ଦ",
"ରାଇଚରଣ",
"ରାଇମୋହନ",
"ରାକେଶ",
"ରାଖାଲ",
"ରାଘବ",
"ରାଜ",
"ରାଜକିଶୋର",
"ରାଜକୃଷ୍ଣ",
"ରାଜୀବ",
"ରାଜୁ",
"ରାଜେନ୍ଦ୍ର",
"ରାଜେଶ୍ୱରୀ",
"ରାଧାକାନ୍ତ",
"ରାଧାକୃଷ୍ଣ",
"ରାଧାମୋହନ",
"ରାଧୁ",
"ରାମ",
"ରାମଚନ୍ଦ୍ର",
"ରାମରାୟ",
"ରିପୁନାଥ",
"ରିଷଭ",
"ରୁଦ୍ର",
"ରୋମାଞ୍ଚ",
"ରୋହିତ",
"ରୋହିଦାସ",
"ଲକ୍ଷ୍ମଣ",
"ଲକ୍ଷ୍ମୀକାନ୍ତ",
"ଲକ୍ଷ୍ମୀଧର",
"ଲଡ଼ୁ",
"ଲମ୍ବୋଦର",
"ଲଳିତ",
"ଲଳିତେନ୍ଦୁ",
"ଲାଲ",
"ଲାଲବିହାରୀ",
"ଲାଲା",
"ଲିଙ୍ଗରାଜ",
"ଲୋକନାଥ",
"ଶଇବ",
"ଶତ୍ରୁଘ୍ନ",
"ଶମ୍ଭୁନାଥ",
"ଶରତ",
"ଶରଦ",
"ଶଶି",
"ଶଶିକାନ୍ତ",
"ଶଶିଭୂଷଣ",
"ଶାନ୍ତନୁ",
"ଶାନ୍ତିରାଜ",
"ଶାରଦା",
"ଶିବବ୍ରତ",
"ଶିବଶଙ୍କର",
"ଶିବସୁନ୍ଦର",
"ଶିବାଜୀ",
"ଶିଶିର",
"ଶୁକଦେବ",
"ଶେକ",
"ଶୈଳେନ୍ଦ୍ର",
"ଶୋଭରାମ",
"ଶ୍ରୀକାନ୍ତ",
"ଶ୍ରୀତମ",
"ଶ୍ରୀଦେବ",
"ଶ୍ରୀଧର",
"ଶ୍ରୀନାଥ",
"ଶ୍ରୀରାମ",
"ଶ୍ୟାମ",
"ଶ୍ୟାମଘନ",
"ଶ୍ୟାମଳେନ୍ଦୁ",
"ଶ୍ୟାମସୁନ୍ଦର",
"ସଂଗ୍ରାମ",
"ସଉରା",
"ସକିଲା",
"ସଚ୍ଚି",
"ସଞ୍ଜିବ",
"ସଞ୍ଜୀବ",
"ସଞ୍ଜୟ",
"ସତ୍ୟନାରାୟଣ",
"ସତ୍ୟପ୍ରିୟ",
"ସତ୍ୟବାଦୀ",
"ସତ୍ୟବ୍ରତ",
"ସତ୍ୟଭାମା",
"ସତ୍ୟଭୂଷଣ",
"ସତ୍ୟସୁନ୍ଦର",
"ସତ୍ୟାନନ୍ଦ",
"ସଦନ",
"ସଦାଶିବ",
"ସନତ",
"ସନାତନ",
"ସନ୍ତୋଷ",
"ସମରେନ୍ଦ୍ର",
"ସମରେଶ",
"ସମଲ",
"ସମୀର",
"ସମ୍ପଦ",
"ସମ୍ବିତ",
"ସରୋଜ",
"ସରୋଜକାନ୍ତ",
"ସରୋଜିନୀ",
"ସଲିଲ",
"ସହରାଇ",
"ସାଗର",
"ସାଗୀର",
"ସାଧୁ",
"ସାନନ୍ଦ",
"ସାମୁଏଲ",
"ସାରଦା",
"ସାଲଖାନ",
"ସାଲବେଗ",
"ସାଲୁଜା",
"ସାହେବ",
"ସିକନ୍ଦର",
"ସିଦ୍ଧଲାଲ",
"ସିଦ୍ଧାନ୍ତ",
"ସିଦ୍ଧାର୍ଥ",
"ସୀତାକାନ୍ତ",
"ସୁକାନ୍ତ",
"ସୁକୁଡା",
"ସୁକୁମାର",
"ସୁଜିତ",
"ସୁଦର୍ଶନ",
"ସୁଦାମ",
"ସୁଧାଂଶୁ",
"ସୁଧାକର",
"ସୁଧୀର",
"ସୁନୀଲ",
"ସୁନ୍ଦର",
"ସୁବର୍ଣ୍ଣ",
"ସୁବାଶ",
"ସୁବାଷ",
"ସୁବାସ",
"ସୁବୋଧ",
"ସୁବ୍ରତ",
"ସୁମନ",
"ସୁର",
"ସୁରେନ୍ଦ୍ର",
"ସୁରେନ୍ଦ୍ରନାଥ",
"ସୁରେଶ",
"ସୁଶାନ୍ତ",
"ସୁଶୀଳ",
"ସୂର୍ଯ୍ୟ",
"ସୂର୍ଯ୍ୟମଣି",
"ସୋମେଶ",
"ସୌଭିକ",
"ସୌମ୍ୟ",
"ସ୍ୱରାଜ",
"ସ୍ୱରୂପ",
"ହର",
"ହରମୋହନ",
"ହରିଚରଣ",
"ହରିପ୍ରସାଦ",
"ହରିହର",
"ହରେକୃଷ୍ଣ",
"ହାଡ଼ି",
"ହାଡ଼ିବନ୍ଧୁ",
"ହିମାଂଶୁ",
"ହେମନ୍ତ",
"ହୋମସିଂହ",
)
first_names = first_names_male + first_names_female + first_names_unisex
middle_names = (
"ଅଲ୍ଲୀ",
"କିଶୋର",
"କୃଷ୍ଣ",
"କେତନ",
"କେଶରୀ",
"ଚନ୍ଦ୍ର",
"ଚରଣ",
"ତିଆଡ଼ି",
"ନାଥ",
"ବଲ୍ଲଭ",
"ବିଦ୍ୟାଧର",
"ବିହାରି",
"ବିହାରୀ",
"ଭଞ୍ଜ",
"ଭାରତୀ",
"ଭୂଷଣ",
"ମଂଜରୀ",
"ମଞ୍ଜରୀ",
"ମତଲୁବ",
"ମାଧବ",
"ମାନସିଂହ",
"ମୋହନ",
"ଯୋଶେଫ୍",
"ରାଣୀ",
"ରାଧାରାଣୀ",
"ଲକ୍ଷ୍ମୀପ୍ରିୟା",
"ଲେଖା",
"ଲୋଚନ",
"ଶଙ୍କର",
"ଶେଖର",
"ଶ୍ରୀ",
"ସବ୍ୟସାଚୀ",
"ସାରଥି",
"ସାରଥୀ",
"ସିଂ",
"ସିଂହ",
"ସୁନ୍ଦରସୁର୍ଯ୍ୟା",
)
last_names = (
"ଅଗରୱାଲ",
"ଅଗ୍ନିବେଶ",
"ଅଗ୍ରୱାଲ",
"ଅତାହାର",
"ଅମାତ",
"ଅଲୀ",
"ଅହମଦ",
"ଆଚାର୍ଯ୍ୟ",
"ଆଦେନୀ",
"ଆନନ୍ଦ",
"ଆଲାମ",
"ଇସଲାମ",
"ଉଲ୍ଲାକା",
"ଏକ୍କା",
"ଓଝା",
"ଓରାମ",
"କଅଁର",
"କର",
"କହଁର",
"କାଡାମ୍",
"କାଡ୍ରାକା",
"କାନୁନଗୋ",
"କିନ୍ନାଗି",
"କିଶାନ",
"କିଷାନ",
"କୁଅଁର",
"କୁଣ୍ଡୁ",
"କୁମାର",
"କୁଲଦୀପ୍",
"କୁଲେସିକା",
"ଖଟୁଆ",
"ଖାଁ",
"ଖାନ",
"ଖୁଣ୍ଟିଆ",
"ଖୋସଲା",
"ଗଜପତି",
"ଗଡନାୟକ",
"ଗଡ଼ତିଆ",
"ଗଡ଼ନାୟକ",
"ଗଣପତି",
"ଗଣ୍ଡ",
"ଗମାଙ୍ଗ",
"ଗରଡ଼ିଆ",
"ଗର୍ଦ୍ଦା",
"ଗିରି",
"ଗୁରୁ",
"ଗୋସ୍ୱାମୀ",
"ଗୌତମ",
"ଗୌନ୍ତିଆ",
"ଘଡ଼ାଇ",
"ଘଡ଼େଇ",
"ଘୋଷ",
"ଚକ୍ରବର୍ତ୍ତୀ",
"ଚଣ୍ଡ",
"ଚମ୍ପତିରାୟ",
"ଚାଟାର୍ଜି",
"ଚିରଞ୍ଜୀବି",
"ଚୌଧୁରୀ",
"ଚୌରାଶିଆ",
"ଛତ୍ରିଆ",
"ଛୁରିଆ",
"ଛୋଟରାୟ",
"ଛୋଲିଆ",
"ଜଗଡାଲ",
"ଜଗଦେବ",
"ଜାନୀ",
"ଜେନା",
"ଜୈନ",
"ଝୋଡ଼ିଆ",
"ଟିକାୟତ",
"ଟୁଡୁ",
"ଟେଟେ",
"ଡାଙ୍ଗ",
"ଢ଼ୋଲକିଆ",
"ଢାଲି",
"ତନ୍ତି",
"ତରାଇ",
"ତିଆଡ଼ି",
"ତିରିୟା",
"ତିର୍କୀ",
"ତେଜ",
"ତ୍ରିପାଠୀ",
"ଥାପା",
"ଦତ୍ତ",
"ଦରାଇ",
"ଦଳବେହେରା",
"ଦାଶ",
"ଦାସ",
"ଦାସନାୟକ",
"ଦାସବର୍ମା",
"ଦିଆନ",
"ଦିଶାରୀ",
"ଦୀପ",
"ଦୁରିଆ",
"ଦୁଲାଳୀ",
"ଦେ",
"ଦେଇ",
"ଦେଓ",
"ଦେବ",
"ଦେବତା",
"ଦେବି",
"ଦେବୀ",
"ଦେହୁରୀ",
"ଦୋରା",
"ଦ୍ୟାନସାମନ୍ତରାୟ",
"ଦ୍ୱିବେଦୀ",
"ଧଡ଼ା",
"ଧଡା",
"ଧଳ",
"ନନ୍ଦ",
"ନନ୍ଦି",
"ନାଏକ",
"ନାଗ",
"ନାଗେଶ",
"ନାଥ",
"ନାହାକ",
"ନାୟକ",
"ନିଆଲ",
"ପଟୁଆ",
"ପଟ୍ଟନାୟକ",
"ପଣ୍ଡା",
"ପଣ୍ଡିତ",
"ପତି",
"ପମ",
"ପରବୀନ",
"ପରମାଣିକ",
"ପରିଜା",
"ପରିଡ଼ା",
"ପରିଡା",
"ପଲେଇ",
"ପଲ୍ଲାଇ",
"ପାଇକରାୟ",
"ପାଙ୍ଗୀ",
"ପାଢ଼ୀ",
"ପାଣି",
"ପାଣିଗ୍ରାହୀ",
"ପାତ୍ର",
"ପାଲ",
"ପାଲିତ",
"ପାଳ",
"ପୁଜାରୀ",
"ପୁଟୀ",
"ପୁରୋହିତ",
"ପୂଜାରୀ",
"ପୃଷ୍ଟି",
"ପୋଡାଲ",
"ପୋଦ୍ଦାର",
"ପ୍ରତିହାରୀ",
"ପ୍ରଧାନ",
"ପ୍ରଧାନୀ",
"ପ୍ରହରାଜ",
"ପ୍ରିୟଦର୍ଶିନୀ",
"ବକା",
"ବଗର୍ତ୍ତି",
"ବଡ଼ଜେନା",
"ବରାଳ",
"ବରିହା",
"ବର୍ମା",
"ବଳ",
"ବଳବନ୍ତରାୟ",
"ବଳସାମନ୍ତ",
"ବଳିଆରସିଂହ",
"ବଳୀୟାରସିଂହ",
"ବସନ୍ତ",
"ବସୁ",
"ବସ୍ତିଆ",
"ବାଗ",
"ବାନାର୍ଜୀ",
"ବାବୁ",
"ବାରିକ",
"ବାର୍ଲା",
"ବାହିନୀପତି",
"ବାହୁବଳେନ୍ଦ୍ର",
"ବିଜୁଳି",
"ବିଦ୍ୟାଧର",
"ବିଶୋୟୀ",
"ବିଶ୍ୱାଳ",
"ବୀର",
"ବେଉରା",
"ବେହୁରା",
"ବେହେରା",
"ବୈଦ୍ୟ",
"ବୋଷ",
"ବ୍ରହ୍ମା",
"ବ୍ୟାସ",
"ଭଞ୍ଜ",
"ଭଞ୍ଜଦେଓ",
"ଭଟ୍ଟାଚାର୍ଯ୍ୟ",
"ଭୂୟାଁ",
"ଭୋଇ",
"ମଙ୍ଗରାଜ",
"ମଢ଼େଇ",
"ମଣ୍ଡଳ",
"ମର୍ଦ୍ଦରାଜ",
"ମଲିକ",
"ମଲ୍ଲ",
"ମଲ୍ଲିକ",
"ମହନ୍ତ",
"ମହସୀନ",
"ମହାକୁଡ଼",
"ମହାନନ୍ଦ",
"ମହାନ୍ତି",
"ମହାପାତ୍ର",
"ମହାରଣା",
"ମହାରଥୀ",
"ମହାଲିଙ୍ଗା",
"ମହାଳିକ",
"ମାଝି",
"ମାଝୀ",
"ମାଢ଼ୀ",
"ମାଢ଼େଇ",
"ମାନସିଂହ",
"ମାନ୍ଧାତା",
"ମାରାଣ୍ଡି",
"ମିଞ୍ଜ୍",
"ମିତ୍ର",
"ମିର୍ଦ୍ଧା",
"ମିଶ୍ର",
"ମୁକ୍କିମ",
"ମୁଖାର୍ଜୀ",
"ମୁଣ୍ଡା",
"ମୁଦି",
"ମୁଦୁଲି",
"ମୁର୍ମୁ",
"ମୁସୀର",
"ମେହେଟା",
"ମେହେର",
"ମୋକିମ୍",
"ରଞ୍ଜନ",
"ରଣସିଂହ",
"ରଣା",
"ରଥ",
"ରନ୍ଧାରୀ",
"ରମଣୀ",
"ରାଉତ",
"ରାଉତରାୟ",
"ରାଉଳ",
"ରାଓ",
"ରାଜ",
"ରାଜନ୍",
"ରାମ",
"ରାୟ",
"ରାୟଚୌଧୁରୀ",
"ରେଡ୍ଡି",
"ରୋହିଦାସ",
"ଲାକ୍ରା",
"ଲାଗୁରୀ",
"ଲାଠ",
"ଲାଲ",
"ଲେଙ୍କା",
"ଲୋକ",
"ଶତପଥୀ",
"ଶର୍ମା",
"ଶାନ୍ତା",
"ଶ୍ରୀଚନ୍ଦନ",
"ଷଡ଼ଙ୍ଗୀ",
"ସଙ୍ଗୀତା",
"ସର୍ଖେଲ",
"ସର୍ଦ୍ଦାର",
"ସାଇ",
"ସାଉଣ୍ଟା",
"ସାମନ୍ତ",
"ସାମନ୍ତରାୟ",
"ସାମଲ",
"ସାରକା",
"ସାଲୁଜା",
"ସାହୁ",
"ସିଂ",
"ସିଂଦେଓ",
"ସିଂହ",
"ସିଂହଦେଓ",
"ସିଦୁ",
"ସିଧୁ",
"ସିପ୍କା",
"ସିହ୍ନା",
"ସୁବାହୁ",
"ସେଟି",
"ସେଠ",
"ସେଠୀ",
"ସେଠ୍",
"ସେନ",
"ସେନାପତି",
"ସୋଡ଼ି",
"ସୋରେନ",
"ସୋରେନ୍",
"ସୌର୍ଯ୍ୟା",
"ସ୍ବାଇଁ",
"ସ୍ୱାଇଁ",
"ହଇବୁରୁ",
"ହନିଫ",
"ହରିଚନ୍ଦନ",
"ହାଁସଦା",
"ହାଇବ୍ରୁ",
"ହିକୋକା",
"ହିକ୍କା",
"ହିମିରିକା",
"ହୁସେନ",
"ହେମ୍ବ୍ରମ",
"ହୋତା",
)
prefixes_female = (
"ସୁଶ୍ରୀ",
"ଶ୍ରୀମତୀ",
"କୁମାରୀ",
)
prefixes_male = (
"ଶ୍ରୀ",
"ଶ୍ରୀମାନ",
"ଶ୍ରୀଯୁକ୍ତ",
)
def first_name_unisex(self) -> str:
return self.random_element(self.first_names_unisex)
def middle_name(self) -> str:
return self.random_element(self.middle_names)
| Provider |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/module_manpath_prepend/package.py | {
"start": 217,
"end": 612
} | class ____(Package):
homepage = "http://www.spack.llnl.gov"
url = "http://www.spack.llnl.gov/module-manpath-prepend-1.0.tar.gz"
version("1.0", "0123456789abcdef0123456789abcdef")
def setup_run_environment(self, env: EnvironmentModifications) -> None:
env.prepend_path("MANPATH", "/path/to/man")
env.prepend_path("MANPATH", "/path/to/share/man")
| ModuleManpathPrepend |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-mcp/llama_index/tools/mcp/client.py | {
"start": 2854,
"end": 14584
} | class ____(ClientSession):
"""
Basic MCP client that can be used to connect to an MCP server.
This is useful for connecting to any MCP server.
Args:
command_or_url: The command to run or the URL to connect to.
args: The arguments to pass to StdioServerParameters.
env: The environment variables to set for StdioServerParameters.
timeout: The timeout for the command in seconds.
auth: Optional OAuth client provider for authentication.
sampling_callback: Optional callback for handling sampling messages.
headers: Optional headers to pass by sse client or streamable http client
tool_call_logs_callback: Async function to store the logs deriving from an MCP tool call: logs are provided as a list of strings, representing log messages. Defaults to None.
"""
def __init__(
self,
command_or_url: str,
args: Optional[List[str]] = None,
env: Optional[Dict[str, str]] = None,
timeout: int = 30,
auth: Optional[OAuthClientProvider] = None,
sampling_callback: Optional[
Callable[
[types.CreateMessageRequestParams], Awaitable[types.CreateMessageResult]
]
] = None,
headers: Optional[Dict[str, Any]] = None,
tool_call_logs_callback: Optional[Callable[[List[str]], Awaitable[Any]]] = None,
):
self.command_or_url = command_or_url
self.args = args or []
self.env = env or {}
self.timeout = timeout
self.auth = auth
self.sampling_callback = sampling_callback
self.headers = headers
self.tool_call_logs_callback = tool_call_logs_callback
@classmethod
def with_oauth(
cls,
command_or_url: str,
client_name: str,
redirect_uris: List[str],
redirect_handler: Callable[[str], None],
callback_handler: Callable[[], Tuple[str, Optional[str]]],
args: Optional[List[str]] = None,
env: Optional[Dict[str, str]] = None,
timeout: int = 30,
token_storage: Optional[TokenStorage] = None,
tool_call_logs_callback: Optional[Callable[[List[str]], Awaitable[Any]]] = None,
) -> "BasicMCPClient":
"""
Create a client with OAuth authentication.
Args:
command_or_url: The command to run or the URL to connect to
client_name: The name of the OAuth client
redirect_uris: The redirect URIs for the OAuth flow
redirect_handler: Function that handles the redirect URL
callback_handler: Function that returns the auth code and state
token_storage: Optional token storage for OAuth client. If not provided,
a default in-memory storage is used (tokens will be lost on restart).
args: The arguments to pass to StdioServerParameters.
env: The environment variables to set for StdioServerParameters.
timeout: The timeout for the command in seconds.
tool_call_logs_callback: Async function to store the logs deriving from an MCP tool call: logs are provided as a list of strings, representing log messages. Defaults to None.
Returns:
An authenticated MCP client
"""
# Use default in-memory storage if none provided
if token_storage is None:
token_storage = DefaultInMemoryTokenStorage()
warnings.warn(
"Using default in-memory token storage. Tokens will be lost on restart.",
UserWarning,
)
oauth_auth = OAuthClientProvider(
server_url=command_or_url if urlparse(command_or_url).scheme else None,
client_metadata=OAuthClientMetadata(
client_name=client_name,
redirect_uris=redirect_uris,
grant_types=["authorization_code", "refresh_token"],
response_types=["code"],
),
redirect_handler=redirect_handler,
callback_handler=callback_handler,
storage=token_storage,
)
return cls(
command_or_url,
auth=oauth_auth,
args=args,
env=env,
timeout=timeout,
tool_call_logs_callback=tool_call_logs_callback,
)
@asynccontextmanager
async def _run_session(self) -> AsyncIterator[ClientSession]:
"""Create and initialize a session with the MCP server."""
url = urlparse(self.command_or_url)
scheme = url.scheme
if scheme in ("http", "https"):
# Check if this is a streamable HTTP endpoint (default) or SSE
if enable_sse(self.command_or_url):
# SSE transport
async with sse_client(
self.command_or_url, auth=self.auth, headers=self.headers
) as streams:
async with ClientSession(
*streams,
read_timeout_seconds=timedelta(seconds=self.timeout),
sampling_callback=self.sampling_callback,
) as session:
await session.initialize()
yield session
else:
# Streamable HTTP transport (recommended)
async with streamablehttp_client(
self.command_or_url, auth=self.auth, headers=self.headers
) as (read, write, _):
async with ClientSession(
read,
write,
read_timeout_seconds=timedelta(seconds=self.timeout),
sampling_callback=self.sampling_callback,
) as session:
await session.initialize()
yield session
else:
# stdio transport
server_parameters = StdioServerParameters(
command=self.command_or_url, args=self.args, env=self.env
)
async with stdio_client(server_parameters) as streams:
async with ClientSession(
*streams,
read_timeout_seconds=timedelta(seconds=self.timeout),
sampling_callback=self.sampling_callback,
) as session:
await session.initialize()
yield session
def _configure_tool_call_logs_callback(self) -> io.StringIO:
handler = io.StringIO()
stream_handler = logging.StreamHandler(handler)
# Configure logging to capture all events
logging.basicConfig(
level=logging.DEBUG, # Capture all log levels
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s\n",
handlers=[
stream_handler,
],
)
# Also enable logging for specific FastMCP components
fastmcp_logger = logging.getLogger("fastmcp")
fastmcp_logger.setLevel(logging.DEBUG)
# Enable HTTP transport logging to see network details
http_logger = logging.getLogger("httpx")
http_logger.setLevel(logging.DEBUG)
return handler
# Tool methods
async def call_tool(
self,
tool_name: str,
arguments: Optional[dict] = None,
progress_callback: Optional[ProgressFnT] = None,
) -> types.CallToolResult:
"""Call a tool on the MCP server."""
if self.tool_call_logs_callback is not None:
# we use a string stream so that we can recover all logs at the end of the session
handler = self._configure_tool_call_logs_callback()
async with self._run_session() as session:
result = await session.call_tool(
tool_name, arguments=arguments, progress_callback=progress_callback
)
# get all logs by dividing the string with \n, since the format of the log has an \n at the end of the log message
extra_values = handler.getvalue().split("\n")
# pipe the logs list into tool_call_logs_callback
await self.tool_call_logs_callback(extra_values)
return result
else:
async with self._run_session() as session:
return await session.call_tool(
tool_name, arguments=arguments, progress_callback=progress_callback
)
async def list_tools(self) -> types.ListToolsResult:
"""List all available tools on the MCP server."""
async with self._run_session() as session:
return await session.list_tools()
# Resource methods
async def list_resources(self) -> types.ListToolsResult:
"""List all available resources on the MCP server."""
async with self._run_session() as session:
return await session.list_resources()
async def list_resource_templates(self) -> types.ListToolsResult:
"""List all dynamic available resources on the MCP server."""
async with self._run_session() as session:
return await session.list_resource_templates()
async def read_resource(self, resource_uri: AnyUrl) -> types.ReadResourceResult:
"""
Read a resource from the MCP server.
Returns:
Tuple containing the resource content as bytes and the MIME type
"""
async with self._run_session() as session:
return await session.read_resource(resource_uri)
## ----- Prompt methods -----
async def list_prompts(self) -> List[types.Prompt]:
"""List all available prompts on the MCP server."""
async with self._run_session() as session:
return await session.list_prompts()
async def get_prompt(
self, prompt_name: str, arguments: Optional[Dict[str, str]] = None
) -> List[ChatMessage]:
"""
Get a prompt from the MCP server.
Args:
prompt_name: The name of the prompt to get
arguments: Optional arguments to pass to the prompt
Returns:
The prompt as a list of llama-index ChatMessage objects
"""
async with self._run_session() as session:
prompt = await session.get_prompt(prompt_name, arguments)
llama_messages = []
for message in prompt.messages:
if isinstance(message.content, types.TextContent):
llama_messages.append(
ChatMessage(
role=message.role,
blocks=[TextBlock(text=message.content.text)],
)
)
elif isinstance(message.content, types.ImageContent):
llama_messages.append(
ChatMessage(
role=message.role,
blocks=[
ImageBlock(
image=message.content.data,
image_mimetype=message.content.mimeType,
)
],
)
)
elif isinstance(message.content, types.EmbeddedResource):
raise NotImplementedError(
"Embedded resources are not supported yet"
)
else:
raise ValueError(
f"Unsupported content type: {type(message.content)}"
)
return llama_messages
| BasicMCPClient |
python | django__django | tests/decorators/test_http.py | {
"start": 2330,
"end": 3864
} | class ____(SimpleTestCase):
def test_require_safe_accepts_only_safe_methods(self):
def my_view(request):
return HttpResponse("OK")
my_safe_view = require_safe(my_view)
request = HttpRequest()
request.method = "GET"
self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = "HEAD"
self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = "POST"
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = "PUT"
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = "DELETE"
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
async def test_require_safe_accepts_only_safe_methods_async_view(self):
@require_safe
async def async_view(request):
return HttpResponse("OK")
request = HttpRequest()
request.method = "GET"
self.assertIsInstance(await async_view(request), HttpResponse)
request.method = "HEAD"
self.assertIsInstance(await async_view(request), HttpResponse)
request.method = "POST"
self.assertIsInstance(await async_view(request), HttpResponseNotAllowed)
request.method = "PUT"
self.assertIsInstance(await async_view(request), HttpResponseNotAllowed)
request.method = "DELETE"
self.assertIsInstance(await async_view(request), HttpResponseNotAllowed)
| RequireSafeDecoratorTest |
python | huggingface__transformers | src/transformers/models/vitdet/modeling_vitdet.py | {
"start": 14808,
"end": 18005
} | class ____(nn.Module):
def __init__(self, config, in_features: int, hidden_features: int) -> None:
super().__init__()
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = ACT2FN[config.hidden_act]
self.fc2 = nn.Linear(hidden_features, in_features)
self.drop = nn.Dropout(config.dropout_prob)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
def window_partition(hidden_state, window_size):
"""
Partition into non-overlapping windows with padding if needed.
Args:
hidden_state (`torch.Tensor`):
Input tokens with [batch_size, height, width, num_channels].
window_size (`int`):
Window size.
Returns:
`tuple(torch.FloatTensor)` comprising various elements:
- windows: windows after partition with [batch_size * num_windows, window_size, window_size, num_channels].
- (padded_height, padded_width): padded height and width before partition
"""
batch_size, height, width, num_channels = hidden_state.shape
pad_height = (window_size - height % window_size) % window_size
pad_width = (window_size - width % window_size) % window_size
# Noop in case pad_width == 0 and pad_height == 0.
hidden_state = nn.functional.pad(hidden_state, (0, 0, 0, pad_width, 0, pad_height))
padded_height, padded_width = height + pad_height, width + pad_width
hidden_state = hidden_state.view(
batch_size, padded_height // window_size, window_size, padded_width // window_size, window_size, num_channels
)
windows = hidden_state.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
return windows, (padded_height, padded_width)
def window_unpartition(windows, window_size, pad_height_width, height_width):
"""
Window unpartition into original sequences and removing padding.
Args:
windows (`torch.Tensor`):
Input tokens with [batch_size * num_windows, window_size, window_size, num_channels].
window_size (`int`):
Window size.
pad_height_width (`tuple[int]`):
Padded height and width (padded_height, padded_width).
height_width (`tuple[int]`):
Original height and width before padding.
Returns:
hidden_state: unpartitioned sequences with [batch_size, height, width, num_channels].
"""
padded_height, padded_width = pad_height_width
height, width = height_width
batch_size = windows.shape[0] // (padded_height * padded_width // window_size // window_size)
hidden_state = windows.view(
batch_size, padded_height // window_size, padded_width // window_size, window_size, window_size, -1
)
hidden_state = hidden_state.permute(0, 1, 3, 2, 4, 5).contiguous()
hidden_state = hidden_state.view(batch_size, padded_height, padded_width, -1)
# We always have height <= padded_height and width <= padded_width
hidden_state = hidden_state[:, :height, :width, :].contiguous()
return hidden_state
| VitDetMlp |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/test_install_callbacks/package.py | {
"start": 276,
"end": 588
} | class ____(generic.Package):
"""This package illustrates install callback test failure."""
homepage = "http://www.example.com/test-install-callbacks"
url = "http://www.test-failure.test/test-install-callbacks-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
| TestInstallCallbacks |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_param.py | {
"start": 8382,
"end": 8758
} | class ____:
# User-defined metadata passed from pre to post-all-gather
all_gather_metadata: Optional[Any] = None
# Save the all-gather input sizes to unflatten the all-gather outputs to ND
all_gather_input_sizes: Sequence[torch.Size] = () # ND
def clear(self):
self.all_gather_metadata = None
self.all_gather_input_sizes = ()
| ExtensionsData |
python | pytest-dev__pytest-mock | src/pytest_mock/plugin.py | {
"start": 766,
"end": 879
} | class ____(UserWarning):
"""Base class for all warnings emitted by pytest-mock."""
@dataclass
| PytestMockWarning |
python | run-llama__llama_index | llama-index-core/llama_index/core/data_structs/table.py | {
"start": 837,
"end": 1034
} | class ____(BaseStructTable):
"""Pandas struct outputs."""
@classmethod
def get_type(cls) -> IndexStructType:
"""Get type."""
return IndexStructType.PANDAS
| PandasStructTable |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 29199,
"end": 32963
} | class ____(fixtures.MappedTest):
__requires__ = "skip_mysql_on_windows", "on_update_or_deferrable_fks"
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
fk_args = _backend_specific_fk_args()
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("username", String(50), unique=True),
Column("fullname", String(100)),
test_needs_fk=True,
)
Table(
"addresses",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("email", String(50)),
Column(
"username", String(50), ForeignKey("users.username", **fk_args)
),
test_needs_fk=True,
)
@classmethod
def setup_classes(cls):
class User(cls.Comparable):
pass
class Address(cls.Comparable):
pass
@testing.requires.on_update_cascade
def test_onetomany_passive(self):
self._test_onetomany(True)
def test_onetomany_nonpassive(self):
self._test_onetomany(False)
def _test_onetomany(self, passive_updates):
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address, passive_updates=passive_updates
)
},
)
self.mapper_registry.map_imperatively(Address, addresses)
sess = fixture_session()
u1 = User(username="jack", fullname="jack")
u1.addresses.append(Address(email="jack1"))
u1.addresses.append(Address(email="jack2"))
sess.add(u1)
sess.flush()
a1 = u1.addresses[0]
eq_(
sess.execute(sa.select(addresses.c.username)).fetchall(),
[("jack",), ("jack",)],
)
assert sess.get(Address, a1.id) is u1.addresses[0]
u1.username = "ed"
sess.flush()
assert u1.addresses[0].username == "ed"
eq_(
sess.execute(sa.select(addresses.c.username)).fetchall(),
[("ed",), ("ed",)],
)
sess.expunge_all()
eq_(
[Address(username="ed"), Address(username="ed")],
sess.query(Address).all(),
)
u1 = sess.get(User, u1.id)
u1.username = "jack"
def go():
sess.flush()
if not passive_updates:
# test passive_updates=False; load addresses,
# update user, update 2 addresses (in one executemany)
self.assert_sql_count(testing.db, go, 3)
else:
# test passive_updates=True; update user
self.assert_sql_count(testing.db, go, 1)
sess.expunge_all()
assert User(
username="jack",
addresses=[Address(username="jack"), Address(username="jack")],
) == sess.get(User, u1.id)
sess.expunge_all()
u1 = sess.get(User, u1.id)
u1.addresses = []
u1.username = "fred"
sess.flush()
sess.expunge_all()
a1 = sess.get(Address, a1.id)
eq_(a1.username, None)
eq_(
sess.execute(sa.select(addresses.c.username)).fetchall(),
[(None,), (None,)],
)
u1 = sess.get(User, u1.id)
eq_(User(username="fred", fullname="jack"), u1)
| NonPKCascadeTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/callbacks/token_counting.py | {
"start": 4166,
"end": 8680
} | class ____(PythonicallyPrintingBaseHandler):
"""
Callback handler for counting tokens in LLM and Embedding events.
Args:
tokenizer:
Tokenizer to use. Defaults to the global tokenizer
(see llama_index.core.utils.globals_helper).
event_starts_to_ignore: List of event types to ignore at the start of a trace.
event_ends_to_ignore: List of event types to ignore at the end of a trace.
"""
def __init__(
self,
tokenizer: Optional[Callable[[str], List]] = None,
event_starts_to_ignore: Optional[List[CBEventType]] = None,
event_ends_to_ignore: Optional[List[CBEventType]] = None,
verbose: bool = False,
logger: Optional[logging.Logger] = None,
) -> None:
self.llm_token_counts: List[TokenCountingEvent] = []
self.embedding_token_counts: List[TokenCountingEvent] = []
self.tokenizer = tokenizer or get_tokenizer()
self._token_counter = TokenCounter(tokenizer=self.tokenizer)
self._verbose = verbose
super().__init__(
event_starts_to_ignore=event_starts_to_ignore or [],
event_ends_to_ignore=event_ends_to_ignore or [],
logger=logger,
)
def start_trace(self, trace_id: Optional[str] = None) -> None:
return
def end_trace(
self,
trace_id: Optional[str] = None,
trace_map: Optional[Dict[str, List[str]]] = None,
) -> None:
return
def on_event_start(
self,
event_type: CBEventType,
payload: Optional[Dict[str, Any]] = None,
event_id: str = "",
parent_id: str = "",
**kwargs: Any,
) -> str:
return event_id
def on_event_end(
self,
event_type: CBEventType,
payload: Optional[Dict[str, Any]] = None,
event_id: str = "",
**kwargs: Any,
) -> None:
"""Count the LLM or Embedding tokens as needed."""
if (
event_type == CBEventType.LLM
and event_type not in self.event_ends_to_ignore
and payload is not None
):
self.llm_token_counts.append(
get_llm_token_counts(
token_counter=self._token_counter,
payload=payload,
event_id=event_id,
)
)
if self._verbose:
self._print(
"LLM Prompt Token Usage: "
f"{self.llm_token_counts[-1].prompt_token_count}\n"
"LLM Completion Token Usage: "
f"{self.llm_token_counts[-1].completion_token_count}",
)
elif (
event_type == CBEventType.EMBEDDING
and event_type not in self.event_ends_to_ignore
and payload is not None
):
total_chunk_tokens = 0
for chunk in payload.get(EventPayload.CHUNKS, []):
self.embedding_token_counts.append(
TokenCountingEvent(
event_id=event_id,
prompt=chunk,
prompt_token_count=self._token_counter.get_string_tokens(chunk),
completion="",
completion_token_count=0,
)
)
total_chunk_tokens += self.embedding_token_counts[-1].total_token_count
if self._verbose:
self._print(f"Embedding Token Usage: {total_chunk_tokens}")
@property
def total_llm_token_count(self) -> int:
"""Get the current total LLM token count."""
return sum([x.total_token_count for x in self.llm_token_counts])
@property
def prompt_llm_token_count(self) -> int:
"""Get the current total LLM prompt token count."""
return sum([x.prompt_token_count for x in self.llm_token_counts])
@property
def completion_llm_token_count(self) -> int:
"""Get the current total LLM completion token count."""
return sum([x.completion_token_count for x in self.llm_token_counts])
@property
def total_embedding_token_count(self) -> int:
"""Get the current total Embedding token count."""
return sum([x.total_token_count for x in self.embedding_token_counts])
def reset_counts(self) -> None:
"""Reset the token counts."""
self.llm_token_counts = []
self.embedding_token_counts = []
| TokenCountingHandler |
python | numba__numba | numba/tests/test_dyn_array.py | {
"start": 30921,
"end": 31385
} | class ____(TestNdZerosLike):
def setUp(self):
super(TestNdOnesLike, self).setUp()
self.pyfunc = np.ones_like
self.expected_value = 1
# Not supported yet.
@unittest.expectedFailure
def test_like_structured(self):
super(TestNdOnesLike, self).test_like_structured()
@unittest.expectedFailure
def test_like_dtype_structured(self):
super(TestNdOnesLike, self).test_like_dtype_structured()
| TestNdOnesLike |
python | GokuMohandas__MadeWithML | madewithml/models.py | {
"start": 152,
"end": 1911
} | class ____(nn.Module):
def __init__(self, llm, dropout_p, embedding_dim, num_classes):
super(FinetunedLLM, self).__init__()
self.llm = llm
self.dropout_p = dropout_p
self.embedding_dim = embedding_dim
self.num_classes = num_classes
self.dropout = torch.nn.Dropout(dropout_p)
self.fc1 = torch.nn.Linear(embedding_dim, num_classes)
def forward(self, batch):
ids, masks = batch["ids"], batch["masks"]
seq, pool = self.llm(input_ids=ids, attention_mask=masks)
z = self.dropout(pool)
z = self.fc1(z)
return z
@torch.inference_mode()
def predict(self, batch):
self.eval()
z = self(batch)
y_pred = torch.argmax(z, dim=1).cpu().numpy()
return y_pred
@torch.inference_mode()
def predict_proba(self, batch):
self.eval()
z = self(batch)
y_probs = F.softmax(z, dim=1).cpu().numpy()
return y_probs
def save(self, dp):
with open(Path(dp, "args.json"), "w") as fp:
contents = {
"dropout_p": self.dropout_p,
"embedding_dim": self.embedding_dim,
"num_classes": self.num_classes,
}
json.dump(contents, fp, indent=4, sort_keys=False)
torch.save(self.state_dict(), os.path.join(dp, "model.pt"))
@classmethod
def load(cls, args_fp, state_dict_fp):
with open(args_fp, "r") as fp:
kwargs = json.load(fp=fp)
llm = BertModel.from_pretrained("allenai/scibert_scivocab_uncased", return_dict=False)
model = cls(llm=llm, **kwargs)
model.load_state_dict(torch.load(state_dict_fp, map_location=torch.device("cpu")))
return model
| FinetunedLLM |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_cache.py | {
"start": 804,
"end": 894
} | class ____:
def foo(self, x):
return 0
def bar(self, x):
return 1
| Y |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 2207,
"end": 3281
} | class ____(ModelOutput):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
The rope index difference between sequence length and multimodal rope.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
rope_deltas: Optional[torch.LongTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for Qwen2VL causal language model (or autoregressive) outputs.
"""
)
| Qwen2VLModelOutputWithPast |
python | django__django | tests/admin_views/test_adminsite.py | {
"start": 3618,
"end": 4544
} | class ____(SimpleTestCase):
def setUp(self):
self.site = admin.AdminSite()
def test_add_action(self):
def test_action():
pass
self.site.add_action(test_action)
self.assertEqual(self.site.get_action("test_action"), test_action)
def test_disable_action(self):
action_name = "delete_selected"
self.assertEqual(self.site._actions[action_name], delete_selected)
self.site.disable_action(action_name)
with self.assertRaises(KeyError):
self.site._actions[action_name]
def test_get_action(self):
"""AdminSite.get_action() returns an action even if it's disabled."""
action_name = "delete_selected"
self.assertEqual(self.site.get_action(action_name), delete_selected)
self.site.disable_action(action_name)
self.assertEqual(self.site.get_action(action_name), delete_selected)
| SiteActionsTests |
python | readthedocs__readthedocs.org | readthedocs/analytics/proxied_api.py | {
"start": 1037,
"end": 5275
} | class ____(CDNCacheControlMixin, APIView):
"""
Track page views.
Query parameters:
- project
- version
- absolute_uri: Full path with domain.
"""
# We always want to hit our analytics endpoint,
# so we capture all views/interactions.
cache_response = False
http_method_names = ["get"]
permission_classes = [IsAuthorizedToViewProject | IsAuthorizedToViewVersion]
@lru_cache(maxsize=1)
def _get_project(self):
project_slug = self.request.GET.get("project")
project = get_object_or_404(Project, slug=project_slug)
return project
@lru_cache(maxsize=1)
def _get_version(self):
version_slug = self.request.GET.get("version")
project = self._get_project()
# Do not call `get_object_or_404` because there may be some invalid URLs without versions.
# We do want to track those 404 pages as well. In that case, the `filename` attribute is the `path`.
version = project.versions.filter(slug=version_slug).first()
return version
def get(self, request, *args, **kwargs):
# TODO: Use absolute_uri only, we don't need project and version.
project = self._get_project()
version = self._get_version()
absolute_uri = self.request.GET.get("absolute_uri")
status = self.request.GET.get("status", "200")
if not absolute_uri:
return JsonResponse(
{"error": "'absolute_uri' GET attribute is required"},
status=status_codes.HTTP_400_BAD_REQUEST,
)
if status not in ("200", "404"):
return JsonResponse(
{"error": "'status' GET attribute should be 200 or 404"},
status=status_codes.HTTP_400_BAD_REQUEST,
)
self.increase_page_view_count(
project=project,
version=version,
absolute_uri=absolute_uri,
status=status,
)
return Response(status=status_codes.HTTP_204_NO_CONTENT)
def increase_page_view_count(self, project, version, absolute_uri, status):
"""Increase the page view count for the given project."""
if is_suspicious_request(self.request):
log.info(
"Suspicious request, not recording pageview.",
url=absolute_uri,
)
return
# Don't track 200 if the version doesn't exist
if status == "200" and not version:
return
# Don't allow tracking page views from external domains.
if self.request.unresolved_domain.is_from_external_domain:
return
# Don't track external versions.
if version and version.is_external:
return
try:
absolute_uri_parsed = urlparse(absolute_uri)
except ValueError as e:
log.info(
"Skipping page view count due to URL parsing error",
url=absolute_uri,
error=str(e),
)
return
try:
unresolved = unresolver.unresolve_url(absolute_uri)
filename = unresolved.filename
absolute_uri_project = unresolved.project
except InvalidPathForVersionedProjectError as exc:
# If the version is missing, we still want to log this request.
#
# If we don't have a version, the filename is the path,
# otherwise it would be empty.
filename = exc.path
absolute_uri_project = exc.project
except UnresolverError:
# If we were unable to resolve the URL, it
# isn't pointing to a valid RTD project.
return
if absolute_uri_project.slug != project.slug:
log.warning(
"Skipping page view count since projects don't match",
project_slug=project.slug,
uri_project_slug=absolute_uri_project.slug,
)
return
PageView.objects.register_page_view(
project=project,
version=version,
filename=filename,
path=absolute_uri_parsed.path,
status=status,
)
| BaseAnalyticsView |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 93281,
"end": 93781
} | class ____(sgqlc.types.Enum):
"""The possible states of an alert
Enumeration Choices:
* `AUTO_DISMISSED`: An alert that has been automatically closed by
Dependabot.
* `DISMISSED`: An alert that has been manually closed by a user.
* `FIXED`: An alert that has been resolved by a code change.
* `OPEN`: An alert that is still open.
"""
__schema__ = github_schema
__choices__ = ("AUTO_DISMISSED", "DISMISSED", "FIXED", "OPEN")
| RepositoryVulnerabilityAlertState |
python | ray-project__ray | python/ray/dashboard/subprocesses/handle.py | {
"start": 1307,
"end": 12535
} | class ____:
"""
A handle to a module created as a subprocess. Can send messages to the module and
receive responses. It only acts as a proxy to the aiohttp server running in the
subprocess. On destruction, the subprocess is terminated.
Lifecycle:
1. In SubprocessModuleHandle creation, the subprocess is started and runs an aiohttp
server.
2. User must call start_module() and wait_for_module_ready() first.
3. SubprocessRouteTable.bind(handle)
4. app.add_routes(routes=SubprocessRouteTable.bound_routes())
5. Run the app.
Health check (_do_periodic_health_check):
Every 1s, do a health check by _do_once_health_check. If the module is
unhealthy:
1. log the exception
2. log the last N lines of the log file
3. fail all active requests
4. restart the module
TODO(ryw): define policy for health check:
- check period (Now: 1s)
- define unhealthy. (Now: process exits. TODO: check_health() for event loop hang)
- check number of failures in a row before we deem it unhealthy (Now: N/A)
- "max number of restarts"? (Now: infinite)
"""
# Class variable. Force using spawn because Ray C bindings have static variables
# that need to be re-initialized for a new process.
mp_context = multiprocessing.get_context("spawn")
def __init__(
self,
loop: asyncio.AbstractEventLoop,
module_cls: type[SubprocessModule],
config: SubprocessModuleConfig,
):
self.loop = loop
self.module_cls = module_cls
self.config = config
# Increment this when the module is restarted.
self.incarnation = 0
# Runtime states, set by start_module() and wait_for_module_ready(),
# reset by destroy_module().
self.parent_conn = None
self.process = None
self.http_client_session: Optional[aiohttp.ClientSession] = None
self.health_check_task = None
def str_for_state(self, incarnation: int, pid: Optional[int]):
return f"SubprocessModuleHandle(module_cls={self.module_cls.__name__}, incarnation={incarnation}, pid={pid})"
def __str__(self):
return self.str_for_state(
self.incarnation, self.process.pid if self.process else None
)
def start_module(self):
"""
Start the module. Should be non-blocking.
"""
self.parent_conn, child_conn = self.mp_context.Pipe()
if not os.path.exists(self.config.socket_dir):
os.makedirs(self.config.socket_dir)
self.process = self.mp_context.Process(
target=run_module,
args=(
self.module_cls,
self.config,
self.incarnation,
child_conn,
),
daemon=True,
name=f"{self.module_cls.__name__}-{self.incarnation}",
)
self.process.start()
child_conn.close()
def wait_for_module_ready(self):
"""
Wait for the module to be ready. This is called after start_module()
and can be blocking.
"""
if self.parent_conn.poll(dashboard_consts.SUBPROCESS_MODULE_WAIT_READY_TIMEOUT):
try:
self.parent_conn.recv()
except EOFError:
raise RuntimeError(
f"Module {self.module_cls.__name__} failed to start. "
"Received EOF from pipe."
)
self.parent_conn.close()
self.parent_conn = None
else:
raise RuntimeError(
f"Module {self.module_cls.__name__} failed to start. "
f"Timeout after {dashboard_consts.SUBPROCESS_MODULE_WAIT_READY_TIMEOUT} seconds."
)
module_name = self.module_cls.__name__
self.http_client_session = get_http_session_to_module(
module_name, self.config.socket_dir, self.config.session_name
)
self.health_check_task = self.loop.create_task(self._do_periodic_health_check())
async def destroy_module(self):
"""
Destroy the module. This is called when the module is unhealthy.
"""
self.incarnation += 1
if self.parent_conn:
self.parent_conn.close()
self.parent_conn = None
if self.process:
self.process.kill()
self.process.join()
self.process = None
if self.http_client_session:
await self.http_client_session.close()
self.http_client_session = None
if self.health_check_task:
self.health_check_task.cancel()
self.health_check_task = None
async def _health_check(self) -> aiohttp.web.Response:
"""
Do internal health check. The module should respond immediately with a 200 OK.
This can be used to measure module responsiveness in RTT, it also indicates
subprocess event loop lag.
Currently you get a 200 OK with body = b'success'. Later if we want we can add more
observability payloads.
"""
resp = await self.http_client_session.get("http://localhost/api/healthz")
return aiohttp.web.Response(
status=resp.status,
headers=filter_hop_by_hop_headers(resp.headers),
body=await resp.read(),
)
async def _do_once_health_check(self):
"""
Do a health check once. We check for:
1. if the process exits, it's considered died.
2. if the health check endpoint returns non-200, it's considered unhealthy.
"""
if self.process.exitcode is not None:
raise RuntimeError(f"Process exited with code {self.process.exitcode}")
resp = await self._health_check()
if resp.status != 200:
raise RuntimeError(f"Health check failed: status code is {resp.status}")
async def _do_periodic_health_check(self):
"""
Every 1s, do a health check. If the module is unhealthy:
1. log the exception
2. log the last N lines of the log file
3. restart the module
"""
while True:
try:
await self._do_once_health_check()
except Exception:
filename = module_logging_filename(
self.module_cls.__name__, self.config.logging_filename
)
logger.exception(
f"Module {self.module_cls.__name__} is unhealthy. Please refer to "
f"{self.config.log_dir}/{filename} for more details. Failing all "
"active requests."
)
await self.destroy_module()
self.start_module()
self.wait_for_module_ready()
return
await asyncio.sleep(1)
async def proxy_request(
self, request: aiohttp.web.Request, resp_type: ResponseType = ResponseType.HTTP
) -> aiohttp.web.StreamResponse:
"""
Sends a new request to the subprocess and returns the response.
"""
if resp_type == ResponseType.HTTP:
return await self.proxy_http(request)
if resp_type == ResponseType.STREAM:
return await self.proxy_stream(request)
if resp_type == ResponseType.WEBSOCKET:
return await self.proxy_websocket(request)
raise ValueError(f"Unknown response type: {resp_type}")
async def proxy_http(self, request: aiohttp.web.Request) -> aiohttp.web.Response:
"""
Proxy handler for non-streaming HTTP API
It forwards the method, query string, headers, and body to the backend.
"""
url = f"http://localhost{request.path_qs}"
body = await request.read()
async with self.http_client_session.request(
request.method,
url,
data=body,
headers=filter_hop_by_hop_headers(request.headers),
allow_redirects=False,
) as backend_resp:
resp_body = await backend_resp.read()
return aiohttp.web.Response(
status=backend_resp.status,
headers=filter_hop_by_hop_headers(backend_resp.headers),
body=resp_body,
)
async def proxy_stream(
self, request: aiohttp.web.Request
) -> aiohttp.web.StreamResponse:
"""
Proxy handler for streaming HTTP API.
It forwards the method, query string, and body to the backend.
"""
url = f"http://localhost{request.path_qs}"
body = await request.read()
async with self.http_client_session.request(
request.method,
url,
data=body,
headers=filter_hop_by_hop_headers(request.headers),
) as backend_resp:
proxy_resp = aiohttp.web.StreamResponse(
status=backend_resp.status,
headers=filter_hop_by_hop_headers(backend_resp.headers),
)
await proxy_resp.prepare(request)
async for chunk, _ in backend_resp.content.iter_chunks():
await proxy_resp.write(chunk)
await proxy_resp.write_eof()
return proxy_resp
async def proxy_websocket(
self, request: aiohttp.web.Request
) -> aiohttp.web.StreamResponse:
"""
Proxy handler for WebSocket API
It establishes a WebSocket connection with the client and simultaneously connects
to the backend server's WebSocket endpoint. Messages are forwarded in single
direction from the backend to the client.
If the backend responds with normal HTTP response, then try to treat it as a normal
HTTP request and calls proxy_http instead.
TODO: Support bidirectional communication if needed. We only support one direction
because it's sufficient for the current use case.
"""
url = f"http://localhost{request.path_qs}"
try:
async with self.http_client_session.ws_connect(
url, headers=filter_hop_by_hop_headers(request.headers)
) as ws_to_backend:
ws_from_client = aiohttp.web.WebSocketResponse()
await ws_from_client.prepare(request)
async for msg in ws_to_backend:
if msg.type == aiohttp.WSMsgType.TEXT:
await ws_from_client.send_str(msg.data)
elif msg.type == aiohttp.WSMsgType.BINARY:
await ws_from_client.send_bytes(msg.data)
else:
logger.error(f"Unknown msg type: {msg.type}")
await ws_from_client.close()
return ws_from_client
except aiohttp.WSServerHandshakeError as e:
logger.warning(f"WebSocket handshake error: {repr(e)}")
# Try to treat it as a normal HTTP request
return await self.proxy_http(request)
except Exception as e:
logger.error(f"WebSocket proxy error: {repr(e)}")
raise aiohttp.web.HTTPInternalServerError(reason="WebSocket proxy error")
| SubprocessModuleHandle |
python | jazzband__django-polymorphic | src/polymorphic/admin/generic.py | {
"start": 385,
"end": 2416
} | class ____(PolymorphicInlineModelAdmin, GenericInlineModelAdmin):
"""
Base class for variation of inlines based on generic foreign keys.
"""
#: The formset class
formset = BaseGenericPolymorphicInlineFormSet
def get_formset(self, request, obj=None, **kwargs):
"""
Construct the generic inline formset class.
"""
# Construct the FormSet class. This is almost the same as parent version,
# except that a different super is called so generic_inlineformset_factory() is used.
# NOTE that generic_inlineformset_factory() also makes sure the GFK fields are excluded in the form.
FormSet = GenericInlineModelAdmin.get_formset(self, request, obj=obj, **kwargs)
FormSet.child_forms = polymorphic_child_forms_factory(
formset_children=self.get_formset_children(request, obj=obj)
)
return FormSet
class Child(PolymorphicInlineModelAdmin.Child):
"""
Variation for generic inlines.
"""
# Make sure that the GFK fields are excluded from the child forms
formset_child = GenericPolymorphicFormSetChild
ct_field = "content_type"
ct_fk_field = "object_id"
@cached_property
def content_type(self):
"""
Expose the ContentType that the child relates to.
This can be used for the ``polymorphic_ctype`` field.
"""
return ContentType.objects.get_for_model(self.model, for_concrete_model=False)
def get_formset_child(self, request, obj=None, **kwargs):
# Similar to GenericInlineModelAdmin.get_formset(),
# make sure the GFK is automatically excluded from the form
defaults = {"ct_field": self.ct_field, "fk_field": self.ct_fk_field}
defaults.update(kwargs)
return super(GenericPolymorphicInlineModelAdmin.Child, self).get_formset_child(
request, obj=obj, **defaults
)
| GenericPolymorphicInlineModelAdmin |
python | google__jax | tests/pallas/tpu_sparsecore_pallas_distributed_test.py | {
"start": 1060,
"end": 4725
} | class ____(parameterized.TestCase):
def setUp(self):
super().setUp()
if jax.device_count() < 2:
self.skipTest('Only >=2 devices are supported.')
if not jtu.is_device_tpu_at_least(5):
self.skipTest('SparseCore only supported on TPU v5+')
@parameterized.product(direction=['left', 'right'], num_devices=[2, None])
def test_collective_permute_1d(self, direction, num_devices):
shape = (8, 128)
# Implements a very simple collective permute.
@pl.kernel(
out_shape=jax.ShapeDtypeStruct(shape, jnp.int32),
mesh=plsc.ScalarSubcoreMesh(axis_name='core', num_cores=1),
scratch_shapes=(
pltpu.SemaphoreType.REGULAR,
pltpu.SemaphoreType.DMA,
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, y_ref, ready_sem, send_sem, recv_sem):
my_id = lax.axis_index('x')
axis_size = lax.axis_size('x')
if direction == 'right':
neighbor = lax.rem(my_id + 1, axis_size)
else:
neighbor = lax.rem(my_id + axis_size - 1, axis_size)
pltpu.semaphore_signal(ready_sem, device_id=neighbor)
pltpu.semaphore_wait(ready_sem)
pltpu.async_remote_copy(
x_ref, y_ref, send_sem, recv_sem, device_id=neighbor
).wait()
num_devices = num_devices or jax.device_count()
x = jnp.arange(num_devices * math.prod(shape), dtype=jnp.int32).reshape(
(-1, shape[-1])
)
device_mesh = mesh_utils.create_device_mesh(
(num_devices,), jax.devices()[:num_devices]
)
mesh = jax.sharding.Mesh(device_mesh, ['x'])
f = jax.jit(
jax.shard_map(
kernel,
mesh=mesh,
in_specs=jax.P('x'),
out_specs=jax.P('x'),
check_vma=False,
)
)
if direction == 'right':
expected = jnp.concatenate([x[-8:], x[:-8]])
else:
expected = jnp.concatenate([x[8:], x[:8]])
np.testing.assert_allclose(f(x), expected)
@parameterized.product(direction=['left', 'right'])
def test_collective_permute_2d(self, direction):
shape = (8, 128)
@pl.kernel(
out_shape=jax.ShapeDtypeStruct(shape, jnp.int32),
mesh=plsc.ScalarSubcoreMesh(axis_name='core', num_cores=1),
scratch_shapes=(
pltpu.SemaphoreType.REGULAR,
pltpu.SemaphoreType.DMA,
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, y_ref, ready_sem, send_sem, recv_sem):
my_id = lax.axis_index('x')
my_other_id = lax.axis_index('y')
axis_size = lax.axis_size('x')
if direction == 'right':
neighbor = lax.rem(my_id + 1, axis_size)
else:
neighbor = lax.rem(my_id + axis_size - 1, axis_size)
pltpu.semaphore_signal(ready_sem, device_id=(my_other_id, neighbor))
pltpu.semaphore_wait(ready_sem)
pltpu.async_remote_copy(
x_ref, y_ref, send_sem, recv_sem, device_id=(my_other_id, neighbor)
).wait()
axis_size = jax.device_count() // 2
x = jnp.arange(axis_size * 8 * 128).reshape((axis_size * 8, 128))
device_mesh = mesh_utils.create_device_mesh((2, axis_size), jax.devices())
mesh = jax.sharding.Mesh(device_mesh, ['y', 'x'])
y = jax.jit(
jax.shard_map(
kernel,
mesh=mesh,
in_specs=jax.P('x', None),
out_specs=jax.P('x', None),
check_vma=False,
)
)(x)
if direction == 'right':
expected = jnp.concatenate([x[-8:], x[:-8]])
else:
expected = jnp.concatenate([x[8:], x[:8]])
np.testing.assert_allclose(y, expected)
if __name__ == '__main__':
absltest.main()
| PallasCallRemoteDMATest |
python | scipy__scipy | scipy/integrate/_cubature.py | {
"start": 19470,
"end": 20956
} | class ____:
"""
A transformation that can be applied to an integral.
"""
@property
def transformed_limits(self):
"""
New limits of integration after applying the transformation.
"""
raise NotImplementedError
@property
def points(self):
"""
Any problematic points introduced by the transformation.
These should be specified as points where ``_VariableTransform(f)(self, point)``
would be problematic.
For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
univariate integral, then points should return ``[ [1], [-1] ]``.
"""
return []
def inv(self, x):
"""
Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
is the function after the transformation is applied, then::
f(x) = g(self.inv(x))
"""
raise NotImplementedError
def __call__(self, t, *args, **kwargs):
"""
Apply the transformation to ``f`` and multiply by the Jacobian determinant.
This should be the new integrand after the transformation has been applied so
that the following is satisfied::
f_transformed = _VariableTransform(f)
cubature(f, a, b) == cubature(
f_transformed,
*f_transformed.transformed_limits(a, b),
)
"""
raise NotImplementedError
| _VariableTransform |
python | cherrypy__cherrypy | cherrypy/test/sessiondemo.py | {
"start": 3435,
"end": 5832
} | class ____(object):
"""Session demo app."""
def page(self):
"""Render HTTP request-related details."""
changemsg = []
if cherrypy.session.id != cherrypy.session.originalid:
if cherrypy.session.originalid is None:
changemsg.append(
'Created new session because no session id was given.',
)
if cherrypy.session.missing:
changemsg.append(
'Created new session due to missing '
'(expired or malicious) session.',
)
if cherrypy.session.regenerated:
changemsg.append('Application generated a new session.')
try:
expires = cherrypy.response.cookie['session_id']['expires']
except KeyError:
expires = ''
return page % {
'sessionid': cherrypy.session.id,
'changemsg': '<br>'.join(changemsg),
'respcookie': cherrypy.response.cookie.output(),
'reqcookie': cherrypy.request.cookie.output(),
'sessiondata': list(cherrypy.session.items()),
'servertime': (
datetime.now(_timezone.utc).strftime('%Y/%m/%d %H:%M UTC')
),
'serverunixtime': calendar.timegm(
datetime.utcnow(_timezone.utc).timetuple(),
),
'cpversion': cherrypy.__version__,
'pyversion': sys.version,
'expires': expires,
}
@cherrypy.expose
def index(self):
"""Save green color in session at app index URI."""
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'green'
return self.page()
@cherrypy.expose
def expire(self):
"""Expire the existing session."""
sessions.expire()
return self.page()
@cherrypy.expose
def regen(self):
"""Regenerate the session, storing yellow color in it."""
cherrypy.session.regenerate()
# Must modify data or the session will not be saved.
cherrypy.session['color'] = 'yellow'
return self.page()
if __name__ == '__main__':
cherrypy.config.update(
{
# 'environment': 'production',
'log.screen': True,
'tools.sessions.on': True,
},
)
cherrypy.quickstart(Root())
| Root |
python | numpy__numpy | numpy/polynomial/tests/test_chebyshev.py | {
"start": 3645,
"end": 6335
} | class ____:
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([2.5, 2., 1.5])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
y = polyval(x, [1., 2., 3.])
def test_chebval(self):
# check empty input
assert_equal(cheb.chebval([], [1]).size, 0)
# check normal input)
x = np.linspace(-1, 1)
y = [polyval(x, c) for c in Tlist]
for i in range(10):
msg = f"At i={i}"
tgt = y[i]
res = cheb.chebval(x, [0] * i + [1])
assert_almost_equal(res, tgt, err_msg=msg)
# check that shape is preserved
for i in range(3):
dims = [2] * i
x = np.zeros(dims)
assert_equal(cheb.chebval(x, [1]).shape, dims)
assert_equal(cheb.chebval(x, [1, 0]).shape, dims)
assert_equal(cheb.chebval(x, [1, 0, 0]).shape, dims)
def test_chebval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test exceptions
assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)
# test values
tgt = y1 * y2
res = cheb.chebval2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = cheb.chebval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_chebval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test exceptions
assert_raises(ValueError, cheb.chebval3d, x1, x2, x3[:2], self.c3d)
# test values
tgt = y1 * y2 * y3
res = cheb.chebval3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = cheb.chebval3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3))
def test_chebgrid2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test values
tgt = np.einsum('i,j->ij', y1, y2)
res = cheb.chebgrid2d(x1, x2, self.c2d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = cheb.chebgrid2d(z, z, self.c2d)
assert_(res.shape == (2, 3) * 2)
def test_chebgrid3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
# test values
tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
res = cheb.chebgrid3d(x1, x2, x3, self.c3d)
assert_almost_equal(res, tgt)
# test shape
z = np.ones((2, 3))
res = cheb.chebgrid3d(z, z, z, self.c3d)
assert_(res.shape == (2, 3) * 3)
| TestEvaluation |
python | huggingface__transformers | tests/utils/test_image_utils.py | {
"start": 34331,
"end": 38378
} | class ____(unittest.TestCase):
def test_load_img_url(self):
img = load_image(INVOICE_URL)
img_arr = np.array(img)
self.assertEqual(img_arr.shape, (1061, 750, 3))
@is_flaky()
def test_load_img_url_timeout(self):
with self.assertRaises(httpx.ConnectTimeout):
load_image(INVOICE_URL, timeout=0.001)
def test_load_img_local(self):
img = load_image("./tests/fixtures/tests_samples/COCO/000000039769.png")
img_arr = np.array(img)
self.assertEqual(
img_arr.shape,
(480, 640, 3),
)
def test_load_img_base64_prefix(self):
path = hf_hub_download(
repo_id="hf-internal-testing/dummy-base64-images", filename="image_0.txt", repo_type="dataset"
)
with open(path, encoding="utf-8") as b64:
img = load_image(b64.read())
img_arr = np.array(img)
self.assertEqual(img_arr.shape, (64, 32, 3))
def test_load_img_base64(self):
path = hf_hub_download(
repo_id="hf-internal-testing/dummy-base64-images", filename="image_1.txt", repo_type="dataset"
)
with open(path, encoding="utf-8") as b64:
img = load_image(b64.read())
img_arr = np.array(img)
self.assertEqual(img_arr.shape, (64, 32, 3))
def test_load_img_base64_encoded_bytes(self):
path = hf_hub_download(
repo_id="hf-internal-testing/dummy-base64-images", filename="image_2.txt", repo_type="dataset"
)
with codecs.open(path, encoding="unicode_escape") as b64:
img = load_image(b64.read())
img_arr = np.array(img)
self.assertEqual(img_arr.shape, (256, 256, 3))
def test_load_img_rgba(self):
# we use revision="refs/pr/1" until the PR is merged
# https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
img = get_image_from_hub_dataset(
"hf-internal-testing/fixtures_image_utils", "0-test-lena.png", revision="refs/pr/1"
)
img = load_image(img) # img with mode RGBA
img_arr = np.array(img)
self.assertEqual(img_arr.shape, (512, 512, 3))
def test_load_img_la(self):
# we use revision="refs/pr/1" until the PR is merged
# https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
img = get_image_from_hub_dataset(
"hf-internal-testing/fixtures_image_utils", "1-test-parrots.png", revision="refs/pr/1"
)
img = load_image(img) # img with mode LA
img_arr = np.array(img)
self.assertEqual(
img_arr.shape,
(512, 768, 3),
)
def test_load_img_l(self):
# we use revision="refs/pr/1" until the PR is merged
# https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
img = get_image_from_hub_dataset(
"hf-internal-testing/fixtures_image_utils", "2-test-tree.png", revision="refs/pr/1"
)
img = load_image(img) # img with mode L
img_arr = np.array(img)
self.assertEqual(
img_arr.shape,
(381, 225, 3),
)
def test_load_img_exif_transpose(self):
# we use revision="refs/pr/1" until the PR is merged
# https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
img_without_exif_transpose = get_image_from_hub_dataset(
"hf-internal-testing/fixtures_image_utils", "3-test-cat-rotated.jpg", revision="refs/pr/1"
)
img_arr_without_exif_transpose = np.array(img_without_exif_transpose)
self.assertEqual(
img_arr_without_exif_transpose.shape,
(333, 500, 3),
)
img_with_exif_transpose = load_image(img_without_exif_transpose)
img_arr_with_exif_transpose = np.array(img_with_exif_transpose)
self.assertEqual(
img_arr_with_exif_transpose.shape,
(500, 333, 3),
)
| LoadImageTester |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-cohere-citation-chat/llama_index/packs/cohere_citation_chat/types.py | {
"start": 334,
"end": 744
} | class ____:
"""Citations settings."""
documents_request_param: str = field(default="documents")
documents_stream_event_type: str = field(default="search-results")
citations_response_field: str = field(default="citations")
documents_response_field: str = field(default="documents")
citations_stream_event_type: str = field(default="citation-generation")
dict = asdict
| CitationsSettings |
python | django__django | django/contrib/postgres/aggregates/statistics.py | {
"start": 673,
"end": 904
} | class ____(StatAggregate):
def __init__(self, y, x, sample=False, filter=None, default=None):
self.function = "COVAR_SAMP" if sample else "COVAR_POP"
super().__init__(y, x, filter=filter, default=default)
| CovarPop |
python | tensorflow__tensorflow | tensorflow/python/training/moving_averages_test.py | {
"start": 6945,
"end": 25404
} | class ____(test.TestCase):
def _CheckDecay(self, ema, actual_decay, dim, dynamic_decay_value=None):
def _Scale(dk, steps):
if ema._zero_debias:
return 1 - dk**steps
else:
return 1
tens = _Repeat(10.0, dim)
thirties = _Repeat(30.0, dim)
var0 = variables.Variable(tens, name="v0")
var1 = variables.Variable(thirties, name="v1")
self.evaluate(variables.global_variables_initializer())
# Note that tensor2 is not a Variable but just a plain Tensor resulting
# from the sum operation.
tensor2 = var0 + var1
if dynamic_decay_value is not None:
self.evaluate(ema._decay.assign(dynamic_decay_value))
update = ema.apply([var0, var1, tensor2])
avg0 = ema.average(var0)
avg1 = ema.average(var1)
avg2 = ema.average(tensor2)
self.assertItemsEqual([var0, var1], variables.moving_average_variables())
self.assertNotIn(avg0, variables.trainable_variables())
self.assertNotIn(avg1, variables.trainable_variables())
self.assertNotIn(avg2, variables.trainable_variables())
self.evaluate(variables.global_variables_initializer())
if dynamic_decay_value is not None:
self.evaluate(ema._decay.assign(dynamic_decay_value))
self.assertEqual("v0/ExponentialMovingAverage:0", avg0.name)
self.assertEqual("v1/ExponentialMovingAverage:0", avg1.name)
self.assertEqual("add/ExponentialMovingAverage:0", avg2.name)
# Check initial values.
self.assertAllClose(tens, self.evaluate(var0))
self.assertAllClose(thirties, self.evaluate(var1))
self.assertAllClose(_Repeat(10.0 + 30.0, dim), self.evaluate(tensor2))
# Check that averages are initialized correctly.
self.assertAllClose(tens, self.evaluate(avg0))
self.assertAllClose(thirties, self.evaluate(avg1))
# Note that averages of Tensor's initialize to zeros_like since no value
# of the Tensor is known because the Op has not been run (yet).
self.assertAllClose(_Repeat(0.0, dim), self.evaluate(avg2))
# Update the averages and check.
self.evaluate(update)
dk = actual_decay
expected = _Repeat(10.0 * dk + 10.0 * (1 - dk), dim)
self.assertAllClose(expected, self.evaluate(avg0))
expected = _Repeat(30.0 * dk + 30.0 * (1 - dk), dim)
self.assertAllClose(expected, self.evaluate(avg1))
expected = _Repeat(0.0 * dk + (10.0 + 30.0) * (1 - dk) / _Scale(dk, 1), dim)
self.assertAllClose(expected, self.evaluate(avg2))
# Again, update the averages and check.
self.evaluate(update)
expected = _Repeat((10.0 * dk + 10.0 * (1 - dk)) * dk + 10.0 * (1 - dk),
dim)
self.assertAllClose(expected, self.evaluate(avg0))
expected = _Repeat((30.0 * dk + 30.0 * (1 - dk)) * dk + 30.0 * (1 - dk),
dim)
self.assertAllClose(expected, self.evaluate(avg1))
expected = _Repeat(((0.0 * dk + (10.0 + 30.0) * (1 - dk)) * dk +
(10.0 + 30.0) * (1 - dk)) / _Scale(dk, 2), dim)
self.assertAllClose(expected, self.evaluate(avg2))
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Scalar(self):
ema = moving_averages.ExponentialMovingAverage(0.25)
self._CheckDecay(ema, actual_decay=0.25, dim=1)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Scalar_DynamicDecay(self):
decay_var = variables.Variable(0.75)
ema = moving_averages.ExponentialMovingAverage(decay_var)
self._CheckDecay(ema, actual_decay=0.25, dim=1, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Scalar_Debias(self):
ema = moving_averages.ExponentialMovingAverage(0.25, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.25, dim=1)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Scalar_Debias_DynamicDecay(self):
decay_var = variables.Variable(0.75)
ema = moving_averages.ExponentialMovingAverage(decay_var, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.25, dim=1, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Vector(self):
ema = moving_averages.ExponentialMovingAverage(0.25)
self._CheckDecay(ema, actual_decay=0.25, dim=5)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Vector_DynamicDecay(self):
decay_var = variables.Variable(0.75)
ema = moving_averages.ExponentialMovingAverage(decay_var)
self._CheckDecay(ema, actual_decay=0.25, dim=5, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Vector_Debias(self):
ema = moving_averages.ExponentialMovingAverage(0.25, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.25, dim=5)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNoNumUpdates_Vector_Debias_DynamicDecay(self):
decay_var = variables.Variable(0.75)
ema = moving_averages.ExponentialMovingAverage(decay_var, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.25, dim=5, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Scalar(self):
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(0.25, num_updates=1)
self._CheckDecay(ema, actual_decay=0.181818, dim=1)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Scalar_DynamicDecay(self):
decay_var = variables.Variable(0.75)
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(decay_var, num_updates=1)
self._CheckDecay(
ema, actual_decay=0.181818, dim=1, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Scalar_Debias(self):
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(
0.25, num_updates=1, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.181818, dim=1)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Scalar_Debias_DynamicDecay(self):
decay_var = variables.Variable(0.75)
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(
decay_var, num_updates=1, zero_debias=True)
self._CheckDecay(
ema, actual_decay=0.181818, dim=1, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Vector(self):
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(0.25, num_updates=1)
self._CheckDecay(ema, actual_decay=0.181818, dim=5)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Vector_DynamicDecay(self):
decay_var = variables.Variable(0.75)
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(decay_var, num_updates=1)
self._CheckDecay(
ema, actual_decay=0.181818, dim=5, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Vector_Debias(self):
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(
0.25, num_updates=1, zero_debias=True)
self._CheckDecay(ema, actual_decay=0.181818, dim=5)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNumUpdates_Vector_Debias_DynamicDecay(self):
decay_var = variables.Variable(0.75)
# With num_updates 1, the decay applied is 0.181818.
ema = moving_averages.ExponentialMovingAverage(
decay_var, num_updates=1, zero_debias=True)
self._CheckDecay(
ema, actual_decay=0.181818, dim=5, dynamic_decay_value=0.25)
@test_util.deprecated_graph_mode_only
def testAverageVariablesWithControlDeps(self):
v0 = variables.Variable(0, name="v0")
add_to_v0 = v0.assign_add(1)
v1 = variables.Variable([10.0], name="v1")
assign_to_v1 = v1.assign([20.0])
ema = moving_averages.ExponentialMovingAverage(0.25)
with ops.control_dependencies([add_to_v0]):
ema_op = ema.apply([v1])
# the moving average of v1 should not have any control inputs
v1_avg = ema.average(v1)
self.assertEqual([], v1_avg.initializer.control_inputs)
self.assertEqual([], v1_avg.value().op.control_inputs)
self.assertEqual([], v1_avg.value().op.control_inputs)
# We should be able to initialize v1_avg before v0.
self.evaluate(v1_avg.initializer)
self.evaluate(v0.initializer)
self.assertEqual([10.0], self.evaluate(v1_avg))
# running ema_op should add to v0 (in addition to updating v1_avg)
self.evaluate(assign_to_v1)
self.evaluate(ema_op)
self.assertEqual(1, self.evaluate(v0))
self.assertEqual([17.5], self.evaluate(v1_avg))
def testBasicEager(self):
v0 = variables.Variable(1.0, name="v0")
v1 = variables.Variable(2.0, name="v1")
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo")
op = ema.apply([v0, v1])
if not context.executing_eagerly():
self.evaluate(variables.global_variables_initializer())
self.evaluate(op)
self.evaluate(v0.assign(2.0))
self.evaluate(v1.assign(4.0))
self.evaluate(ema.apply([v0, v1]))
self.assertEqual("foo", ema.name)
self.assertEqual("v0/foo", ema.average_name(v0))
self.assertEqual("v1/foo", ema.average_name(v1))
self.assertAllEqual(self.evaluate(ema.average(v0)), 1.75)
self.assertAllEqual(self.evaluate(ema.average(v1)), 3.5)
def averageVariablesNamesHelper(self, zero_debias):
v0 = variables.Variable(10.0, name="v0")
v1 = variables.Variable(30.0, name="v1")
# Add a non-trainable variable.
v2 = variables.Variable(20.0, name="v2", trainable=False)
tensor2 = v0 + v1
ema = moving_averages.ExponentialMovingAverage(
0.25, zero_debias=zero_debias, name="foo")
self.assertEqual("foo", ema.name)
self.assertEqual("v0/foo", ema.average_name(v0))
self.assertEqual("v1/foo", ema.average_name(v1))
self.assertEqual("add/foo", ema.average_name(tensor2))
ema.apply([v0, v1, tensor2])
vars_to_restore = ema.variables_to_restore()
# vars_to_restore should contain the following:
# {v0/foo : v0,
# v1/foo : v1,
# add/foo : add/foo,
# v2 : v2}
expected_names = [
ema.average_name(v0),
ema.average_name(v1),
ema.average_name(tensor2), v2.op.name
]
if zero_debias:
# vars_to_restore should also contain the following:
# {add/foo/biased: add/foo/biased,
# add/foo/local_step: add/foo/local_step}
expected_names += [
ema.average_name(tensor2) + "/biased",
ema.average_name(tensor2) + "/local_step"
]
self.assertEqual(sorted(expected_names), sorted(vars_to_restore.keys()))
self.assertEqual(ema.average(v0).op.name, ema.average_name(v0))
self.assertEqual(ema.average(v1).op.name, ema.average_name(v1))
self.assertEqual(ema.average(tensor2).op.name, ema.average_name(tensor2))
@test_util.deprecated_graph_mode_only
def testAverageVariablesNames(self):
self.averageVariablesNamesHelper(zero_debias=True)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNamesNoDebias(self):
self.averageVariablesNamesHelper(zero_debias=False)
@test_util.deprecated_graph_mode_only
def averageVariablesNamesRespectScopeHelper(self, zero_debias):
# See discussion on #2740.
with variable_scope.variable_scope("scope1"):
v0 = variables.Variable(10.0, name="v0")
v1 = variables.Variable(30.0, name="v1")
# Add a non-trainable variable.
v2 = variables.Variable(20.0, name="v2", trainable=False)
tensor2 = v0 + v1
with variable_scope.variable_scope("scope2"):
ema = moving_averages.ExponentialMovingAverage(
0.25, zero_debias=zero_debias, name="foo")
self.assertEqual("scope2/scope1/v0/foo", ema.average_name(v0))
self.assertEqual("scope2/scope1/v1/foo", ema.average_name(v1))
self.assertEqual("scope2/scope1/add/foo", ema.average_name(tensor2))
ema.apply([v0, v1, tensor2])
vars_to_restore = ema.variables_to_restore()
# `vars_to_restore` should contain the following:
# {scope2/scope1/v0/foo : v0,
# scope2/scope1/v1/foo : v1,
# scope2/scope1/add/foo : add/foo,
# scope1/v2 : v2}
expected_names = [
ema.average_name(v0),
ema.average_name(v1),
ema.average_name(tensor2), v2.op.name
]
if zero_debias:
# `vars_to_restore` should also contain the following:
# {scope2/scope2/scope1/add/foo/biased: add/foo/biased,
# scope2/scope2/scope1/add/foo/local_step: add/foo/local_step}
sc = "scope2/"
expected_names += [
sc + ema.average_name(tensor2) + "/biased",
sc + ema.average_name(tensor2) + "/local_step"
]
self.assertEqual(sorted(expected_names), sorted(vars_to_restore.keys()))
self.assertEqual(ema.average(v0).op.name, ema.average_name(v0))
self.assertEqual(ema.average(v1).op.name, ema.average_name(v1))
self.assertEqual(ema.average(tensor2).op.name, ema.average_name(tensor2))
@test_util.deprecated_graph_mode_only
def testAverageVariablesNamesRespectScope(self):
self.averageVariablesNamesRespectScopeHelper(zero_debias=True)
@test_util.deprecated_graph_mode_only
def testAverageVariablesNamesRespectScopeNoDebias(self):
self.averageVariablesNamesRespectScopeHelper(zero_debias=False)
@test_util.deprecated_graph_mode_only
def testSubsetAverageVariablesNames(self):
v0 = variables.Variable(10.0, name="v0")
v1 = variables.Variable(30.0, name="v1")
# Add a non-trainable variable.
v2 = variables.Variable(20.0, name="v2", trainable=False)
tensor2 = v0 + v1
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
self.assertEqual("v0/foo_avg", ema.average_name(v0))
self.assertEqual("v1/foo_avg", ema.average_name(v1))
self.assertEqual("add/foo_avg", ema.average_name(tensor2))
vars_to_restore = ema.variables_to_restore([v0, tensor2])
# vars_to_restore should contain the following:
# {v0/foo_avg : v0,
# add/foo_avg : add
# v1 : v1,
# v2 : v2}
self.assertEqual(
sorted(vars_to_restore.keys()),
sorted([
ema.average_name(v0),
ema.average_name(tensor2), v1.op.name, v2.op.name
]))
ema.apply([v0, v1, tensor2])
self.assertEqual(ema.average(v0).op.name, ema.average_name(v0))
self.assertEqual(ema.average(v1).op.name, ema.average_name(v1))
self.assertEqual(ema.average(tensor2).op.name, ema.average_name(tensor2))
def testSubsetAverageVariablesNamesEager(self):
v0 = variables.Variable(10.0, name="v0")
v1 = variables.Variable(30.0, name="v1")
# Add a non-trainable variable.
v2 = variables.Variable(20.0, name="v2", trainable=False)
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
self.assertEqual("v0/foo_avg", ema.average_name(v0))
self.assertEqual("v1/foo_avg", ema.average_name(v1))
vars_to_restore = ema.variables_to_restore([v0, v1, v2])
self.assertAllEqual(
sorted(vars_to_restore.keys()),
sorted([
ema.average_name(v0), ema.average_name(v1), ema.average_name(v2)
]))
ema.apply([v0, v1])
self.assertEqual(ema.average(v0).name[:-len(":0")], ema.average_name(v0))
self.assertEqual(ema.average(v1).name[:-len(":0")], ema.average_name(v1))
@test_util.deprecated_graph_mode_only
def testAverageVariablesDeviceAssignment(self):
with ops.device("/job:dev_v0"):
v0 = variables.Variable(10.0, name="v0")
with ops.device("/job:dev_v1"):
v1 = gen_state_ops.variable(
shape=[1],
dtype=dtypes.float32,
name="v1",
container="",
shared_name="")
v1.set_shape([1])
tensor2 = v0 + v1
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
with ops.device("/job:default"):
ema.apply([v0, v1, tensor2])
self.assertDeviceEqual("/job:dev_v0", ema.average(v0).device)
self.assertDeviceEqual("/job:dev_v1", ema.average(v1).device)
# However, the colocation property is maintained.
self.assertEqual([b"loc:@v1"], ema.average(v1).op.colocation_groups())
self.assertDeviceEqual("/job:default", ema.average(tensor2).device)
def _ExportAndImportGraph(self, graph):
"""Export and import graph into a new graph."""
meta_graph = saver_lib.export_meta_graph(
graph=graph, collection_list=graph.get_all_collection_keys())
graph_copy = ops.Graph()
with graph_copy.as_default():
_ = saver_lib.import_meta_graph(meta_graph)
return graph_copy
@test_util.deprecated_graph_mode_only
def testImportedGraphVariablesToRestore(self):
g = ops.Graph()
with g.as_default():
variables.Variable(10.0, name="v")
# Export and import the graph into a new graph.
g_copy = self._ExportAndImportGraph(g)
with g_copy.as_default():
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
vars_to_restore = ema.variables_to_restore()
# There should only be one variable in vars_to_restore. This is important
# to check because when importing from a GraphDef, TF makes duplicate
# python Variable objects referring to the same underlying variable. We
# need to be sure that two variables referring to the same variable don't
# both get added to vars_to_restore.
self.assertEqual(len(vars_to_restore), 1)
self.assertIn("v/foo_avg", vars_to_restore)
@test_util.deprecated_graph_mode_only
def testCopyXlaSharding(self):
ema = moving_averages.ExponentialMovingAverage(0.25, name="foo_avg")
v = variables.Variable(_Repeat(10.0, 2), name="v")
self.assertIsNone(xla_sharding.get_tensor_sharding(v))
v = xla_sharding.mesh_split(v, np.array([0, 1]), [0], use_sharding_op=False)
self.assertIsNotNone(xla_sharding.get_tensor_sharding(v))
self.evaluate(variables.global_variables_initializer())
ema.apply([v])
avg = ema.average(v)
self.assertEqual(
xla_sharding.get_tensor_sharding(v),
xla_sharding.get_tensor_sharding(avg))
if __name__ == "__main__":
test.main()
| ExponentialMovingAverageTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 137563,
"end": 137722
} | class ____(BinaryExpression[Any]):
"""Represent the class of expressions that are like an "index"
operation."""
inherit_cache = True
| IndexExpression |
python | pytorch__pytorch | torch/quasirandom.py | {
"start": 71,
"end": 7948
} | class ____:
r"""
The :class:`torch.quasirandom.SobolEngine` is an engine for generating
(scrambled) Sobol sequences. Sobol sequences are an example of low
discrepancy quasi-random sequences.
This implementation of an engine for Sobol sequences is capable of
sampling sequences up to a maximum dimension of 21201. It uses direction
numbers from https://web.maths.unsw.edu.au/~fkuo/sobol/ obtained using the
search criterion D(6) up to the dimension 21201. This is the recommended
choice by the authors.
References:
- Art B. Owen. Scrambling Sobol and Niederreiter-Xing points.
Journal of Complexity, 14(4):466-489, December 1998.
- I. M. Sobol. The distribution of points in a cube and the accurate
evaluation of integrals.
Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, 1967.
Args:
dimension (Int): The dimensionality of the sequence to be drawn
scramble (bool, optional): Setting this to ``True`` will produce
scrambled Sobol sequences. Scrambling is
capable of producing better Sobol
sequences. Default: ``False``.
seed (Int, optional): This is the seed for the scrambling. The seed
of the random number generator is set to this,
if specified. Otherwise, it uses a random seed.
Default: ``None``
Examples::
>>> # xdoctest: +SKIP("unseeded random state")
>>> soboleng = torch.quasirandom.SobolEngine(dimension=5)
>>> soboleng.draw(3)
tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.7500, 0.2500, 0.2500, 0.2500, 0.7500]])
"""
MAXBIT = 30
MAXDIM = 21201
def __init__(self, dimension, scramble=False, seed=None):
if dimension > self.MAXDIM or dimension < 1:
raise ValueError(
"Supported range of dimensionality "
f"for SobolEngine is [1, {self.MAXDIM}]"
)
self.seed = seed
self.scramble = scramble
self.dimension = dimension
cpu = torch.device("cpu")
self.sobolstate = torch.zeros(
dimension, self.MAXBIT, device=cpu, dtype=torch.long
)
torch._sobol_engine_initialize_state_(self.sobolstate, self.dimension)
if not self.scramble:
self.shift = torch.zeros(self.dimension, device=cpu, dtype=torch.long)
else:
self._scramble()
self.quasi = self.shift.clone(memory_format=torch.contiguous_format)
self._first_point = (self.quasi / 2**self.MAXBIT).reshape(1, -1)
self.num_generated = 0
def draw(
self,
n: int = 1,
out: Optional[torch.Tensor] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
r"""
Function to draw a sequence of :attr:`n` points from a Sobol sequence.
Note that the samples are dependent on the previous samples. The size
of the result is :math:`(n, dimension)`.
Args:
n (Int, optional): The length of sequence of points to draw.
Default: 1
out (Tensor, optional): The output tensor
dtype (:class:`torch.dtype`, optional): the desired data type of the
returned tensor.
Default: ``None``
"""
if dtype is None:
dtype = torch.get_default_dtype()
if self.num_generated == 0:
if n == 1:
result = self._first_point.to(dtype)
else:
result, self.quasi = torch._sobol_engine_draw(
self.quasi,
n - 1,
self.sobolstate,
self.dimension,
self.num_generated,
dtype=dtype,
)
result = torch.cat((self._first_point.to(dtype), result), dim=-2)
else:
result, self.quasi = torch._sobol_engine_draw(
self.quasi,
n,
self.sobolstate,
self.dimension,
self.num_generated - 1,
dtype=dtype,
)
self.num_generated += n
if out is not None:
out.resize_as_(result).copy_(result)
return out
return result
def draw_base2(
self,
m: int,
out: Optional[torch.Tensor] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
r"""
Function to draw a sequence of :attr:`2**m` points from a Sobol sequence.
Note that the samples are dependent on the previous samples. The size
of the result is :math:`(2**m, dimension)`.
Args:
m (Int): The (base2) exponent of the number of points to draw.
out (Tensor, optional): The output tensor
dtype (:class:`torch.dtype`, optional): the desired data type of the
returned tensor.
Default: ``None``
"""
n = 2**m
total_n = self.num_generated + n
if not (total_n & (total_n - 1) == 0):
raise ValueError(
"The balance properties of Sobol' points require "
f"n to be a power of 2. {self.num_generated} points have been "
f"previously generated, then: n={self.num_generated}+2**{m}={total_n}. "
"If you still want to do this, please use "
"'SobolEngine.draw()' instead."
)
return self.draw(n=n, out=out, dtype=dtype)
def reset(self):
r"""
Function to reset the ``SobolEngine`` to base state.
"""
self.quasi.copy_(self.shift)
self.num_generated = 0
return self
def fast_forward(self, n):
r"""
Function to fast-forward the state of the ``SobolEngine`` by
:attr:`n` steps. This is equivalent to drawing :attr:`n` samples
without using the samples.
Args:
n (Int): The number of steps to fast-forward by.
"""
if self.num_generated == 0:
torch._sobol_engine_ff_(
self.quasi, n - 1, self.sobolstate, self.dimension, self.num_generated
)
else:
torch._sobol_engine_ff_(
self.quasi, n, self.sobolstate, self.dimension, self.num_generated - 1
)
self.num_generated += n
return self
def _scramble(self):
g: Optional[torch.Generator] = None
if self.seed is not None:
g = torch.Generator()
g.manual_seed(self.seed)
cpu = torch.device("cpu")
# Generate shift vector
shift_ints = torch.randint(
2, (self.dimension, self.MAXBIT), device=cpu, generator=g
)
self.shift = torch.mv(
shift_ints, torch.pow(2, torch.arange(0, self.MAXBIT, device=cpu))
)
# Generate lower triangular matrices (stacked across dimensions)
ltm_dims = (self.dimension, self.MAXBIT, self.MAXBIT)
ltm = torch.randint(2, ltm_dims, device=cpu, generator=g).tril()
torch._sobol_engine_scramble_(self.sobolstate, ltm, self.dimension)
def __repr__(self):
fmt_string = [f"dimension={self.dimension}"]
if self.scramble:
fmt_string += ["scramble=True"]
if self.seed is not None:
fmt_string += [f"seed={self.seed}"]
return self.__class__.__name__ + "(" + ", ".join(fmt_string) + ")"
| SobolEngine |
python | pytorch__pytorch | torch/ao/ns/_numeric_suite_fx.py | {
"start": 10013,
"end": 41390
} | class ____(quantize_fx.QuantizationTracer):
"""
Just like a regular FX quantization tracer, but treats observers and fake_quantize
modules as leaf modules.
"""
def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
# fmt: off
"""
""" # blank docblock to make autodoc happy
# fmt: on
if isinstance(m, torch.ao.quantization.ObserverBase):
return True
elif isinstance(m, torch.ao.quantization.FakeQuantizeBase):
return True
return super().is_leaf_module(m, module_qualified_name)
def _extract_weights_one_model(
model_name: str,
model: GraphModule,
nodes_and_names_to_instrument: list[tuple[Node, str]],
results: NSResultsType,
op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
| None = None,
) -> None:
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx._extract_weights_one_model"
)
for node, ref_name in nodes_and_names_to_instrument:
res_type = NSSingleResultValuesType.WEIGHT.value
extracted_weight = extract_weight_from_node(
node, model, op_to_type_to_weight_extraction_fn
)
if extracted_weight:
if ref_name not in results:
results[ref_name] = {res_type: {}}
results[ref_name][res_type][model_name] = [extracted_weight]
def _extract_weights_impl(
model_name_a: str,
gm_a: GraphModule,
model_name_b: str,
gm_b: GraphModule,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
| None = None,
) -> NSResultsType:
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx._extract_weights_impl"
)
matched_subgraph_pairs = get_matching_subgraph_pairs(
gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
)
# split the subgraph pairs into one data structure for each model
nodes_and_names_to_instrument_a: list[tuple[Node, str]] = []
nodes_and_names_to_instrument_b: list[tuple[Node, str]] = []
for match_name, match in matched_subgraph_pairs.items():
subgraph_a, subgraph_b = match
nodes_and_names_to_instrument_a.append((subgraph_a.base_op_node, match_name))
nodes_and_names_to_instrument_b.append((subgraph_b.base_op_node, match_name))
# populate the results, one model at a time
results: NSResultsType = {}
_extract_weights_one_model(
model_name_a,
gm_a,
nodes_and_names_to_instrument_a,
results,
op_to_type_to_weight_extraction_fn,
)
_extract_weights_one_model(
model_name_b,
gm_b,
nodes_and_names_to_instrument_b,
results,
op_to_type_to_weight_extraction_fn,
)
# fill in missing fqn entries
maybe_add_missing_fqns(results)
# rekey on names of nodes in gm_b
results = rekey_logger_info_on_node_name_of_model(results, model_name_b)
return results
def extract_weights(
model_name_a: str,
model_a: nn.Module,
model_name_b: str,
model_b: nn.Module,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
| None = None,
) -> NSResultsType:
"""
Extract weights from model A and model B, and return a comparison.
Args:
model_name_a: string name of model A to use in results
model_a: model A
model_name_b: string name of model B to use in results
model_b: model B
base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
unmatchable_types_map: optional override of unmatchable types, subject to change
op_to_type_to_weight_extraction_fn: optional override of function which extracts weight
from a type, subject to change
Return:
NSResultsType, containing the weight comparisons
"""
torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_weights")
if base_name_to_sets_of_related_ops is None:
base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
# TODO(future PR): expose these
skipped_module_names: list[str] = []
skipped_module_classes: list[Callable] = []
tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
gm_a = GraphModule(model_a, tracer_a.trace(model_a))
maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
model_a, "node_name_to_scope"
)
if maybe_model_a_node_name_to_scope is not None:
gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
gm_b = GraphModule(model_b, tracer_b.trace(model_b))
maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
model_b, "node_name_to_scope"
)
if maybe_model_b_node_name_to_scope is not None:
gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
return _extract_weights_impl(
model_name_a,
gm_a,
model_name_b,
gm_b,
base_name_to_sets_of_related_ops,
unmatchable_types_map,
op_to_type_to_weight_extraction_fn,
)
def _add_loggers_one_model(
model_name: str,
model: GraphModule,
nodes_and_names_to_instrument_inputs: list[tuple[Node, str, str]],
nodes_and_names_to_instrument_outputs: list[tuple[Node, str, str]],
logger_cls: Callable,
) -> nn.Module:
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx._add_loggers_one_model"
)
# TODO(future PR): do not observe nodes we do not care
# about (both fp32, denylist, etc)
node_to_instrument_inputs_to_ref_name: dict[Node, tuple[str, str]] = {}
node_to_instrument_outputs_to_ref_name: dict[Node, tuple[str, str]] = {}
for node, ref_name, ref_node_type in nodes_and_names_to_instrument_inputs:
node_to_instrument_inputs_to_ref_name[node] = (ref_name, ref_node_type)
for node, ref_name, ref_node_type in nodes_and_names_to_instrument_outputs:
node_to_instrument_outputs_to_ref_name[node] = (ref_name, ref_node_type)
model = add_loggers_to_model(
model,
node_to_instrument_inputs_to_ref_name,
node_to_instrument_outputs_to_ref_name,
logger_cls,
model_name,
)
return model
def _add_loggers_impl(
name_a: str,
gm_a: GraphModule,
name_b: str,
gm_b: GraphModule,
logger_cls: Callable,
should_log_inputs: bool,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
) -> tuple[nn.Module, nn.Module]:
torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_loggers_impl")
matched_subgraph_pairs = get_matching_subgraph_pairs(
gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
)
nodes_and_names_to_instrument_inputs_a = []
nodes_and_names_to_instrument_inputs_b = []
nodes_and_names_to_instrument_outputs_a = []
nodes_and_names_to_instrument_outputs_b = []
for match_name, (subgraph_a, subgraph_b) in matched_subgraph_pairs.items():
ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
# Note: for matching inputs we use start_node, such as observing
# the input of linear in linear-relu
if should_log_inputs:
nodes_and_names_to_instrument_inputs_a.append(
(subgraph_a.start_node, match_name, ref_node_type_a)
)
nodes_and_names_to_instrument_inputs_b.append(
(subgraph_b.start_node, match_name, ref_node_type_b)
)
# Note: for matching activations we always use end_node,
# such as observing the output of relu in linear-relu
nodes_and_names_to_instrument_outputs_a.append(
(subgraph_a.end_node, match_name, ref_node_type_a)
)
nodes_and_names_to_instrument_outputs_b.append(
(subgraph_b.end_node, match_name, ref_node_type_b)
)
new_model_a = _add_loggers_one_model(
name_a,
gm_a,
nodes_and_names_to_instrument_inputs_a,
nodes_and_names_to_instrument_outputs_a,
logger_cls,
)
new_model_b = _add_loggers_one_model(
name_b,
gm_b,
nodes_and_names_to_instrument_inputs_b,
nodes_and_names_to_instrument_outputs_b,
logger_cls,
)
return (new_model_a, new_model_b)
def add_loggers(
name_a: str,
model_a: nn.Module,
name_b: str,
model_b: nn.Module,
logger_cls: Callable,
should_log_inputs: bool = False,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
) -> tuple[nn.Module, nn.Module]:
"""
Instrument model A and model B with loggers.
Args:
name_a: string name of model A to use in results
model_a: model A
name_b: string name of model B to use in results
model_b: model B
logger_cls: class of Logger to use
base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
unmatchable_types_map: optional override of unmatchable types, subject to change
Return:
Returns a tuple of (model_a_with_loggers, model_b_with_loggers). Modifies both models inplace.
"""
torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.add_loggers")
# TODO(future PR): expose these
skipped_module_names: list[str] = []
skipped_module_classes: list[Callable] = []
tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
gm_a = GraphModule(model_a, tracer_a.trace(model_a))
maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
model_a, "node_name_to_scope"
)
if maybe_model_a_node_name_to_scope is not None:
gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
gm_b = GraphModule(model_b, tracer_b.trace(model_b))
maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
model_b, "node_name_to_scope"
)
if maybe_model_b_node_name_to_scope is not None:
gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
return _add_loggers_impl(
name_a,
gm_a,
name_b,
gm_b,
logger_cls,
should_log_inputs=should_log_inputs,
base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
unmatchable_types_map=unmatchable_types_map,
)
def _extract_logger_info_one_model(
model: nn.Module,
results: NSResultsType,
logger_cls: Callable,
) -> None:
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx._extract_logger_info_one_model"
)
for _gm_name, mod in model.named_modules():
# TODO(future PR): better check when scripted
is_logger = isinstance(mod, logger_cls) or ( # type: ignore[arg-type]
isinstance(mod, torch.jit.RecursiveScriptModule)
and mod.original_name == "OutputLogger"
)
if is_logger:
key = mod.ref_name
if key not in results:
results[key] = {}
if mod.model_name in results[key]:
raise AssertionError(f"{mod.model_name} is already present in results")
if mod.results_type not in results[key]:
results[key][mod.results_type] = {}
if mod.model_name not in results[key][mod.results_type]:
results[key][mod.results_type][mod.model_name] = []
stats_to_use = mod.stats
if len(mod.stats_rnn) > 0:
stats_to_use = mod.stats_rnn
data = {
"type": mod.results_type,
"values": stats_to_use,
"ref_node_name": mod.ref_node_name,
"ref_node_target_type": mod.ref_node_target_type,
"prev_node_name": mod.prev_node_name,
"prev_node_target_type": mod.prev_node_target_type,
"index_within_arg": mod.index_within_arg,
"index_of_arg": mod.index_of_arg,
"fqn": mod.fqn,
"qconfig_str": mod.qconfig_str,
}
if hasattr(mod, "comparisons"):
data["comparisons"] = mod.comparisons
data["comparison_fn_name"] = mod.comparison_fn_name
else:
data["comparisons"] = []
data["comparison_fn_name"] = ""
results[key][mod.results_type][mod.model_name].append(data)
# ensure the list stays sorted
results[key][mod.results_type][mod.model_name].sort(
key=lambda res: f"{res['index_of_arg']}:{res['index_within_arg']}"
)
# TODO(future PR): align on naming
# this is equivalent of just the comparison extraction part of `ns.compare_model_outputs`
def extract_logger_info(
model_a: nn.Module,
model_b: nn.Module,
logger_cls: Callable,
model_name_to_use_for_layer_names: str,
) -> NSResultsType:
"""
Traverse all loggers in `model_a` and `model_b`, and extract the logged
information.
Args:
model_a: model A
model_b: model B
logger_cls: class of Logger to use
model_name_to_use_for_layer_names: string name of model to use for
layer names in the output
Return:
NSResultsType, containing the logged comparisons
"""
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx.extract_logger_info"
)
results: NSResultsType = {}
for model in (model_a, model_b):
_extract_logger_info_one_model(model, results, logger_cls)
# fill in missing fqn entries
maybe_add_missing_fqns(results)
# rekey on the name of model b
results = rekey_logger_info_on_node_name_of_model(
results, model_name_to_use_for_layer_names
)
return results
def _add_shadow_loggers_impl(
name_a: str,
gm_a: GraphModule,
name_b: str,
gm_b: GraphModule,
logger_cls: Callable,
should_log_inputs: bool,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
) -> nn.Module:
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx._add_shadow_loggers_impl"
)
matched_subgraph_pairs = get_matching_subgraph_pairs(
gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
)
gm_a_shadows_b = create_a_shadows_b(
name_a,
gm_a,
name_b,
gm_b,
matched_subgraph_pairs,
logger_cls,
should_log_inputs=should_log_inputs,
node_type_to_io_type_map=node_type_to_io_type_map,
)
return gm_a_shadows_b
def add_shadow_loggers(
name_a: str,
model_a: nn.Module,
name_b: str,
model_b: nn.Module,
logger_cls: Callable,
should_log_inputs: bool = False,
base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
) -> nn.Module:
"""
Instrument model A and model B with shadow loggers.
Args:
name_a: string name of model A to use in results
model_a: model A
name_b: string name of model B to use in results
model_b: model B
logger_cls: class of Logger to use
should_log_inputs: whether to log inputs
base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
unmatchable_types_map: optional override of unmatchable types, subject to change
"""
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx.add_shadow_loggers"
)
# TODO(future PR): expose these
skipped_module_names: list[str] = []
skipped_module_classes: list[Callable] = []
tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
gm_a = GraphModule(model_a, tracer_a.trace(model_a))
maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
model_a, "node_name_to_scope"
)
if maybe_model_a_node_name_to_scope is not None:
gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
gm_b = GraphModule(model_b, tracer_b.trace(model_b))
maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
model_b, "node_name_to_scope"
)
if maybe_model_b_node_name_to_scope is not None:
gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
return _add_shadow_loggers_impl(
name_a,
gm_a,
name_b,
gm_b,
logger_cls,
should_log_inputs=should_log_inputs,
base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
node_type_to_io_type_map=node_type_to_io_type_map,
unmatchable_types_map=unmatchable_types_map,
)
def extract_shadow_logger_info(
model_a_shadows_b: nn.Module,
logger_cls: Callable,
model_name_to_use_for_layer_names: str,
) -> NSResultsType:
"""
Traverse all loggers in a shadow model, and extract the logged
information.
Args:
model_a_shadows_b: shadow model
logger_cls: class of Logger to use
model_name_to_use_for_layer_names: string name of model to use for
layer names in the output
Return:
NSResultsType, containing the logged comparisons
"""
torch._C._log_api_usage_once(
"quantization_api._numeric_suite_fx.extract_shadow_logger_info"
)
results: NSResultsType = collections.defaultdict(dict)
_extract_logger_info_one_model(model_a_shadows_b, results, logger_cls)
# fill in missing fqn entries
maybe_add_missing_fqns(results)
# rekey on the name of model b
results = rekey_logger_info_on_node_name_of_model(
results, model_name_to_use_for_layer_names
)
return dict(results)
def extend_logger_results_with_comparison(
results: NSResultsType,
model_name_1: str,
model_name_2: str,
comparison_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
comparison_name: str,
) -> None:
"""
Compares the logged values from `model_name_2` against the corresponding
values in `model_name_1`, using `comparison_fn`. Records the result
in `model_name_2`'s results under `comparison_name`. Modifies `results` inplace.
Args:
results: the result data structure from `extract_logger_info` or
`extract_shadow_logger_info`.
model_name_1: string name of model 1
model_name_2: string name of model 2
comparison_fn: function to compare two Tensors
comparison_name: string name of model to use for
layer names in the output
"""
for results_type_to_results in results.values():
for model_name_to_results in results_type_to_results.values():
if model_name_1 not in model_name_to_results:
raise AssertionError(f"{model_name_1} not found in results")
if model_name_2 not in model_name_to_results:
raise AssertionError(f"{model_name_2} not found in results")
results_1 = model_name_to_results[model_name_1]
results_2 = model_name_to_results[model_name_2]
for result_2 in results_2:
index_within_arg_2 = result_2["index_within_arg"]
index_of_arg_2 = result_2["index_of_arg"]
# find corresponding result_1
result_1 = None
for cur_result_1 in results_1:
index_within_arg_1 = cur_result_1["index_within_arg"]
index_of_arg_1 = cur_result_1["index_of_arg"]
if (index_within_arg_1 == index_within_arg_2) and (
index_of_arg_1 == index_of_arg_2
):
result_1 = cur_result_1
break
if result_1 is None:
raise AssertionError("Expected result_1 to be not None")
values_1 = result_1["values"]
values_2 = result_2["values"]
result_2[comparison_name] = []
for value_1, value_2 in zip(values_1, values_2):
comparison_result = comparison_fn(value_1, value_2)
result_2[comparison_name].append(comparison_result)
def prepare_n_shadows_model(
model: torch.nn.Module,
example_inputs: Any,
qconfig_multi_mapping: QConfigMultiMapping,
backend_config: BackendConfig,
custom_prepare_fn: Callable | None = None,
custom_prepare_kwargs: dict[str, Any] | None = None,
custom_tracer: Any = None,
) -> GraphModule:
"""
Given a model with a graph with M ops such as
args_kwargs_m -> op_m -> output_m
And a set of N qconfigs for each op, creates a new model, with
each of the subgraph of `op_m` transformed into
.. code::
|---------> op_m_n -> log_m_n
| /
args_kwargs_m ---------> op_m -> log_m_0
Where op_m_n is op_m wrapped in a submodule and transformed with
qconfig_n, and its inner graph looks like
.. code::
args_m -------- op_m_prepared_with_qconfig_n -> out_m_n
/
kwargs_m ---
This is useful for testing different quantization of multiple layers in
a single pass through the model.
High level TODOs for future PRs:
* figure out a better way to name the output structure
* return a results data structure instead of printing it out
* add examples to docblocks
"""
if custom_tracer is None:
tracer = quantize_fx.QuantizationTracer([], [])
else:
tracer = custom_tracer
mt = torch.fx.GraphModule(model, tracer.trace(model))
# this is necessary to ensure logger FQNs get populated
mt._node_name_to_scope = tracer.node_name_to_scope # type: ignore[assignment]
# run example input propagation, we need this to call prepare_fx on
# individual subgraphs
output_prop = OutputProp(mt)
output_prop.propagate(*example_inputs)
# Find the set of subgraphs in the original graph which we need to
# consider.
modules = dict(mt.named_modules(remove_duplicate=False))
patterns = _get_pattern_to_quantize_handlers(backend_config)
root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
standalone_module_names: list[str] = []
standalone_module_classes: list[type] = []
custom_module_classes: list[type] = []
matches = _find_matches(
mt.graph,
modules,
patterns,
root_node_getter_mapping,
standalone_module_names,
standalone_module_classes,
custom_module_classes,
)
subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
# generate node to qconfig for each subgraph
# TODO(future PR): deduplicate repeating entries
list_of_node_name_to_qconfig: list[dict[str, QConfigAny]] = []
for qconfig_mapping in qconfig_multi_mapping.qconfig_mappings_list:
node_name_to_qconfig = _generate_node_name_to_qconfig(
mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
)
list_of_node_name_to_qconfig.append(node_name_to_qconfig)
# For each region in the model, do the following:
# For each qconfig for that region, do the following:
# 1. create a copy of the region wrapped in a module
# 2. pass original args, original kwargs, and expected output to module
# 3. add an output comparison logger and hook it up to compare
# actual output to expected output
# 4. run `prepare_fx` on the module
for subgraph_idx, (match_name, nodes_in_this_subgraph) in enumerate(
subgraphs_dedup.items()
):
create_n_transformed_and_logged_copies_of_subgraph(
mt,
subgraph_idx,
match_name,
nodes_in_this_subgraph,
qconfig_multi_mapping.qconfig_mappings_list,
list_of_node_name_to_qconfig,
custom_prepare_fn,
custom_prepare_kwargs, # type: ignore[arg-type]
)
return mt
# TODO(future PR): we should rethink the names of all the PNP APIs
def _prepare_n_shadows_add_loggers_model(
model: torch.nn.Module,
example_inputs: Any,
qconfig_mapping: QConfigMapping,
backend_config: BackendConfig,
) -> torch.nn.Module:
r"""
Note: this API is not recommended for wide usage, it is only
provided for customers who need to migrate from the `add_loggers`
API.
This creates a model which provides logging for the following
problem: if we quantize `model` with `qconfig_mapping` and feed
the same input through both models, log the comparisons of
corresponding intermediate layers.
The problem is solved with a single model. Specifically, we
partition `model` into N subgraphs, create a copy of each relevant
subgraph, wrap it in a module, apply the quantization API to that
module, and hook up loggers to measure the comparisons.
Example starting graph:
x0 -> op0 -> x1 -> op1 -> x2
Example config: quantize op0 to int8, do nothing to op1.
The following graph will be created:
.. code::
x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
\ \ \ # noqa: W605
---> op0_1 -> x1_1 ----> clog -> op1_0 -> x2_1 ----> clog
Where op0_0 is op0, op0_1 is op0 wrapped in a submodule and quantized
to int8, op1_0 is op1 (appearing in the graph twice), log is a logger,
and clog is a comparison logger.
"""
tracer = quantize_fx.QuantizationTracer([], [])
mt = torch.fx.GraphModule(model, tracer.trace(model))
# this is necessary to ensure logger FQNs get populated
mt._node_name_to_scope = tracer.node_name_to_scope # type: ignore[assignment]
# run example input propagation, we need this to call prepare_fx on
# individual subgraphs
output_prop = OutputProp(mt)
output_prop.propagate(*example_inputs)
# Find the set of subgraphs in the original graph which we need to
# consider.
modules = dict(mt.named_modules(remove_duplicate=False))
patterns = _get_pattern_to_quantize_handlers(backend_config)
root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
standalone_module_names: list[str] = []
standalone_module_classes: list[type] = []
custom_module_classes: list[type] = []
matches = _find_matches(
mt.graph,
modules,
patterns,
root_node_getter_mapping,
standalone_module_names,
standalone_module_classes,
custom_module_classes,
)
subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
# generate node to qconfig for each subgraph
node_name_to_qconfig = _generate_node_name_to_qconfig(
mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
)
# Now, mutate the graph to be the add_loggers graph with propagation
# error.
create_add_loggers_graph(mt, subgraphs_dedup, qconfig_mapping, node_name_to_qconfig)
return mt
# TODO(future PR): we should rethink the names of all the PNP APIs
def _n_shadows_compare_weights(
model: torch.nn.Module,
example_inputs: Any,
qconfig_mapping: QConfigMapping,
backend_config: BackendConfig,
) -> NSResultsType:
"""
Note: this API is not recommended for wide usage, it is only
provided for customers who need to migrate from the `add_loggers`
API.
"""
qconfig_multi_mapping = QConfigMultiMapping.from_list_qconfig_mapping(
[qconfig_mapping]
)
mp = prepare_n_shadows_model(
model, example_inputs, qconfig_multi_mapping, backend_config
)
# passing inputs through the model is necessary to populate
# observers which observe weights with real values
mp(*example_inputs)
mq = convert_n_shadows_model(mp)
weight_comparison = extract_weight_comparison(mq)
return weight_comparison
# TODO(future PR): consider aligning API signature with other similar quantization
# functions (enable_fake_quant, etc)
def loggers_set_enabled(model: torch.nn.Module, enabled: bool) -> None:
"""
Sets the `enabled` setting on a `model`'s loggers
"""
for _, child in model.named_modules():
if isinstance(child, OutputLogger):
child.enabled = enabled
# TODO(future PR): consider aligning API signature with other similar quantization
# functions (enable_fake_quant, etc)
def loggers_set_save_activations(
model: torch.nn.Module,
save_activations: bool,
) -> None:
"""
Sets the `save_activations` setting on a `model`'s loggers
"""
for _name, child in model.named_modules():
if isinstance(child, OutputLogger):
child.save_activations = save_activations
def convert_n_shadows_model(
model: GraphModule,
custom_convert_fn: Callable | None = None,
custom_convert_kwargs: dict[str, Any] | None = None,
) -> GraphModule:
"""
Given a model from `prepare_n_shadows_model`, runs `convert_fx`
on each shadow submodule.
"""
for node in model.graph.nodes:
# TODO(future PR): consider matching in a safer way than
# node name string match
if node.name.startswith(SHADOW_WRAPPER_NODE_NAME_PREFIX):
orig_mod = getattr(model, node.name)
if custom_convert_fn is None:
converted_mod = torch.ao.quantization.quantize_fx.convert_fx(orig_mod)
else:
if custom_convert_kwargs is None:
custom_convert_kwargs = {}
converted_mod = custom_convert_fn(orig_mod, **custom_convert_kwargs)
setattr(model, node.name, converted_mod)
return model
def extract_results_n_shadows_model(model: torch.nn.Module) -> NSResultsType:
"""
Extracts logger results from `model`.
"""
results: NSResultsType = {}
_extract_logger_info_one_model(model, results, OutputLogger)
return results
def print_comparisons_n_shadows_model(results: NSResultsType) -> None:
"""
Prints a summary of extracted `results`.
"""
results_grouped = group_results_by_subgraph(results)
results_comparison = create_results_comparison(results_grouped)
print_n_shadows_summary(results_comparison)
| NSTracer |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_csv.py | {
"start": 229,
"end": 30093
} | class ____:
def test_to_csv_with_single_column(self, temp_file):
# see gh-18676, https://bugs.python.org/issue32255
#
# Python's CSV library adds an extraneous '""'
# before the newline when the NaN-value is in
# the first row. Otherwise, only the newline
# character is added. This behavior is inconsistent
# and was patched in https://bugs.python.org/pull_request4672.
df1 = DataFrame([None, 1])
expected1 = """\
""
1.0
"""
df1.to_csv(temp_file, header=None, index=None)
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected1
df2 = DataFrame([1, None])
expected2 = """\
1.0
""
"""
df2.to_csv(temp_file, header=None, index=None)
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected2
def test_to_csv_default_encoding(self, temp_file):
# GH17097
df = DataFrame({"col": ["AAAAA", "ÄÄÄÄÄ", "ßßßßß", "聞聞聞聞聞"]})
# the default to_csv encoding is uft-8.
df.to_csv(temp_file)
tm.assert_frame_equal(pd.read_csv(temp_file, index_col=0), df)
def test_to_csv_quotechar(self, temp_file):
df = DataFrame({"col": [1, 2]})
expected = """\
"","col"
"0","1"
"1","2"
"""
df.to_csv(temp_file, quoting=1) # 1=QUOTE_ALL
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
expected = """\
$$,$col$
$0$,$1$
$1$,$2$
"""
df.to_csv(temp_file, quoting=1, quotechar="$")
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
with pytest.raises(TypeError, match="quotechar"):
df.to_csv(temp_file, quoting=1, quotechar=None)
def test_to_csv_doublequote(self, temp_file):
df = DataFrame({"col": ['a"a', '"bb"']})
expected = '''\
"","col"
"0","a""a"
"1","""bb"""
'''
df.to_csv(temp_file, quoting=1, doublequote=True) # QUOTE_ALL
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
with pytest.raises(Error, match="escapechar"):
df.to_csv(temp_file, doublequote=False) # no escapechar set
def test_to_csv_escapechar(self, temp_file):
df = DataFrame({"col": ['a"a', '"bb"']})
expected = """\
"","col"
"0","a\\"a"
"1","\\"bb\\""
"""
df.to_csv(temp_file, quoting=1, doublequote=False, escapechar="\\")
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
df = DataFrame({"col": ["a,a", ",bb,"]})
expected = """\
,col
0,a\\,a
1,\\,bb\\,
"""
df.to_csv(temp_file, quoting=3, escapechar="\\") # QUOTE_NONE
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
def test_csv_to_string(self):
df = DataFrame({"col": [1, 2]})
expected_rows = [",col", "0,1", "1,2"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv() == expected
def test_to_csv_decimal(self):
# see gh-781
df = DataFrame({"col1": [1], "col2": ["a"], "col3": [10.1]})
expected_rows = [",col1,col2,col3", "0,1,a,10.1"]
expected_default = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv() == expected_default
expected_rows = [";col1;col2;col3", "0;1;a;10,1"]
expected_european_excel = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv(decimal=",", sep=";") == expected_european_excel
expected_rows = [",col1,col2,col3", "0,1,a,10.10"]
expected_float_format_default = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv(float_format="%.2f") == expected_float_format_default
expected_rows = [";col1;col2;col3", "0;1;a;10,10"]
expected_float_format = tm.convert_rows_list_to_csv_str(expected_rows)
assert (
df.to_csv(decimal=",", sep=";", float_format="%.2f")
== expected_float_format
)
# see gh-11553: testing if decimal is taken into account for '0.0'
df = DataFrame({"a": [0, 1.1], "b": [2.2, 3.3], "c": 1})
expected_rows = ["a,b,c", "0^0,2^2,1", "1^1,3^3,1"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv(index=False, decimal="^") == expected
# same but for an index
assert df.set_index("a").to_csv(decimal="^") == expected
# same for a multi-index
assert df.set_index(["a", "b"]).to_csv(decimal="^") == expected
def test_to_csv_float_format(self):
# testing if float_format is taken into account for the index
# GH 11553
df = DataFrame({"a": [0, 1], "b": [2.2, 3.3], "c": 1})
expected_rows = ["a,b,c", "0,2.20,1", "1,3.30,1"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.set_index("a").to_csv(float_format="%.2f") == expected
# same for a multi-index
assert df.set_index(["a", "b"]).to_csv(float_format="%.2f") == expected
def test_to_csv_na_rep(self):
# see gh-11553
#
# Testing if NaN values are correctly represented in the index.
df = DataFrame({"a": [0, np.nan], "b": [0, 1], "c": [2, 3]})
expected_rows = ["a,b,c", "0.0,0,2", "_,1,3"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.set_index("a").to_csv(na_rep="_") == expected
assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected
# now with an index containing only NaNs
df = DataFrame({"a": np.nan, "b": [0, 1], "c": [2, 3]})
expected_rows = ["a,b,c", "_,0,2", "_,1,3"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.set_index("a").to_csv(na_rep="_") == expected
assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected
# check if na_rep parameter does not break anything when no NaN
df = DataFrame({"a": 0, "b": [0, 1], "c": [2, 3]})
expected_rows = ["a,b,c", "0,0,2", "0,1,3"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.set_index("a").to_csv(na_rep="_") == expected
assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected
csv = pd.Series(["a", pd.NA, "c"]).to_csv(na_rep="ZZZZZ")
expected = tm.convert_rows_list_to_csv_str([",0", "0,a", "1,ZZZZZ", "2,c"])
assert expected == csv
def test_to_csv_na_rep_nullable_string(self, nullable_string_dtype):
# GH 29975
# Make sure full na_rep shows up when a dtype is provided
expected = tm.convert_rows_list_to_csv_str([",0", "0,a", "1,ZZZZZ", "2,c"])
csv = pd.Series(["a", pd.NA, "c"], dtype=nullable_string_dtype).to_csv(
na_rep="ZZZZZ"
)
assert expected == csv
def test_to_csv_date_format(self):
# GH 10209
df_sec = DataFrame({"A": pd.date_range("20130101", periods=5, freq="s")})
df_day = DataFrame({"A": pd.date_range("20130101", periods=5, freq="D")})
expected_rows = [
",A",
"0,2013-01-01 00:00:00",
"1,2013-01-01 00:00:01",
"2,2013-01-01 00:00:02",
"3,2013-01-01 00:00:03",
"4,2013-01-01 00:00:04",
]
expected_default_sec = tm.convert_rows_list_to_csv_str(expected_rows)
assert df_sec.to_csv() == expected_default_sec
expected_rows = [
",A",
"0,2013-01-01 00:00:00",
"1,2013-01-02 00:00:00",
"2,2013-01-03 00:00:00",
"3,2013-01-04 00:00:00",
"4,2013-01-05 00:00:00",
]
expected_ymdhms_day = tm.convert_rows_list_to_csv_str(expected_rows)
assert df_day.to_csv(date_format="%Y-%m-%d %H:%M:%S") == expected_ymdhms_day
expected_rows = [
",A",
"0,2013-01-01",
"1,2013-01-01",
"2,2013-01-01",
"3,2013-01-01",
"4,2013-01-01",
]
expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows)
assert df_sec.to_csv(date_format="%Y-%m-%d") == expected_ymd_sec
expected_rows = [
",A",
"0,2013-01-01",
"1,2013-01-02",
"2,2013-01-03",
"3,2013-01-04",
"4,2013-01-05",
]
expected_default_day = tm.convert_rows_list_to_csv_str(expected_rows)
assert df_day.to_csv() == expected_default_day
assert df_day.to_csv(date_format="%Y-%m-%d") == expected_default_day
# see gh-7791
#
# Testing if date_format parameter is taken into account
# for multi-indexed DataFrames.
df_sec["B"] = 0
df_sec["C"] = 1
expected_rows = ["A,B,C", "2013-01-01,0,1.0"]
expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows)
df_sec_grouped = df_sec.groupby([pd.Grouper(key="A", freq="1h"), "B"])
assert df_sec_grouped.mean().to_csv(date_format="%Y-%m-%d") == expected_ymd_sec
def test_to_csv_different_datetime_formats(self):
# GH#21734
df = DataFrame(
{
"date": pd.to_datetime("1970-01-01"),
"datetime": pd.date_range("1970-01-01", periods=2, freq="h"),
}
)
expected_rows = [
"date,datetime",
"1970-01-01,1970-01-01 00:00:00",
"1970-01-01,1970-01-01 01:00:00",
]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert df.to_csv(index=False) == expected
def test_to_csv_date_format_in_categorical(self):
# GH#40754
ser = pd.Series(pd.to_datetime(["2021-03-27", pd.NaT], format="%Y-%m-%d"))
ser = ser.astype("category")
expected = tm.convert_rows_list_to_csv_str(["0", "2021-03-27", '""'])
assert ser.to_csv(index=False) == expected
ser = pd.Series(
pd.date_range(
start="2021-03-27", freq="D", periods=1, tz="Europe/Berlin"
).append(pd.DatetimeIndex([pd.NaT]))
)
ser = ser.astype("category")
assert ser.to_csv(index=False, date_format="%Y-%m-%d") == expected
def test_to_csv_float_ea_float_format(self):
# GH#45991
df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})
df["a"] = df["a"].astype("Float64")
result = df.to_csv(index=False, float_format="%.5f")
expected = tm.convert_rows_list_to_csv_str(
["a,b", "1.10000,c", "2.02000,c", ",c", "6.00001,c"]
)
assert result == expected
def test_to_csv_float_ea_no_float_format(self):
# GH#45991
df = DataFrame({"a": [1.1, 2.02, pd.NA, 6.000006], "b": "c"})
df["a"] = df["a"].astype("Float64")
result = df.to_csv(index=False)
expected = tm.convert_rows_list_to_csv_str(
["a,b", "1.1,c", "2.02,c", ",c", "6.000006,c"]
)
assert result == expected
def test_to_csv_multi_index(self):
# see gh-6618
df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]))
exp_rows = [",1", ",2", "0,1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv() == exp
exp_rows = ["1", "2", "1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv(index=False) == exp
df = DataFrame(
[1],
columns=pd.MultiIndex.from_arrays([[1], [2]]),
index=pd.MultiIndex.from_arrays([[1], [2]]),
)
exp_rows = [",,1", ",,2", "1,2,1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv() == exp
exp_rows = ["1", "2", "1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv(index=False) == exp
df = DataFrame([1], columns=pd.MultiIndex.from_arrays([["foo"], ["bar"]]))
exp_rows = [",foo", ",bar", "0,1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv() == exp
exp_rows = ["foo", "bar", "1"]
exp = tm.convert_rows_list_to_csv_str(exp_rows)
assert df.to_csv(index=False) == exp
@pytest.mark.parametrize(
"ind,expected",
[
(
pd.MultiIndex(levels=[[1.0]], codes=[[0]], names=["x"]),
"x,data\n1.0,1\n",
),
(
pd.MultiIndex(
levels=[[1.0], [2.0]], codes=[[0], [0]], names=["x", "y"]
),
"x,y,data\n1.0,2.0,1\n",
),
],
)
def test_to_csv_single_level_multi_index(self, ind, expected, frame_or_series):
# see gh-19589
obj = frame_or_series(pd.Series([1], ind, name="data"))
result = obj.to_csv(lineterminator="\n", header=True)
assert result == expected
def test_to_csv_string_array_ascii(self, temp_file):
# GH 10813
str_array = [{"names": ["foo", "bar"]}, {"names": ["baz", "qux"]}]
df = DataFrame(str_array)
expected_ascii = """\
,names
0,"['foo', 'bar']"
1,"['baz', 'qux']"
"""
df.to_csv(temp_file, encoding="ascii")
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected_ascii
def test_to_csv_string_array_utf8(self, temp_file):
# GH 10813
str_array = [{"names": ["foo", "bar"]}, {"names": ["baz", "qux"]}]
df = DataFrame(str_array)
expected_utf8 = """\
,names
0,"['foo', 'bar']"
1,"['baz', 'qux']"
"""
df.to_csv(temp_file, encoding="utf-8")
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected_utf8
def test_to_csv_string_with_lf(self, temp_file):
# GH 20353
data = {"int": [1, 2, 3], "str_lf": ["abc", "d\nef", "g\nh\n\ni"]}
df = DataFrame(data)
# case 1: The default line terminator(=os.linesep)(PR 21406)
os_linesep = os.linesep.encode("utf-8")
expected_noarg = (
b"int,str_lf"
+ os_linesep
+ b"1,abc"
+ os_linesep
+ b'2,"d\nef"'
+ os_linesep
+ b'3,"g\nh\n\ni"'
+ os_linesep
)
df.to_csv(temp_file, index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_noarg
# case 2: LF as line terminator
expected_lf = b'int,str_lf\n1,abc\n2,"d\nef"\n3,"g\nh\n\ni"\n'
df.to_csv(temp_file, lineterminator="\n", index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_lf
# case 3: CRLF as line terminator
# 'lineterminator' should not change inner element
expected_crlf = b'int,str_lf\r\n1,abc\r\n2,"d\nef"\r\n3,"g\nh\n\ni"\r\n'
df.to_csv(temp_file, lineterminator="\r\n", index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_crlf
def test_to_csv_string_with_crlf(self, temp_file):
# GH 20353
data = {"int": [1, 2, 3], "str_crlf": ["abc", "d\r\nef", "g\r\nh\r\n\r\ni"]}
df = DataFrame(data)
# case 1: The default line terminator(=os.linesep)(PR 21406)
os_linesep = os.linesep.encode("utf-8")
expected_noarg = (
b"int,str_crlf"
+ os_linesep
+ b"1,abc"
+ os_linesep
+ b'2,"d\r\nef"'
+ os_linesep
+ b'3,"g\r\nh\r\n\r\ni"'
+ os_linesep
)
df.to_csv(temp_file, index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_noarg
# case 2: LF as line terminator
expected_lf = b'int,str_crlf\n1,abc\n2,"d\r\nef"\n3,"g\r\nh\r\n\r\ni"\n'
df.to_csv(temp_file, lineterminator="\n", index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_lf
# case 3: CRLF as line terminator
# 'lineterminator' should not change inner element
expected_crlf = (
b'int,str_crlf\r\n1,abc\r\n2,"d\r\nef"\r\n3,"g\r\nh\r\n\r\ni"\r\n'
)
df.to_csv(temp_file, lineterminator="\r\n", index=False)
with open(temp_file, "rb") as f:
assert f.read() == expected_crlf
def test_to_csv_stdout_file(self, capsys):
# GH 21561
df = DataFrame([["foo", "bar"], ["baz", "qux"]], columns=["name_1", "name_2"])
expected_rows = [",name_1,name_2", "0,foo,bar", "1,baz,qux"]
expected_ascii = tm.convert_rows_list_to_csv_str(expected_rows)
df.to_csv(sys.stdout, encoding="ascii")
captured = capsys.readouterr()
assert captured.out == expected_ascii
assert not sys.stdout.closed
@pytest.mark.xfail(
compat.is_platform_windows(),
reason=(
"Especially in Windows, file stream should not be passed"
"to csv writer without newline='' option."
"(https://docs.python.org/3/library/csv.html#csv.writer)"
),
)
def test_to_csv_write_to_open_file(self, temp_file):
# GH 21696
df = DataFrame({"a": ["x", "y", "z"]})
expected = """\
manual header
x
y
z
"""
with open(temp_file, "w", encoding="utf-8") as f:
f.write("manual header\n")
df.to_csv(f, header=None, index=None)
with open(temp_file, encoding="utf-8") as f:
assert f.read() == expected
def test_to_csv_write_to_open_file_with_newline_py3(self, temp_file):
# see gh-21696
# see gh-20353
df = DataFrame({"a": ["x", "y", "z"]})
expected_rows = ["x", "y", "z"]
expected = "manual header\n" + tm.convert_rows_list_to_csv_str(expected_rows)
with open(temp_file, "w", newline="", encoding="utf-8") as f:
f.write("manual header\n")
df.to_csv(f, header=None, index=None)
with open(temp_file, "rb") as f:
assert f.read() == bytes(expected, "utf-8")
@pytest.mark.parametrize("to_infer", [True, False])
@pytest.mark.parametrize("read_infer", [True, False])
def test_to_csv_compression(
self,
compression_only,
read_infer,
to_infer,
compression_to_extension,
temp_file,
):
# see gh-15008
compression = compression_only
df = DataFrame({"A": [1]})
to_compression = "infer" if to_infer else compression
read_compression = "infer" if read_infer else compression
path_ext = str(temp_file) + "." + compression_to_extension[compression]
df.to_csv(path_ext, compression=to_compression)
result = pd.read_csv(path_ext, index_col=0, compression=read_compression)
tm.assert_frame_equal(result, df)
def test_to_csv_compression_dict(self, compression_only, temp_file):
# GH 26023
method = compression_only
df = DataFrame({"ABC": [1]})
extension = {
"gzip": "gz",
"zstd": "zst",
}.get(method, method)
path = str(temp_file) + "." + extension
df.to_csv(path, compression={"method": method})
read_df = pd.read_csv(path, index_col=0)
tm.assert_frame_equal(read_df, df)
def test_to_csv_compression_dict_no_method_raises(self, temp_file):
# GH 26023
df = DataFrame({"ABC": [1]})
compression = {"some_option": True}
msg = "must have key 'method'"
with pytest.raises(ValueError, match=msg):
df.to_csv(temp_file, compression=compression)
@pytest.mark.parametrize("compression", ["zip", "infer"])
@pytest.mark.parametrize("archive_name", ["test_to_csv.csv", "test_to_csv.zip"])
def test_to_csv_zip_arguments(self, compression, archive_name, temp_file):
# GH 26023
df = DataFrame({"ABC": [1]})
path = str(temp_file) + ".zip"
df.to_csv(
path, compression={"method": compression, "archive_name": archive_name}
)
with ZipFile(path) as zp:
assert len(zp.filelist) == 1
archived_file = zp.filelist[0].filename
assert archived_file == archive_name
@pytest.mark.parametrize(
"filename,expected_arcname",
[
("archive.csv", "archive.csv"),
("archive.tsv", "archive.tsv"),
("archive.csv.zip", "archive.csv"),
("archive.tsv.zip", "archive.tsv"),
("archive.zip", "archive"),
],
)
def test_to_csv_zip_infer_name(self, tmp_path, filename, expected_arcname):
# GH 39465
df = DataFrame({"ABC": [1]})
path = tmp_path / filename
df.to_csv(path, compression="zip")
with ZipFile(path) as zp:
assert len(zp.filelist) == 1
archived_file = zp.filelist[0].filename
assert archived_file == expected_arcname
@pytest.mark.parametrize("df_new_type", ["Int64"])
def test_to_csv_na_rep_long_string(self, df_new_type):
# see gh-25099
df = DataFrame({"c": [pd.NA] * 3})
df = df.astype(df_new_type)
expected_rows = ["c", "mynull", "mynull", "mynull"]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
result = df.to_csv(index=False, na_rep="mynull", encoding="ascii")
assert expected == result
def test_to_csv_timedelta_precision(self):
# GH 6783
s = pd.Series([1, 1]).astype("timedelta64[ns]")
buf = io.StringIO()
s.to_csv(buf)
result = buf.getvalue()
expected_rows = [
",0",
"0,0 days 00:00:00.000000001",
"1,0 days 00:00:00.000000001",
]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert result == expected
def test_na_rep_truncated(self):
# https://github.com/pandas-dev/pandas/issues/31447
result = pd.Series(range(8, 12)).to_csv(na_rep="-")
expected = tm.convert_rows_list_to_csv_str([",0", "0,8", "1,9", "2,10", "3,11"])
assert result == expected
result = pd.Series([True, False]).to_csv(na_rep="nan")
expected = tm.convert_rows_list_to_csv_str([",0", "0,True", "1,False"])
assert result == expected
result = pd.Series([1.1, 2.2]).to_csv(na_rep=".")
expected = tm.convert_rows_list_to_csv_str([",0", "0,1.1", "1,2.2"])
assert result == expected
@pytest.mark.parametrize("errors", ["surrogatepass", "ignore", "replace"])
def test_to_csv_errors(self, errors, temp_file):
# GH 22610
data = ["\ud800foo"]
ser = pd.Series(data, index=Index(data, dtype=object), dtype=object)
ser.to_csv(temp_file, errors=errors)
# No use in reading back the data as it is not the same anymore
# due to the error handling
@pytest.mark.parametrize("mode", ["wb", "w"])
def test_to_csv_binary_handle(self, mode, temp_file):
"""
Binary file objects should work (if 'mode' contains a 'b') or even without
it in most cases.
GH 35058 and GH 19827
"""
df = DataFrame(
1.1 * np.arange(120).reshape((30, 4)),
columns=Index(list("ABCD")),
index=Index([f"i-{i}" for i in range(30)]),
)
with open(temp_file, mode="w+b") as handle:
df.to_csv(handle, mode=mode)
tm.assert_frame_equal(df, pd.read_csv(temp_file, index_col=0))
@pytest.mark.parametrize("mode", ["wb", "w"])
def test_to_csv_encoding_binary_handle(self, mode, temp_file):
"""
Binary file objects should honor a specified encoding.
GH 23854 and GH 13068 with binary handles
"""
# example from GH 23854
content = "a, b, 🐟".encode("utf-8-sig")
buffer = io.BytesIO(content)
df = pd.read_csv(buffer, encoding="utf-8-sig")
buffer = io.BytesIO()
df.to_csv(buffer, mode=mode, encoding="utf-8-sig", index=False)
buffer.seek(0) # tests whether file handle wasn't closed
assert buffer.getvalue().startswith(content)
# example from GH 13068
with open(temp_file, "w+b") as handle:
DataFrame().to_csv(handle, mode=mode, encoding="utf-8-sig")
handle.seek(0)
assert handle.read().startswith(b'\xef\xbb\xbf""')
def test_to_csv_iterative_compression_name(compression, temp_file):
# GH 38714
df = DataFrame(
1.1 * np.arange(120).reshape((30, 4)),
columns=Index(list("ABCD")),
index=Index([f"i-{i}" for i in range(30)]),
)
df.to_csv(temp_file, compression=compression, chunksize=1)
tm.assert_frame_equal(
pd.read_csv(temp_file, compression=compression, index_col=0), df
)
def test_to_csv_iterative_compression_buffer(compression):
# GH 38714
df = DataFrame(
1.1 * np.arange(120).reshape((30, 4)),
columns=Index(list("ABCD")),
index=Index([f"i-{i}" for i in range(30)]),
)
with io.BytesIO() as buffer:
df.to_csv(buffer, compression=compression, chunksize=1)
buffer.seek(0)
tm.assert_frame_equal(
pd.read_csv(buffer, compression=compression, index_col=0), df
)
assert not buffer.closed
def test_new_style_float_format_basic():
df = DataFrame({"A": [1234.56789, 9876.54321]})
result = df.to_csv(float_format="{:.2f}", lineterminator="\n")
expected = ",A\n0,1234.57\n1,9876.54\n"
assert result == expected
def test_new_style_float_format_thousands():
df = DataFrame({"A": [1234.56789, 9876.54321]})
result = df.to_csv(float_format="{:,.2f}", lineterminator="\n")
expected = ',A\n0,"1,234.57"\n1,"9,876.54"\n'
assert result == expected
def test_new_style_scientific_format():
df = DataFrame({"A": [0.000123, 0.000456]})
result = df.to_csv(float_format="{:.2e}", lineterminator="\n")
expected = ",A\n0,1.23e-04\n1,4.56e-04\n"
assert result == expected
def test_new_style_with_nan():
df = DataFrame({"A": [1.23, np.nan, 4.56]})
result = df.to_csv(float_format="{:.2f}", na_rep="NA", lineterminator="\n")
expected = ",A\n0,1.23\n1,NA\n2,4.56\n"
assert result == expected
def test_new_style_with_mixed_types():
df = DataFrame({"A": [1.23, 4.56], "B": ["x", "y"]})
result = df.to_csv(float_format="{:.2f}", lineterminator="\n")
expected = ",A,B\n0,1.23,x\n1,4.56,y\n"
assert result == expected
def test_new_style_with_mixed_types_in_column():
df = DataFrame({"A": [1.23, "text", 4.56]})
result = df.to_csv(float_format="{:.2f}", lineterminator="\n")
expected = ",A\n0,1.23\n1,text\n2,4.56\n"
assert result == expected
def test_invalid_new_style_format_missing_brace():
df = DataFrame({"A": [1.23]})
with pytest.raises(ValueError, match="Invalid new-style format string '{:.2f"):
df.to_csv(float_format="{:.2f")
def test_invalid_new_style_format_specifier():
df = DataFrame({"A": [1.23]})
with pytest.raises(ValueError, match="Invalid new-style format string '{:.2z}'"):
df.to_csv(float_format="{:.2z}")
def test_old_style_format_compatibility():
df = DataFrame({"A": [1234.56789, 9876.54321]})
result = df.to_csv(float_format="%.2f", lineterminator="\n")
expected = ",A\n0,1234.57\n1,9876.54\n"
assert result == expected
def test_callable_float_format_compatibility():
df = DataFrame({"A": [1234.56789, 9876.54321]})
result = df.to_csv(float_format=lambda x: f"{x:,.2f}", lineterminator="\n")
expected = ',A\n0,"1,234.57"\n1,"9,876.54"\n'
assert result == expected
def test_no_float_format():
df = DataFrame({"A": [1.23, 4.56]})
result = df.to_csv(float_format=None, lineterminator="\n")
expected = ",A\n0,1.23\n1,4.56\n"
assert result == expected
def test_large_numbers():
df = DataFrame({"A": [1e308, 2e308]})
result = df.to_csv(float_format="{:.2e}", lineterminator="\n")
expected = ",A\n0,1.00e+308\n1,inf\n"
assert result == expected
def test_zero_and_negative():
df = DataFrame({"A": [0.0, -1.23456]})
result = df.to_csv(float_format="{:+.2f}", lineterminator="\n")
expected = ",A\n0,+0.00\n1,-1.23\n"
assert result == expected
def test_unicode_format():
df = DataFrame({"A": [1.23, 4.56]})
result = df.to_csv(float_format="{:.2f}€", encoding="utf-8", lineterminator="\n")
expected = ",A\n0,1.23€\n1,4.56€\n"
assert result == expected
def test_empty_dataframe():
df = DataFrame({"A": []})
result = df.to_csv(float_format="{:.2f}", lineterminator="\n")
expected = ",A\n"
assert result == expected
def test_multi_column_float():
df = DataFrame({"A": [1.23, 4.56], "B": [7.89, 0.12]})
result = df.to_csv(float_format="{:.2f}", lineterminator="\n")
expected = ",A,B\n0,1.23,7.89\n1,4.56,0.12\n"
assert result == expected
def test_invalid_float_format_type():
df = DataFrame({"A": [1.23]})
with pytest.raises(ValueError, match="float_format must be a string or callable"):
df.to_csv(float_format=123)
def test_new_style_with_inf():
df = DataFrame({"A": [1.23, np.inf, -np.inf]})
result = df.to_csv(float_format="{:.2f}", na_rep="NA", lineterminator="\n")
expected = ",A\n0,1.23\n1,inf\n2,-inf\n"
assert result == expected
def test_new_style_with_precision_edge():
df = DataFrame({"A": [1.23456789]})
result = df.to_csv(float_format="{:.10f}", lineterminator="\n")
expected = ",A\n0,1.2345678900\n"
assert result == expected
def test_new_style_with_template():
df = DataFrame({"A": [1234.56789]})
result = df.to_csv(float_format="Value: {:,.2f}", lineterminator="\n")
expected = ',A\n0,"Value: 1,234.57"\n'
assert result == expected
| TestToCSV |
python | ray-project__ray | python/ray/data/tests/test_actor_pool_map_operator.py | {
"start": 1747,
"end": 26823
} | class ____(unittest.TestCase):
def setup_class(self):
self._last_created_actor_and_ready_ref: Optional[
Tuple[ActorHandle, ObjectRef[Any]]
] = None
self._actor_node_id = "node1"
ray.init(num_cpus=4)
def teardown_class(self):
ray.shutdown()
def _create_task_selector(self, pool: _ActorPool) -> _ActorTaskSelector:
return ActorPoolMapOperator._create_task_selector(pool)
def _pick_actor(
self,
pool: _ActorPool,
bundle: Optional[RefBundle] = None,
actor_locality_enabled: bool = False,
) -> ActorHandle:
if bundle is None:
bundles = make_ref_bundles([[0]])
else:
bundles = [bundle]
queue = FIFOBundleQueue()
for bundle in bundles:
queue.add(bundle)
actor_task_selector = self._create_task_selector(pool)
it = actor_task_selector.select_actors(queue, actor_locality_enabled)
try:
actor = next(it)[1]
pool.on_task_submitted(actor)
return actor
except StopIteration:
return None
def _create_actor_fn(
self,
labels: Dict[str, Any],
logical_actor_id: str = "Actor1",
) -> Tuple[ActorHandle, ObjectRef[Any]]:
actor = PoolWorker.options(_labels=labels).remote(self._actor_node_id)
ready_ref = actor.get_location.remote()
self._last_created_actor_and_ready_ref = actor, ready_ref
return actor, ready_ref
def _create_actor_pool(
self,
min_size=1,
max_size=4,
initial_size=1,
max_tasks_in_flight=4,
):
pool = _ActorPool(
min_size=min_size,
max_size=max_size,
initial_size=initial_size,
max_actor_concurrency=1,
max_tasks_in_flight_per_actor=max_tasks_in_flight,
create_actor_fn=self._create_actor_fn,
per_actor_resource_usage=ExecutionResources(cpu=1),
)
return pool
def _add_pending_actor(
self, pool: _ActorPool, node_id="node1"
) -> Tuple[ActorHandle, ObjectRef[Any]]:
self._actor_node_id = node_id
num_actors = pool.scale(
ActorPoolScalingRequest(delta=1, reason="adding pending actor")
)
assert num_actors == 1
assert self._last_created_actor_and_ready_ref is not None
actor, ready_ref = self._last_created_actor_and_ready_ref
self._last_created_actor_and_ready_ref = None
return actor, ready_ref
def _wait_for_actor_ready(self, pool: _ActorPool, ready_ref):
ray.get(ready_ref)
pool.pending_to_running(ready_ref)
def _add_ready_actor(self, pool: _ActorPool, node_id="node1") -> ActorHandle:
actor, ready_ref = self._add_pending_actor(pool, node_id)
self._wait_for_actor_ready(pool, ready_ref)
return actor
def _wait_for_actor_dead(self, actor_id: str):
def _check_actor_dead():
nonlocal actor_id
actor_info = ray.state.actors(actor_id)
return actor_info["State"] == "DEAD"
wait_for_condition(_check_actor_dead)
def test_basic_config(self):
pool = self._create_actor_pool(
min_size=1,
max_size=4,
max_tasks_in_flight=4,
)
assert pool.min_size() == 1
assert pool.max_size() == 4
assert pool.current_size() == 0
assert pool.max_tasks_in_flight_per_actor() == 4
def test_can_scale_down(self):
pool = self._create_actor_pool(min_size=1, max_size=4)
downscaling_request = ActorPoolScalingRequest.downscale(
delta=-1, reason="scaling down"
)
with freeze_time() as f:
# Scale up
pool.scale(ActorPoolScalingRequest(delta=1, reason="scaling up"))
# Assert we can't scale down immediately after scale up
assert not pool._can_apply(downscaling_request)
assert pool._last_upscaled_at == time.time()
# Check that we can still scale down if downscaling request
# is a forced one
assert pool._can_apply(replace(downscaling_request, force=True))
# Advance clock
f.tick(
datetime.timedelta(
seconds=_ActorPool._ACTOR_POOL_SCALE_DOWN_DEBOUNCE_PERIOD_S + 1
)
)
# Assert can scale down after debounce period
assert pool._can_apply(downscaling_request)
def test_add_pending(self):
# Test that pending actor is added in the correct state.
pool = self._create_actor_pool()
_, ready_ref = self._add_pending_actor(pool)
# Check that the pending actor is not pickable.
assert self._pick_actor(pool) is None
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 1
assert pool.num_pending_actors() == 1
assert pool.num_running_actors() == 0
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 0
# Check that ready future is returned.
assert pool.get_pending_actor_refs() == [ready_ref]
def test_pending_to_running(self):
# Test that pending actor is correctly transitioned to running.
pool = self._create_actor_pool()
actor = self._add_ready_actor(pool)
# Check that the actor is pickable.
picked_actor = self._pick_actor(pool)
assert picked_actor == actor
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_active_actors() == 1
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 3
def test_restarting_to_alive(self):
# Test that actor is correctly transitioned from restarting to alive.
pool = self._create_actor_pool(max_tasks_in_flight=1)
actor = self._add_ready_actor(pool)
# Mark the actor as restarting and test pick_actor fails
pool.update_running_actor_state(actor, True)
assert self._pick_actor(pool) is None
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_restarting_actors() == 1
assert pool.num_alive_actors() == 0
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 1
assert pool.num_free_task_slots() == 1
assert pool.get_actor_info() == _ActorPoolInfo(
running=0, pending=0, restarting=1
)
# Mark the actor as alive and test pick_actor succeeds
pool.update_running_actor_state(actor, False)
picked_actor = self._pick_actor(pool)
assert picked_actor == actor
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_restarting_actors() == 0
assert pool.num_alive_actors() == 1
assert pool.num_active_actors() == 1
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 0
assert pool.get_actor_info() == _ActorPoolInfo(
running=1, pending=0, restarting=0
)
# Return the actor
pool.on_task_completed(picked_actor)
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_restarting_actors() == 0
assert pool.num_alive_actors() == 1
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 1
assert pool.num_free_task_slots() == 1
assert pool.get_actor_info() == _ActorPoolInfo(
running=1, pending=0, restarting=0
)
def test_repeated_picking(self):
# Test that we can repeatedly pick the same actor.
pool = self._create_actor_pool(max_tasks_in_flight=999)
actor = self._add_ready_actor(pool)
for _ in range(10):
picked_actor = self._pick_actor(pool)
assert picked_actor == actor
def test_return_actor(self):
# Test that we can return an actor as many times as we've picked it.
pool = self._create_actor_pool(max_tasks_in_flight=999)
self._add_ready_actor(pool)
for _ in range(10):
picked_actor = self._pick_actor(pool)
# Return the actor as many times as it was picked.
for _ in range(10):
pool.on_task_completed(picked_actor)
# Returning the actor more times than it has been picked should raise an
# AssertionError.
with pytest.raises(AssertionError):
pool.on_task_completed(picked_actor)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 1 # Actor should now be idle.
assert pool.num_free_task_slots() == 999
def test_pick_max_tasks_in_flight(self):
# Test that we can't pick an actor beyond the max_tasks_in_flight cap.
pool = self._create_actor_pool(max_tasks_in_flight=2)
actor = self._add_ready_actor(pool)
assert pool.num_free_task_slots() == 2
assert self._pick_actor(pool) == actor
assert pool.num_free_task_slots() == 1
assert self._pick_actor(pool) == actor
assert pool.num_free_task_slots() == 0
# Check that the 3rd pick doesn't return the actor.
assert self._pick_actor(pool) is None
def test_pick_ordering_lone_idle(self):
# Test that a lone idle actor is the one that's picked.
pool = self._create_actor_pool()
self._add_ready_actor(pool)
# Ensure that actor has been picked once.
self._pick_actor(pool)
# Add a new, idle actor.
actor2 = self._add_ready_actor(pool)
# Check that picked actor is the idle newly added actor.
picked_actor = self._pick_actor(pool)
assert picked_actor == actor2
def test_pick_ordering_full_order(self):
# Test that the least loaded actor is always picked.
pool = self._create_actor_pool()
# Add 4 actors to the pool.
actors = [self._add_ready_actor(pool) for _ in range(4)]
# Pick 4 actors.
picked_actors = [self._pick_actor(pool) for _ in range(4)]
# Check that the 4 distinct actors that were added to the pool were all
# returned.
assert set(picked_actors) == set(actors)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 4
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 4
assert pool.num_active_actors() == 4
assert pool.num_idle_actors() == 0
def test_pick_all_max_tasks_in_flight(self):
# Test that max_tasks_in_flight cap applies to all actors in pool.
pool = self._create_actor_pool(max_tasks_in_flight=2)
# Add 4 actors to the pool.
actors = [self._add_ready_actor(pool) for _ in range(4)]
picked_actors = [self._pick_actor(pool) for _ in range(8)]
pick_counts = collections.Counter(picked_actors)
# Check that picks were evenly distributed over the pool.
assert len(pick_counts) == 4
for actor, count in pick_counts.items():
assert actor in actors
assert count == 2
# Check that the next pick doesn't return an actor.
assert self._pick_actor(pool) is None
def test_pick_ordering_with_returns(self):
# Test that pick ordering works with returns.
pool = self._create_actor_pool()
actor1 = self._add_ready_actor(pool)
actor2 = self._add_ready_actor(pool)
picked_actors = [self._pick_actor(pool) for _ in range(2)]
# Double-check that both actors were picked.
assert set(picked_actors) == {actor1, actor2}
# Return actor 2, implying that it's now idle.
pool.on_task_completed(actor2)
# Check that actor 2 is the next actor that's picked.
picked_actor = self._pick_actor(pool)
assert picked_actor == actor2
def test_kill_inactive_pending_actor(self):
# Test that a pending actor is killed on the kill_inactive_actor() call.
pool = self._create_actor_pool()
actor, _ = self._add_pending_actor(pool)
# Kill inactive actor.
killed = pool._remove_inactive_actor()
# Check that an actor was killed.
assert killed
# Check that actor is not in pool.
assert pool.get_pending_actor_refs() == []
# Check that actor is dead.
actor_id = actor._actor_id.hex()
del actor
self._wait_for_actor_dead(actor_id)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 0
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 0
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 0
def test_kill_inactive_idle_actor(self):
# Test that a idle actor is killed on the kill_inactive_actor() call.
pool = self._create_actor_pool()
actor = self._add_ready_actor(pool)
# Kill inactive actor.
killed = pool._remove_inactive_actor()
# Check that an actor was killed.
assert killed
# Check that actor is not in pool.
assert self._pick_actor(pool) is None
# Check that actor is dead.
actor_id = actor._actor_id.hex()
del actor
self._wait_for_actor_dead(actor_id)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 0
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 0
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 0
def test_kill_inactive_active_actor_not_killed(self):
# Test that active actors are NOT killed on the kill_inactive_actor() call.
pool = self._create_actor_pool()
actor = self._add_ready_actor(pool)
# Pick actor (and double-check that the actor was picked).
picked_actor = self._pick_actor(pool)
assert picked_actor == actor
# Kill inactive actor.
killed = pool._remove_inactive_actor()
# Check that an actor was NOT killed.
assert not killed
# Check that the active actor is still in the pool.
picked_actor = self._pick_actor(pool)
assert picked_actor == actor
def test_kill_inactive_pending_over_idle(self):
# Test that a killing pending actors is prioritized over killing idle actors on
# the kill_inactive_actor() call.
pool = self._create_actor_pool()
# Add pending worker.
pending_actor, _ = self._add_pending_actor(pool)
# Add idle worker.
idle_actor = self._add_ready_actor(pool)
# Kill inactive actor.
killed = pool._remove_inactive_actor()
# Check that an actor was killed.
assert killed
# Check that the idle actor is still in the pool.
picked_actor = self._pick_actor(pool)
assert picked_actor == idle_actor
pool.on_task_completed(idle_actor)
# Check that the pending actor is not in pool.
assert pool.get_pending_actor_refs() == []
# Check that actor is dead.
actor_id = pending_actor._actor_id.hex()
del pending_actor
self._wait_for_actor_dead(actor_id)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 1
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 1
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 1
assert pool.num_free_task_slots() == 4
def test_all_actors_killed(self):
# Test that all actors are killed after the kill_all_actors() call.
pool = self._create_actor_pool()
active_actor = self._add_ready_actor(pool)
# Pick actor (and double-check that the actor was picked).
assert self._pick_actor(pool) == active_actor
idle_actor = self._add_ready_actor(pool)
# Kill all actors, including active actors.
pool.shutdown()
# Check that the pool is empty.
assert self._pick_actor(pool) is None
# Check that both actors are dead
actor_id = active_actor._actor_id.hex()
del active_actor
self._wait_for_actor_dead(actor_id)
actor_id = idle_actor._actor_id.hex()
del idle_actor
self._wait_for_actor_dead(actor_id)
# Check that the per-state pool sizes are as expected.
assert pool.current_size() == 0
assert pool.num_pending_actors() == 0
assert pool.num_running_actors() == 0
assert pool.num_active_actors() == 0
assert pool.num_idle_actors() == 0
assert pool.num_free_task_slots() == 0
def test_locality_based_actor_ranking(self):
pool = self._create_actor_pool(max_tasks_in_flight=2)
# Setup bundle mocks.
bundles = make_ref_bundles([[0] for _ in range(5)])
# Patch all bundles to return mocked preferred locations
def _get_preferred_locs():
# Node1 is higher in priority
return {"node1": 1024, "node2": 512}
for b in bundles:
# monkeypatch the get_preferred_object_locations method
b.get_preferred_object_locations = _get_preferred_locs
# Setup an actor on each node.
actor1 = self._add_ready_actor(pool, node_id="node1")
actor2 = self._add_ready_actor(pool, node_id="node2")
# Create the mock bundle queue
bundle_queue = FIFOBundleQueue()
for bundle in bundles:
bundle_queue.add(bundle)
# Create the mock task actor selector iterator
task_selector = self._create_task_selector(pool)
it = task_selector.select_actors(bundle_queue, actor_locality_enabled=True)
# Actors on node1 should be preferred
res1 = next(it)[1]
pool.on_task_submitted(res1)
assert res1 == actor1
# Actors on node1 should be preferred still
res2 = next(it)[1]
pool.on_task_submitted(res2)
assert res2 == actor1
# Fallback to remote actors
res3 = next(it)[1]
pool.on_task_submitted(res3)
assert res3 == actor2
# NOTE: Actor 2 is selected (since Actor 1 is at capacity)
res4 = next(it)[1]
pool.on_task_submitted(res4)
assert res4 == actor2
# NOTE: Actor 2 is at max requests in-flight, hence excluded
try:
res5 = next(it)[1]
except StopIteration:
res5 = None
assert res5 is None
def test_locality_based_actor_ranking_no_locations(self):
pool = self._create_actor_pool(max_tasks_in_flight=2)
# Setup bundle mocks
bundles = make_ref_bundles([[0] for _ in range(10)])
# Patch all bundles to return mocked preferred locations
for b in bundles:
# monkeypatch the get_preferred_object_locations method
b.get_preferred_object_locations = lambda: {}
# Create the mock bundle queue
bundle_queue = FIFOBundleQueue()
for bundle in bundles:
bundle_queue.add(bundle)
# Add one actor to the pool
actor1 = self._add_ready_actor(pool, node_id="node1")
# Create the mock task actor selector iterator
task_selector = self._create_task_selector(pool)
it = task_selector.select_actors(bundle_queue, actor_locality_enabled=True)
# Select one actor to schedule it on actor1
res1 = next(it)[1]
pool.on_task_submitted(res1)
assert res1 == actor1
# Add another actor to the pool
actor2 = self._add_ready_actor(pool, node_id="node2")
# Re-create the mock task actor selector iterator
task_selector = self._create_task_selector(pool)
it = task_selector.select_actors(bundle_queue, actor_locality_enabled=True)
# Select and actor, it should be scheudled on actor2
res2 = next(it)[1]
pool.on_task_submitted(res2)
assert res2 == actor2
# Select another actor, it could be either actor1 or actor2
res3 = next(it)[1]
pool.on_task_submitted(res3)
# Select another actor, it should be the other actor
res4 = next(it)[1]
pool.on_task_submitted(res4)
if res3 == actor1:
assert res4 == actor2
else:
assert res4 == actor1
# Nothing left
try:
res5 = next(it)[1]
except StopIteration:
res5 = None
assert res5 is None
def test_setting_initial_size_for_actor_pool():
data_context = ray.data.DataContext.get_current()
op = ActorPoolMapOperator(
map_transformer=MagicMock(),
input_op=InputDataBuffer(data_context, input_data=MagicMock()),
data_context=data_context,
compute_strategy=ray.data.ActorPoolStrategy(
min_size=1, max_size=4, initial_size=2
),
ray_remote_args={"num_cpus": 1},
)
op.start(ExecutionOptions())
assert op._actor_pool.get_actor_info() == _ActorPoolInfo(
running=0, pending=2, restarting=0
)
ray.shutdown()
def _create_bundle_with_single_row(row):
block = pa.Table.from_pylist([row])
block_ref = ray.put(block)
metadata = BlockAccessor.for_block(block).get_metadata()
schema = BlockAccessor.for_block(block).schema()
return RefBundle([(block_ref, metadata)], owns_blocks=False, schema=schema)
@pytest.mark.parametrize("min_rows_per_bundle", [2, None])
def test_internal_input_queue_is_empty_after_early_completion(
ray_start_regular_shared, min_rows_per_bundle
):
data_context = ray.data.DataContext.get_current()
op = ActorPoolMapOperator(
map_transformer=MagicMock(),
input_op=InputDataBuffer(data_context, input_data=MagicMock()),
data_context=data_context,
compute_strategy=ray.data.ActorPoolStrategy(size=1),
min_rows_per_bundle=min_rows_per_bundle,
)
op.start(ExecutionOptions())
ref_bundle = _create_bundle_with_single_row({"id": 0})
op.add_input(ref_bundle, 0)
op.mark_execution_finished()
assert (
op.internal_input_queue_num_blocks() == 0
), op.internal_input_queue_num_blocks()
def test_min_max_resource_requirements(restore_data_context):
data_context = ray.data.DataContext.get_current()
op = ActorPoolMapOperator(
map_transformer=MagicMock(),
input_op=InputDataBuffer(data_context, input_data=MagicMock()),
data_context=data_context,
compute_strategy=ray.data.ActorPoolStrategy(
min_size=1,
max_size=2,
),
ray_remote_args={"num_cpus": 1},
)
op._metrics = MagicMock(obj_store_mem_max_pending_output_per_task=3)
(
min_resource_usage_bound,
max_resource_usage_bound,
) = op.min_max_resource_requirements()
assert (
min_resource_usage_bound == ExecutionResources(cpu=1, object_store_memory=3)
and max_resource_usage_bound == ExecutionResources.for_limits()
)
def test_start_actor_timeout(ray_start_regular_shared, restore_data_context):
"""Tests that ActorPoolMapOperator raises an exception on
timeout while waiting for actors."""
class UDFClass:
def __call__(self, x):
return x
from ray.exceptions import GetTimeoutError
ray.data.DataContext.get_current().wait_for_min_actors_s = 1
with pytest.raises(
GetTimeoutError,
match=(
"Timed out while starting actors. This may mean that the cluster "
"does not have enough resources for the requested actor pool."
),
):
# Specify an unachievable resource requirement to ensure
# we timeout while waiting for actors.
ray.data.range(10).map_batches(
UDFClass,
batch_size=1,
compute=ray.data.ActorPoolStrategy(size=5),
num_gpus=100,
).take_all()
def make_map_transformer(block_fn: Callable[[Block], Block]):
"""Create a simple map transformer."""
def map_fn(block_iter):
for block in block_iter:
yield block_fn(block)
return MapTransformer([BlockMapTransformFn(map_fn)])
| TestActorPool |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 21651,
"end": 22161
} | class ____(StateMigration):
"""
Migrates parent state from legacy format to the new format
"""
def should_migrate(self, stream_state: Mapping[str, Any]) -> bool:
return stream_state and not stream_state.get("parent_state")
def migrate(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
if not self.should_migrate(stream_state):
return stream_state
return {"parent_state": {"change_status": stream_state}}
| GoogleAdsCriterionParentStateMigration |
python | plotly__plotly.py | plotly/graph_objs/pie/legendgrouptitle/_font.py | {
"start": 233,
"end": 9906
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie.legendgrouptitle"
_path_str = "pie.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.pie.legendgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.pie.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.pie.legendgrouptitle.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 936,
"end": 1247
} | class ____:
def foo():
XXXXXXXXXXXX.append(
(
"xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})".format(
xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx
),
my_var,
my_other_var,
)
)
| A |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 79194,
"end": 80415
} | class ____(Response):
"""
Response of tasks.add_or_update_artifacts endpoint.
:param updated: Indicates if the task was updated successfully
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_artifacts"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"updated": {
"description": "Indicates if the task was updated successfully",
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, updated: Optional[int] = None, **kwargs: Any) -> None:
super(AddOrUpdateArtifactsResponse, self).__init__(**kwargs)
self.updated = updated
@schema_property("updated")
def updated(self) -> Optional[int]:
return self._property_updated
@updated.setter
def updated(self, value: Optional[int]) -> None:
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
| AddOrUpdateArtifactsResponse |
python | catalyst-team__catalyst | tests/pipelines/test_vae.py | {
"start": 892,
"end": 1594
} | class ____(nn.Module):
def __init__(self, in_features, hid_features):
super().__init__()
self.hid_features = hid_features
self.encoder = nn.Linear(in_features, hid_features * 2)
self.decoder = nn.Sequential(nn.Linear(hid_features, in_features), nn.Sigmoid())
def forward(self, x, deterministic=False):
z = self.encoder(x)
bs, z_dim = z.shape
loc, log_scale = z[:, : z_dim // 2], z[:, z_dim // 2 :]
log_scale = torch.clamp(log_scale, LOG_SCALE_MIN, LOG_SCALE_MAX)
z_ = loc if deterministic else normal_sample(loc, log_scale)
z_ = z_.view(bs, -1)
x_ = self.decoder(z_)
return x_, loc, log_scale
| VAE |
python | walkccc__LeetCode | solutions/2736. Maximum Sum Queries/2736.py | {
"start": 60,
"end": 173
} | class ____:
x: int
y: int
def __iter__(self):
yield self.x
yield self.y
@dataclass(frozen=True)
| Pair |
python | pallets__werkzeug | src/werkzeug/debug/console.py | {
"start": 5516,
"end": 6089
} | class ____:
"""An interactive console."""
def __init__(
self,
globals: dict[str, t.Any] | None = None,
locals: dict[str, t.Any] | None = None,
) -> None:
if locals is None:
locals = {}
if globals is None:
globals = {}
self._ipy = _InteractiveConsole(globals, locals)
def eval(self, code: str) -> str:
_ipy.set(self._ipy)
old_sys_stdout = sys.stdout
try:
return self._ipy.runsource(code)
finally:
sys.stdout = old_sys_stdout
| Console |
python | apache__airflow | providers/vertica/tests/unit/vertica/hooks/test_vertica.py | {
"start": 998,
"end": 4779
} | class ____:
def setup_method(self):
self.connection = Connection(
login="login",
password="password",
host="host",
schema="vertica",
)
class UnitTestVerticaHook(VerticaHook):
conn_name_attr = "vertica_conn_id"
self.db_hook = UnitTestVerticaHook()
self.db_hook.get_connection = mock.Mock()
self.db_hook.get_connection.return_value = self.connection
@patch("airflow.providers.vertica.hooks.vertica.connect")
def test_get_conn(self, mock_connect):
self.db_hook.get_conn()
mock_connect.assert_called_once_with(
host="host", port=5433, database="vertica", user="login", password="password"
)
@patch("airflow.providers.vertica.hooks.vertica.connect")
def test_get_conn_extra_parameters_no_cast(self, mock_connect):
"""Test if parameters are correctly passed to connection"""
extra_dict = self.connection.extra_dejson
bool_options = [
"connection_load_balance",
"binary_transfer",
"disable_copy_local",
"use_prepared_statements",
]
for bo in bool_options:
extra_dict.update({bo: True})
extra_dict.update({"request_complex_types": False})
std_options = [
"session_label",
"kerberos_host_name",
"kerberos_service_name",
"unicode_error",
"workload",
"ssl",
]
for so in std_options:
extra_dict.update({so: so})
bck_server_node = ["1.2.3.4", "4.3.2.1"]
conn_timeout = 30
log_lvl = 40
extra_dict.update({"backup_server_node": bck_server_node})
extra_dict.update({"connection_timeout": conn_timeout})
extra_dict.update({"log_level": log_lvl})
self.connection.extra = json.dumps(extra_dict)
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
for bo in bool_options:
assert kwargs[bo] is True
assert kwargs["request_complex_types"] is False
for so in std_options:
assert kwargs[so] == so
assert bck_server_node[0] in kwargs["backup_server_node"]
assert bck_server_node[1] in kwargs["backup_server_node"]
assert kwargs["connection_timeout"] == conn_timeout
assert kwargs["log_level"] == log_lvl
assert kwargs["log_path"] is None
@patch("airflow.providers.vertica.hooks.vertica.connect")
def test_get_conn_extra_parameters_cast(self, mock_connect):
"""Test if parameters that can be passed either as string or int/bool
like log_level are correctly converted when passed as string
(while test_get_conn_extra_parameters_no_cast tests them passed as int/bool)"""
import logging
extra_dict = self.connection.extra_dejson
bool_options = [
"connection_load_balance",
"binary_transfer",
"disable_copy_local",
"use_prepared_statements",
]
for bo in bool_options:
extra_dict.update({bo: "True"})
extra_dict.update({"request_complex_types": "False"})
extra_dict.update({"log_level": "Error"})
self.connection.extra = json.dumps(extra_dict)
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
for bo in bool_options:
assert kwargs[bo] is True
assert kwargs["request_complex_types"] is False
assert kwargs["log_level"] == logging.ERROR
assert kwargs["log_path"] is None
| TestVerticaHookConn |
python | getsentry__sentry | tests/sentry/incidents/models/test_alert_rule.py | {
"start": 3067,
"end": 4946
} | class ____(TestCase):
def setUp(self) -> None:
self.alert_rule = self.create_alert_rule()
self.trigger = self.create_alert_rule_trigger(self.alert_rule)
def test_updated_alert_rule(self) -> None:
AlertRuleTrigger.objects.get_for_alert_rule(self.alert_rule)
assert cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id)) == [
self.trigger
]
self.alert_rule.save()
assert (
cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id))
) is None
def test_deleted_alert_rule(self) -> None:
AlertRuleTrigger.objects.get_for_alert_rule(self.alert_rule)
assert cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id)) == [
self.trigger
]
alert_rule_id = self.alert_rule.id
self.alert_rule.delete()
assert (cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(alert_rule_id))) is None
def test_updated_alert_rule_trigger(self) -> None:
AlertRuleTrigger.objects.get_for_alert_rule(self.alert_rule)
assert cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id)) == [
self.trigger
]
self.trigger.save()
assert (
cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id))
) is None
def test_deleted_alert_rule_trigger(self) -> None:
AlertRuleTrigger.objects.get_for_alert_rule(self.alert_rule)
assert cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id)) == [
self.trigger
]
self.trigger.delete()
assert (
cache.get(AlertRuleTrigger.objects._build_trigger_cache_key(self.alert_rule.id))
) is None
| AlertRuleTriggerClearCacheTest |
python | walkccc__LeetCode | solutions/1130. Minimum Cost Tree From Leaf Values/1130-3.py | {
"start": 0,
"end": 216
} | class ____:
def mctFromLeafValues(self, arr: list[int]) -> int:
ans = 0
while len(arr) > 1:
i = arr.index(min(arr))
ans += min(arr[i - 1:i] + arr[i + 1:i + 2]) * arr.pop(i)
return ans
| Solution |
python | numba__numba | numba/core/types/functions.py | {
"start": 19368,
"end": 20053
} | class ____(Type):
"""
Base class for types parametered by a mortal object, to which only
a weak reference is kept.
"""
def _store_object(self, obj):
self._wr = _PickleableWeakRef(obj)
def _get_object(self):
obj = self._wr()
if obj is None:
raise ReferenceError("underlying object has vanished")
return obj
@property
def key(self):
return self._wr
def __eq__(self, other):
if type(self) is type(other):
obj = self._wr()
return obj is not None and obj is other._wr()
return NotImplemented
def __hash__(self):
return Type.__hash__(self)
| WeakType |
python | jazzband__django-oauth-toolkit | tests/models.py | {
"start": 1479,
"end": 1567
} | class ____(AbstractGrant):
custom_field = models.CharField(max_length=255)
| SampleGrant |
python | getsentry__sentry | src/sentry/api/client.py | {
"start": 638,
"end": 4034
} | class ____:
prefix = "/api/0"
ApiError: TypeAlias = ApiError
def request(
self,
method,
path,
user=None,
auth=None,
params=None,
data=None,
is_sudo=None,
is_superuser=None,
request=None,
):
if self.prefix not in path:
full_path = self.prefix + path
else:
full_path = path
# we explicitly do not allow you to override the request *and* the user
# as then other checks like is_superuser would need overwritten
assert not (request and (user or auth)), "use either request or auth"
resolver_match = resolve(full_path)
callback, callback_args, callback_kwargs = resolver_match
if data:
# TODO(@anonrig): Investigate why we are doing this?
# we encode to ensure compatibility
data = orjson.loads(orjson.dumps(data, option=orjson.OPT_UTC_Z))
rf = APIRequestFactory()
mock_request = getattr(rf, method.lower())(full_path, data or {})
# Flag to our API class that we should trust this auth passed through
mock_request.__from_api_client__ = True
if request:
mock_request.auth = getattr(request, "auth", None)
mock_request.user = request.user
if is_sudo is None:
mock_request.is_sudo = lambda: request.is_sudo()
else:
mock_request.is_sudo = lambda: is_sudo
mock_request.session = request.session
if is_superuser is None:
mock_request.superuser = request.superuser
else:
mock_request.superuser = Superuser(mock_request)
else:
mock_request.auth = auth
mock_request.user = user or AnonymousUser()
mock_request.is_sudo = lambda: is_sudo
mock_request.session = {}
mock_request.superuser = Superuser(mock_request)
if "*" not in settings.ALLOWED_HOSTS:
mock_request.META["HTTP_HOST"] = settings.ALLOWED_HOSTS[0]
if request:
# superuser checks require access to IP
mock_request.META["REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
force_authenticate(mock_request, user, auth)
if params:
mock_request.GET._mutable = True
for key, value in params.items():
if isinstance(value, list):
mock_request.GET.setlist(key, [str(v) for v in value])
else:
mock_request.GET[key] = str(value)
mock_request.GET._mutable = False
if data:
mock_request.POST._mutable = True
mock_request.POST.update(data)
mock_request.POST._mutable = False
response = callback(mock_request, *callback_args, **callback_kwargs)
if 200 <= response.status_code < 400:
return response
raise self.ApiError(response.status_code, response.data)
def get(self, *args, **kwargs):
return self.request("GET", *args, **kwargs)
def post(self, *args, **kwargs):
return self.request("POST", *args, **kwargs)
def put(self, *args, **kwargs):
return self.request("PUT", *args, **kwargs)
def delete(self, *args, **kwargs):
return self.request("DELETE", *args, **kwargs)
| ApiClient |
python | pytorch__pytorch | test/dynamo/test_repros.py | {
"start": 29368,
"end": 29436
} | class ____:
def __init__(self, x):
self.x = x + 2
| IncByTwo |
python | python-markdown__markdown | tests/test_extensions.py | {
"start": 4697,
"end": 7767
} | class ____(unittest.TestCase):
""" Test `Wikilinks` Extension. """
def setUp(self):
self.md = markdown.Markdown(extensions=['wikilinks'])
self.text = "Some text with a [[WikiLink]]."
def testBasicWikilinks(self):
""" Test `[[wikilinks]]`. """
self.assertEqual(
self.md.convert(self.text),
'<p>Some text with a '
'<a class="wikilink" href="/WikiLink/">WikiLink</a>.</p>'
)
def testWikilinkWhitespace(self):
""" Test whitespace in `wikilinks`. """
self.assertEqual(
self.md.convert('[[ foo bar_baz ]]'),
'<p><a class="wikilink" href="/foo_bar_baz/">foo bar_baz</a></p>'
)
self.assertEqual(
self.md.convert('foo [[ ]] bar'),
'<p>foo bar</p>'
)
def testSimpleSettings(self):
""" Test Simple Settings. """
self.assertEqual(markdown.markdown(
self.text, extensions=[
markdown.extensions.wikilinks.WikiLinkExtension(
base_url='/wiki/',
end_url='.html',
html_class='foo')
]
),
'<p>Some text with a '
'<a class="foo" href="/wiki/WikiLink.html">WikiLink</a>.</p>')
def testComplexSettings(self):
""" Test Complex Settings. """
md = markdown.Markdown(
extensions=['wikilinks'],
extension_configs={
'wikilinks': [
('base_url', 'http://example.com/'),
('end_url', '.html'),
('html_class', '')
]
},
safe_mode=True
)
self.assertEqual(
md.convert(self.text),
'<p>Some text with a '
'<a href="http://example.com/WikiLink.html">WikiLink</a>.</p>'
)
def testWikilinksMetaData(self):
""" test `MetaData` with `Wikilinks` Extension. """
text = """wiki_base_url: http://example.com/
wiki_end_url: .html
wiki_html_class:
Some text with a [[WikiLink]]."""
md = markdown.Markdown(extensions=['meta', 'wikilinks'])
self.assertEqual(
md.convert(text),
'<p>Some text with a '
'<a href="http://example.com/WikiLink.html">WikiLink</a>.</p>'
)
# `MetaData` should not carry over to next document:
self.assertEqual(
md.convert("No [[MetaData]] here."),
'<p>No <a class="wikilink" href="/MetaData/">MetaData</a> '
'here.</p>'
)
def testURLCallback(self):
""" Test used of a custom URL builder. """
from markdown.extensions.wikilinks import WikiLinkExtension
def my_url_builder(label, base, end):
return '/bar/'
md = markdown.Markdown(extensions=[WikiLinkExtension(build_url=my_url_builder)])
self.assertEqual(
md.convert('[[foo]]'),
'<p><a class="wikilink" href="/bar/">foo</a></p>'
)
| TestWikiLinks |
python | apache__airflow | airflow-core/src/airflow/jobs/base_job_runner.py | {
"start": 1065,
"end": 2366
} | class ____:
"""Abstract class for job runners to derive from."""
job_type = "undefined"
def __init__(self, job: Job) -> None:
if job.job_type and job.job_type != self.job_type:
raise AirflowException(
f"The job is already assigned a different job_type: {job.job_type}."
f"This is a bug and should be reported."
)
job.job_type = self.job_type
self.job: Job = job
def _execute(self) -> int | None:
"""
Execute the logic connected to the runner.
This method should be overridden by subclasses.
:meta private:
:return: return code if available, otherwise None
"""
raise NotImplementedError()
@provide_session
def heartbeat_callback(self, session: Session = NEW_SESSION) -> None:
"""
Execute callback during heartbeat.
This method can be overwritten by the runners.
"""
@classmethod
@provide_session
def most_recent_job(cls, session: Session = NEW_SESSION) -> Job | None:
"""Return the most recent job of this type, if any, based on last heartbeat received."""
from airflow.jobs.job import most_recent_job
return most_recent_job(cls.job_type, session=session)
| BaseJobRunner |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 39892,
"end": 40216
} | class ____(dtypes.ExtendedDType):
type: ClassVar[Any] = barrier_dtype
name: ClassVar[str] = "cluster_barrier"
collective_axes: tuple[str | tuple[str, ...], ...]
num_arrivals: int
orders_tensor_core: bool
def __str__(self):
return self.name
@dataclasses.dataclass(frozen=True, kw_only=True)
| ClusterBarrierType |
python | agronholm__apscheduler | src/apscheduler/_structures.py | {
"start": 9996,
"end": 14267
} | class ____:
"""
Represents a queued request to run a task.
:var ~uuid.UUID id: autogenerated unique identifier of the job
:var str task_id: unique identifier of the task to be run
:var tuple args: positional arguments to pass to the task callable
:var dict[str, Any] kwargs: keyword arguments to pass to the task callable
:var str schedule_id: unique identifier of the associated schedule
(if the job was derived from a schedule)
:var ~datetime.datetime | None scheduled_fire_time: the time the job was scheduled
to run at (if the job was derived from a schedule; includes jitter)
:var ~datetime.timedelta | None jitter: the time that was randomly added to the
calculated scheduled run time (if the job was derived from a schedule)
:var ~datetime.datetime | None start_deadline: if the job is started in the
scheduler after this time, it is considered to be misfired and will be aborted
:var ~datetime.timedelta result_expiration_time: minimum amount of time to keep the
result available for fetching in the data store
:var metadata: key-value pairs for storing JSON compatible custom information
:var ~datetime.datetime created_at: the time at which the job was created
:var str | None acquired_by: the unique identifier of the scheduler that has
acquired the job for execution
:var str | None acquired_until: the time after which other schedulers are free to
acquire the job for processing even if it is still marked as acquired
"""
id: UUID = attrs.field(factory=uuid4, on_setattr=frozen)
task_id: str = attrs.field(on_setattr=frozen)
args: tuple = attrs.field(
converter=tuple, default=(), repr=False, on_setattr=frozen
)
kwargs: dict[str, Any] = attrs.field(
converter=dict, factory=dict, repr=False, on_setattr=frozen
)
schedule_id: str | None = attrs.field(default=None, on_setattr=frozen)
scheduled_fire_time: datetime | None = attrs.field(
converter=as_aware_datetime, default=None, on_setattr=frozen
)
executor: str = attrs.field(on_setattr=frozen)
jitter: timedelta = attrs.field(
converter=as_timedelta, factory=timedelta, repr=False, on_setattr=frozen
)
start_deadline: datetime | None = attrs.field(
converter=as_aware_datetime, default=None, repr=False, on_setattr=frozen
)
result_expiration_time: timedelta = attrs.field(
converter=as_timedelta, default=timedelta(), repr=False, on_setattr=frozen
)
metadata: MetadataType = attrs.field(validator=valid_metadata, factory=dict)
created_at: datetime = attrs.field(
converter=as_aware_datetime,
factory=partial(datetime.now, timezone.utc),
on_setattr=frozen,
)
acquired_by: str | None = attrs.field(default=None, repr=False)
acquired_until: datetime | None = attrs.field(
converter=as_aware_datetime, default=None, repr=False
)
@property
def original_scheduled_time(self) -> datetime | None:
"""The scheduled time without any jitter included."""
if self.scheduled_fire_time is None:
return None
return self.scheduled_fire_time - self.jitter
def marshal(self, serializer: Serializer) -> dict[str, Any]:
marshalled = attrs.asdict(self, recurse=False, value_serializer=serialize)
marshalled["args"] = serializer.serialize(self.args)
marshalled["kwargs"] = serializer.serialize(self.kwargs)
if not self.acquired_by:
del marshalled["acquired_by"]
del marshalled["acquired_until"]
return marshalled
@classmethod
def unmarshal(cls, serializer: Serializer, marshalled: dict[str, Any]) -> Job:
if args := marshalled["args"]:
marshalled["args"] = serializer.deserialize(args)
if kwargs := marshalled["kwargs"]:
marshalled["kwargs"] = serializer.deserialize(kwargs)
return cls(**marshalled)
def __hash__(self) -> int:
return hash(self.id)
def __eq__(self, other: object) -> bool:
if isinstance(other, Job):
return self.id == other.id
return NotImplemented
@attrs.define(kw_only=True, frozen=True, eq=False)
| Job |
python | ray-project__ray | rllib/policy/eager_tf_policy.py | {
"start": 9800,
"end": 43457
} | class ____:
def __init__(self, tape):
self.tape = tape
def compute_gradients(self, loss, var_list):
return list(zip(self.tape.gradient(loss, var_list), var_list))
@OldAPIStack
def _build_eager_tf_policy(
name,
loss_fn,
get_default_config=None,
postprocess_fn=None,
stats_fn=None,
optimizer_fn=None,
compute_gradients_fn=None,
apply_gradients_fn=None,
grad_stats_fn=None,
extra_learn_fetches_fn=None,
extra_action_out_fn=None,
validate_spaces=None,
before_init=None,
before_loss_init=None,
after_init=None,
make_model=None,
action_sampler_fn=None,
action_distribution_fn=None,
mixins=None,
get_batch_divisibility_req=None,
# Deprecated args.
obs_include_prev_action_reward=DEPRECATED_VALUE,
extra_action_fetches_fn=None,
gradients_fn=None,
):
"""Build an eager TF policy.
An eager policy runs all operations in eager mode, which makes debugging
much simpler, but has lower performance.
You shouldn't need to call this directly. Rather, prefer to build a TF
graph policy and use set `.framework("tf2", eager_tracing=False) in your
AlgorithmConfig to have it automatically be converted to an eager policy.
This has the same signature as build_tf_policy()."""
base = add_mixins(EagerTFPolicy, mixins)
if obs_include_prev_action_reward != DEPRECATED_VALUE:
deprecation_warning(old="obs_include_prev_action_reward", error=True)
if extra_action_fetches_fn is not None:
deprecation_warning(
old="extra_action_fetches_fn", new="extra_action_out_fn", error=True
)
if gradients_fn is not None:
deprecation_warning(old="gradients_fn", new="compute_gradients_fn", error=True)
class eager_policy_cls(base):
def __init__(self, observation_space, action_space, config):
# If this class runs as a @ray.remote actor, eager mode may not
# have been activated yet.
if not tf1.executing_eagerly():
tf1.enable_eager_execution()
self.framework = config.get("framework", "tf2")
EagerTFPolicy.__init__(self, observation_space, action_space, config)
# Global timestep should be a tensor.
self.global_timestep = tf.Variable(0, trainable=False, dtype=tf.int64)
self.explore = tf.Variable(
self.config["explore"], trainable=False, dtype=tf.bool
)
# Log device and worker index.
num_gpus = self._get_num_gpus_for_policy()
if num_gpus > 0:
gpu_ids = get_gpu_devices()
logger.info(f"Found {len(gpu_ids)} visible cuda devices.")
self._is_training = False
# Only for `config.eager_tracing=True`: A counter to keep track of
# how many times an eager-traced method (e.g.
# `self._compute_actions_helper`) has been re-traced by tensorflow.
# We will raise an error if more than n re-tracings have been
# detected, since this would considerably slow down execution.
# The variable below should only get incremented during the
# tf.function trace operations, never when calling the already
# traced function after that.
self._re_trace_counter = 0
self._loss_initialized = False
# To ensure backward compatibility:
# Old way: If `loss` provided here, use as-is (as a function).
if loss_fn is not None:
self._loss = loss_fn
# New way: Convert the overridden `self.loss` into a plain
# function, so it can be called the same way as `loss` would
# be, ensuring backward compatibility.
elif self.loss.__func__.__qualname__ != "Policy.loss":
self._loss = self.loss.__func__
# `loss` not provided nor overridden from Policy -> Set to None.
else:
self._loss = None
self.batch_divisibility_req = (
get_batch_divisibility_req(self)
if callable(get_batch_divisibility_req)
else (get_batch_divisibility_req or 1)
)
self._max_seq_len = config["model"]["max_seq_len"]
if validate_spaces:
validate_spaces(self, observation_space, action_space, config)
if before_init:
before_init(self, observation_space, action_space, config)
self.config = config
self.dist_class = None
if action_sampler_fn or action_distribution_fn:
if not make_model:
raise ValueError(
"`make_model` is required if `action_sampler_fn` OR "
"`action_distribution_fn` is given"
)
else:
self.dist_class, logit_dim = ModelCatalog.get_action_dist(
action_space, self.config["model"]
)
if make_model:
self.model = make_model(self, observation_space, action_space, config)
else:
self.model = ModelCatalog.get_model_v2(
observation_space,
action_space,
logit_dim,
config["model"],
framework=self.framework,
)
# Lock used for locking some methods on the object-level.
# This prevents possible race conditions when calling the model
# first, then its value function (e.g. in a loss function), in
# between of which another model call is made (e.g. to compute an
# action).
self._lock = threading.RLock()
# Auto-update model's inference view requirements, if recurrent.
self._update_model_view_requirements_from_init_state()
# Combine view_requirements for Model and Policy.
self.view_requirements.update(self.model.view_requirements)
self.exploration = self._create_exploration()
self._state_inputs = self.model.get_initial_state()
self._is_recurrent = len(self._state_inputs) > 0
if before_loss_init:
before_loss_init(self, observation_space, action_space, config)
if optimizer_fn:
optimizers = optimizer_fn(self, config)
else:
optimizers = tf.keras.optimizers.Adam(config["lr"])
optimizers = force_list(optimizers)
if self.exploration:
optimizers = self.exploration.get_exploration_optimizer(optimizers)
# The list of local (tf) optimizers (one per loss term).
self._optimizers: List[LocalOptimizer] = optimizers
# Backward compatibility: A user's policy may only support a single
# loss term and optimizer (no lists).
self._optimizer: LocalOptimizer = optimizers[0] if optimizers else None
self._initialize_loss_from_dummy_batch(
auto_remove_unneeded_view_reqs=True,
stats_fn=stats_fn,
)
self._loss_initialized = True
if after_init:
after_init(self, observation_space, action_space, config)
# Got to reset global_timestep again after fake run-throughs.
self.global_timestep.assign(0)
@override(Policy)
def compute_actions_from_input_dict(
self,
input_dict: Dict[str, TensorType],
explore: bool = None,
timestep: Optional[int] = None,
episodes=None,
**kwargs,
) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:
if not self.config.get("eager_tracing") and not tf1.executing_eagerly():
tf1.enable_eager_execution()
self._is_training = False
explore = explore if explore is not None else self.explore
timestep = timestep if timestep is not None else self.global_timestep
if isinstance(timestep, tf.Tensor):
timestep = int(timestep.numpy())
# Pass lazy (eager) tensor dict to Model as `input_dict`.
input_dict = self._lazy_tensor_dict(input_dict)
input_dict.set_training(False)
# Pack internal state inputs into (separate) list.
state_batches = [
input_dict[k] for k in input_dict.keys() if "state_in" in k[:8]
]
self._state_in = state_batches
self._is_recurrent = state_batches != []
# Call the exploration before_compute_actions hook.
self.exploration.before_compute_actions(
timestep=timestep, explore=explore, tf_sess=self.get_session()
)
ret = self._compute_actions_helper(
input_dict,
state_batches,
# TODO: Passing episodes into a traced method does not work.
None if self.config["eager_tracing"] else episodes,
explore,
timestep,
)
# Update our global timestep by the batch size.
self.global_timestep.assign_add(tree.flatten(ret[0])[0].shape.as_list()[0])
return convert_to_numpy(ret)
@override(Policy)
def compute_actions(
self,
obs_batch: Union[List[TensorStructType], TensorStructType],
state_batches: Optional[List[TensorType]] = None,
prev_action_batch: Union[List[TensorStructType], TensorStructType] = None,
prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None,
info_batch: Optional[Dict[str, list]] = None,
episodes: Optional[List] = None,
explore: Optional[bool] = None,
timestep: Optional[int] = None,
**kwargs,
) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:
# Create input dict to simply pass the entire call to
# self.compute_actions_from_input_dict().
input_dict = SampleBatch(
{
SampleBatch.CUR_OBS: obs_batch,
},
_is_training=tf.constant(False),
)
if state_batches is not None:
for i, s in enumerate(state_batches):
input_dict[f"state_in_{i}"] = s
if prev_action_batch is not None:
input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch
if prev_reward_batch is not None:
input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch
if info_batch is not None:
input_dict[SampleBatch.INFOS] = info_batch
return self.compute_actions_from_input_dict(
input_dict=input_dict,
explore=explore,
timestep=timestep,
episodes=episodes,
**kwargs,
)
@with_lock
@override(Policy)
def compute_log_likelihoods(
self,
actions,
obs_batch,
state_batches=None,
prev_action_batch=None,
prev_reward_batch=None,
actions_normalized=True,
**kwargs,
):
if action_sampler_fn and action_distribution_fn is None:
raise ValueError(
"Cannot compute log-prob/likelihood w/o an "
"`action_distribution_fn` and a provided "
"`action_sampler_fn`!"
)
seq_lens = tf.ones(len(obs_batch), dtype=tf.int32)
input_batch = SampleBatch(
{SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_batch)},
_is_training=False,
)
if prev_action_batch is not None:
input_batch[SampleBatch.PREV_ACTIONS] = tf.convert_to_tensor(
prev_action_batch
)
if prev_reward_batch is not None:
input_batch[SampleBatch.PREV_REWARDS] = tf.convert_to_tensor(
prev_reward_batch
)
if self.exploration:
# Exploration hook before each forward pass.
self.exploration.before_compute_actions(explore=False)
# Action dist class and inputs are generated via custom function.
if action_distribution_fn:
dist_inputs, dist_class, _ = action_distribution_fn(
self, self.model, input_batch, explore=False, is_training=False
)
# Default log-likelihood calculation.
else:
dist_inputs, _ = self.model(input_batch, state_batches, seq_lens)
dist_class = self.dist_class
action_dist = dist_class(dist_inputs, self.model)
# Normalize actions if necessary.
if not actions_normalized and self.config["normalize_actions"]:
actions = normalize_action(actions, self.action_space_struct)
log_likelihoods = action_dist.logp(actions)
return log_likelihoods
@override(Policy)
def postprocess_trajectory(
self, sample_batch, other_agent_batches=None, episode=None
):
assert tf.executing_eagerly()
# Call super's postprocess_trajectory first.
sample_batch = EagerTFPolicy.postprocess_trajectory(self, sample_batch)
if postprocess_fn:
return postprocess_fn(self, sample_batch, other_agent_batches, episode)
return sample_batch
@with_lock
@override(Policy)
def learn_on_batch(self, postprocessed_batch):
# Callback handling.
learn_stats = {}
self.callbacks.on_learn_on_batch(
policy=self, train_batch=postprocessed_batch, result=learn_stats
)
pad_batch_to_sequences_of_same_size(
postprocessed_batch,
max_seq_len=self._max_seq_len,
shuffle=False,
batch_divisibility_req=self.batch_divisibility_req,
view_requirements=self.view_requirements,
)
self._is_training = True
postprocessed_batch = self._lazy_tensor_dict(postprocessed_batch)
postprocessed_batch.set_training(True)
stats = self._learn_on_batch_helper(postprocessed_batch)
self.num_grad_updates += 1
stats.update(
{
"custom_metrics": learn_stats,
NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count,
NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates,
# -1, b/c we have to measure this diff before we do the update
# above.
DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: (
self.num_grad_updates
- 1
- (postprocessed_batch.num_grad_updates or 0)
),
}
)
return convert_to_numpy(stats)
@override(Policy)
def compute_gradients(
self, postprocessed_batch: SampleBatch
) -> Tuple[ModelGradients, Dict[str, TensorType]]:
pad_batch_to_sequences_of_same_size(
postprocessed_batch,
shuffle=False,
max_seq_len=self._max_seq_len,
batch_divisibility_req=self.batch_divisibility_req,
view_requirements=self.view_requirements,
)
self._is_training = True
self._lazy_tensor_dict(postprocessed_batch)
postprocessed_batch.set_training(True)
grads_and_vars, grads, stats = self._compute_gradients_helper(
postprocessed_batch
)
return convert_to_numpy((grads, stats))
@override(Policy)
def apply_gradients(self, gradients: ModelGradients) -> None:
self._apply_gradients_helper(
list(
zip(
[
(tf.convert_to_tensor(g) if g is not None else None)
for g in gradients
],
self.model.trainable_variables(),
)
)
)
@override(Policy)
def get_weights(self, as_dict=False):
variables = self.variables()
if as_dict:
return {v.name: v.numpy() for v in variables}
return [v.numpy() for v in variables]
@override(Policy)
def set_weights(self, weights):
variables = self.variables()
assert len(weights) == len(variables), (len(weights), len(variables))
for v, w in zip(variables, weights):
v.assign(w)
@override(Policy)
def get_exploration_state(self):
return convert_to_numpy(self.exploration.get_state())
@override(Policy)
def is_recurrent(self):
return self._is_recurrent
@override(Policy)
def num_state_tensors(self):
return len(self._state_inputs)
@override(Policy)
def get_initial_state(self):
if hasattr(self, "model"):
return self.model.get_initial_state()
return []
@override(Policy)
def get_state(self) -> PolicyState:
# Legacy Policy state (w/o keras model and w/o PolicySpec).
state = super().get_state()
state["global_timestep"] = state["global_timestep"].numpy()
if self._optimizer and len(self._optimizer.variables()) > 0:
state["_optimizer_variables"] = self._optimizer.variables()
# Add exploration state.
if self.exploration:
# This is not compatible with RLModules, which have a method
# `forward_exploration` to specify custom exploration behavior.
state["_exploration_state"] = self.exploration.get_state()
return state
@override(Policy)
def set_state(self, state: PolicyState) -> None:
# Set optimizer vars first.
optimizer_vars = state.get("_optimizer_variables", None)
if optimizer_vars and self._optimizer.variables():
if not type(self).__name__.endswith("_traced") and log_once(
"set_state_optimizer_vars_tf_eager_policy_v2"
):
logger.warning(
"Cannot restore an optimizer's state for tf eager! Keras "
"is not able to save the v1.x optimizers (from "
"tf.compat.v1.train) since they aren't compatible with "
"checkpoints."
)
for opt_var, value in zip(self._optimizer.variables(), optimizer_vars):
opt_var.assign(value)
# Set exploration's state.
if hasattr(self, "exploration") and "_exploration_state" in state:
self.exploration.set_state(state=state["_exploration_state"])
# Restore glbal timestep (tf vars).
self.global_timestep.assign(state["global_timestep"])
# Then the Policy's (NN) weights and connectors.
super().set_state(state)
@override(Policy)
def export_model(self, export_dir, onnx: Optional[int] = None) -> None:
"""Exports the Policy's Model to local directory for serving.
Note: Since the TfModelV2 class that EagerTfPolicy uses is-NOT-a
tf.keras.Model, we need to assume that there is a `base_model` property
within this TfModelV2 class that is-a tf.keras.Model. This base model
will be used here for the export.
TODO (kourosh): This restriction will be resolved once we move Policy and
ModelV2 to the new Learner/RLModule APIs.
Args:
export_dir: Local writable directory.
onnx: If given, will export model in ONNX format. The
value of this parameter set the ONNX OpSet version to use.
"""
if (
hasattr(self, "model")
and hasattr(self.model, "base_model")
and isinstance(self.model.base_model, tf.keras.Model)
):
# Store model in ONNX format.
if onnx:
try:
import tf2onnx
except ImportError as e:
raise RuntimeError(
"Converting a TensorFlow model to ONNX requires "
"`tf2onnx` to be installed. Install with "
"`pip install tf2onnx`."
) from e
model_proto, external_tensor_storage = tf2onnx.convert.from_keras(
self.model.base_model,
output_path=os.path.join(export_dir, "model.onnx"),
)
# Save the tf.keras.Model (architecture and weights, so it can be
# retrieved w/o access to the original (custom) Model or Policy code).
else:
try:
self.model.base_model.save(export_dir, save_format="tf")
except Exception:
logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL)
else:
logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL)
def variables(self):
"""Return the list of all savable variables for this policy."""
if isinstance(self.model, tf.keras.Model):
return self.model.variables
else:
return self.model.variables()
def loss_initialized(self):
return self._loss_initialized
@with_lock
def _compute_actions_helper(
self, input_dict, state_batches, episodes, explore, timestep
):
# Increase the tracing counter to make sure we don't re-trace too
# often. If eager_tracing=True, this counter should only get
# incremented during the @tf.function trace operations, never when
# calling the already traced function after that.
self._re_trace_counter += 1
# Calculate RNN sequence lengths.
batch_size = tree.flatten(input_dict[SampleBatch.OBS])[0].shape[0]
seq_lens = tf.ones(batch_size, dtype=tf.int32) if state_batches else None
# Add default and custom fetches.
extra_fetches = {}
# Use Exploration object.
with tf.variable_creator_scope(_disallow_var_creation):
if action_sampler_fn:
action_sampler_outputs = action_sampler_fn(
self,
self.model,
input_dict[SampleBatch.CUR_OBS],
explore=explore,
timestep=timestep,
episodes=episodes,
)
if len(action_sampler_outputs) == 4:
actions, logp, dist_inputs, state_out = action_sampler_outputs
else:
dist_inputs = None
state_out = []
actions, logp = action_sampler_outputs
else:
if action_distribution_fn:
# Try new action_distribution_fn signature, supporting
# state_batches and seq_lens.
try:
(
dist_inputs,
self.dist_class,
state_out,
) = action_distribution_fn(
self,
self.model,
input_dict=input_dict,
state_batches=state_batches,
seq_lens=seq_lens,
explore=explore,
timestep=timestep,
is_training=False,
)
# Trying the old way (to stay backward compatible).
# TODO: Remove in future.
except TypeError as e:
if (
"positional argument" in e.args[0]
or "unexpected keyword argument" in e.args[0]
):
(
dist_inputs,
self.dist_class,
state_out,
) = action_distribution_fn(
self,
self.model,
input_dict[SampleBatch.OBS],
explore=explore,
timestep=timestep,
is_training=False,
)
else:
raise e
elif isinstance(self.model, tf.keras.Model):
input_dict = SampleBatch(input_dict, seq_lens=seq_lens)
if state_batches and "state_in_0" not in input_dict:
for i, s in enumerate(state_batches):
input_dict[f"state_in_{i}"] = s
self._lazy_tensor_dict(input_dict)
dist_inputs, state_out, extra_fetches = self.model(input_dict)
else:
dist_inputs, state_out = self.model(
input_dict, state_batches, seq_lens
)
action_dist = self.dist_class(dist_inputs, self.model)
# Get the exploration action from the forward results.
actions, logp = self.exploration.get_exploration_action(
action_distribution=action_dist,
timestep=timestep,
explore=explore,
)
# Action-logp and action-prob.
if logp is not None:
extra_fetches[SampleBatch.ACTION_PROB] = tf.exp(logp)
extra_fetches[SampleBatch.ACTION_LOGP] = logp
# Action-dist inputs.
if dist_inputs is not None:
extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs
# Custom extra fetches.
if extra_action_out_fn:
extra_fetches.update(extra_action_out_fn(self))
return actions, state_out, extra_fetches
# TODO: Figure out, why _ray_trace_ctx=None helps to prevent a crash in
# AlphaStar w/ framework=tf2; eager_tracing=True on the policy learner actors.
# It seems there may be a clash between the traced-by-tf function and the
# traced-by-ray functions (for making the policy class a ray actor).
def _learn_on_batch_helper(self, samples, _ray_trace_ctx=None):
# Increase the tracing counter to make sure we don't re-trace too
# often. If eager_tracing=True, this counter should only get
# incremented during the @tf.function trace operations, never when
# calling the already traced function after that.
self._re_trace_counter += 1
with tf.variable_creator_scope(_disallow_var_creation):
grads_and_vars, _, stats = self._compute_gradients_helper(samples)
self._apply_gradients_helper(grads_and_vars)
return stats
def _get_is_training_placeholder(self):
return tf.convert_to_tensor(self._is_training)
@with_lock
def _compute_gradients_helper(self, samples):
"""Computes and returns grads as eager tensors."""
# Increase the tracing counter to make sure we don't re-trace too
# often. If eager_tracing=True, this counter should only get
# incremented during the @tf.function trace operations, never when
# calling the already traced function after that.
self._re_trace_counter += 1
# Gather all variables for which to calculate losses.
if isinstance(self.model, tf.keras.Model):
variables = self.model.trainable_variables
else:
variables = self.model.trainable_variables()
# Calculate the loss(es) inside a tf GradientTape.
with tf.GradientTape(persistent=compute_gradients_fn is not None) as tape:
losses = self._loss(self, self.model, self.dist_class, samples)
losses = force_list(losses)
# User provided a compute_gradients_fn.
if compute_gradients_fn:
# Wrap our tape inside a wrapper, such that the resulting
# object looks like a "classic" tf.optimizer. This way, custom
# compute_gradients_fn will work on both tf static graph
# and tf-eager.
optimizer = _OptimizerWrapper(tape)
# More than one loss terms/optimizers.
if self.config["_tf_policy_handles_more_than_one_loss"]:
grads_and_vars = compute_gradients_fn(
self, [optimizer] * len(losses), losses
)
# Only one loss and one optimizer.
else:
grads_and_vars = [compute_gradients_fn(self, optimizer, losses[0])]
# Default: Compute gradients using the above tape.
else:
grads_and_vars = [
list(zip(tape.gradient(loss, variables), variables))
for loss in losses
]
if log_once("grad_vars"):
for g_and_v in grads_and_vars:
for g, v in g_and_v:
if g is not None:
logger.info(f"Optimizing variable {v.name}")
# `grads_and_vars` is returned a list (len=num optimizers/losses)
# of lists of (grad, var) tuples.
if self.config["_tf_policy_handles_more_than_one_loss"]:
grads = [[g for g, _ in g_and_v] for g_and_v in grads_and_vars]
# `grads_and_vars` is returned as a list of (grad, var) tuples.
else:
grads_and_vars = grads_and_vars[0]
grads = [g for g, _ in grads_and_vars]
stats = self._stats(self, samples, grads)
return grads_and_vars, grads, stats
def _apply_gradients_helper(self, grads_and_vars):
# Increase the tracing counter to make sure we don't re-trace too
# often. If eager_tracing=True, this counter should only get
# incremented during the @tf.function trace operations, never when
# calling the already traced function after that.
self._re_trace_counter += 1
if apply_gradients_fn:
if self.config["_tf_policy_handles_more_than_one_loss"]:
apply_gradients_fn(self, self._optimizers, grads_and_vars)
else:
apply_gradients_fn(self, self._optimizer, grads_and_vars)
else:
if self.config["_tf_policy_handles_more_than_one_loss"]:
for i, o in enumerate(self._optimizers):
o.apply_gradients(
[(g, v) for g, v in grads_and_vars[i] if g is not None]
)
else:
self._optimizer.apply_gradients(
[(g, v) for g, v in grads_and_vars if g is not None]
)
def _stats(self, outputs, samples, grads):
fetches = {}
if stats_fn:
fetches[LEARNER_STATS_KEY] = dict(stats_fn(outputs, samples))
else:
fetches[LEARNER_STATS_KEY] = {}
if extra_learn_fetches_fn:
fetches.update(dict(extra_learn_fetches_fn(self)))
if grad_stats_fn:
fetches.update(dict(grad_stats_fn(self, samples, grads)))
return fetches
def _lazy_tensor_dict(self, postprocessed_batch: SampleBatch):
# TODO: (sven): Keep for a while to ensure backward compatibility.
if not isinstance(postprocessed_batch, SampleBatch):
postprocessed_batch = SampleBatch(postprocessed_batch)
postprocessed_batch.set_get_interceptor(_convert_to_tf)
return postprocessed_batch
@classmethod
def with_tracing(cls):
return _traced_eager_policy(cls)
eager_policy_cls.__name__ = name + "_eager"
eager_policy_cls.__qualname__ = name + "_eager"
return eager_policy_cls
| _OptimizerWrapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.