code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async def test_notifier_base(self, send_message_mock):
"""
Unit tests for hummingbot.notifier.notifier_base.NotifierBase
"""
# create a NotifierBase instance
notifier_base = NotifierBase()
notifier_base._sleep = AsyncMock()
send_message_mock.side_effect = [None, E... |
Unit tests for hummingbot.notifier.notifier_base.NotifierBase
| test_notifier_base | python | hummingbot/hummingbot | test/hummingbot/notifier/test_notifier_base.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/notifier/test_notifier_base.py | Apache-2.0 |
def simulate_place_order(order_tracker: OrderTracker, order: Union[LimitOrder, MarketOrder], market_info: MarketTradingPairTuple):
"""
Simulates an order being successfully placed.
"""
if isinstance(order, LimitOrder):
order_tracker.add_create_order_pending(order.client_order... |
Simulates an order being successfully placed.
| simulate_place_order | python | hummingbot/hummingbot | test/hummingbot/strategy/test_order_tracker.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/test_order_tracker.py | Apache-2.0 |
def simulate_stop_tracking_order(order_tracker: OrderTracker, order: Union[LimitOrder, MarketOrder], market_info: MarketTradingPairTuple):
"""
Simulates an order being cancelled or filled completely.
"""
if isinstance(order, LimitOrder):
order_tracker.stop_tracking_limit_orde... |
Simulates an order being cancelled or filled completely.
| simulate_stop_tracking_order | python | hummingbot/hummingbot | test/hummingbot/strategy/test_order_tracker.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/test_order_tracker.py | Apache-2.0 |
def test_profit_without_fees_for_different_base_trading_pairs_and_different_amount_on_sides(self):
"""
If the amount is different on both sides and the base tokens are different, then
the profit calculation should not apply the conversion rate for the base tokens because
the different or... |
If the amount is different on both sides and the base tokens are different, then
the profit calculation should not apply the conversion rate for the base tokens because
the different orders of magnitude for the tokens might have been considered when configuring
the arbitrage sides.
... | test_profit_without_fees_for_different_base_trading_pairs_and_different_amount_on_sides | python | hummingbot/hummingbot | test/hummingbot/strategy/amm_arb/test_data_types.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/amm_arb/test_data_types.py | Apache-2.0 |
def build_config_map(cm: ClientConfigAdapter, cs: Dict):
"""This routine can be used in the create command, with slight modifications."""
for key in cm.keys():
client_data = cm.get_client_data(key)
if client_data is not None and client_data.prompt_on_new:
... | This routine can be used in the create command, with slight modifications. | build_config_map | python | hummingbot/hummingbot | test/hummingbot/strategy/avellaneda_market_making/test_avellaneda_market_making_config_map_pydantic.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/avellaneda_market_making/test_avellaneda_market_making_config_map_pydantic.py | Apache-2.0 |
def create_market(trading_pairs: List[str], mid_price, balances: Dict[str, int]) -> \
(MockPaperExchange, Dict[str, MarketTradingPairTuple]):
"""
Create a BacktestMarket and marketinfo dictionary to be used by the liquidity mining strategy
"""
market: MockPaperExchange = Mock... |
Create a BacktestMarket and marketinfo dictionary to be used by the liquidity mining strategy
| create_market | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def simulate_maker_market_trade(
self, is_buy: bool, quantity: Decimal, price: Decimal, trading_pair: str,
market: Optional[MockPaperExchange] = None,
):
"""
simulate making a trade, broadcasts a trade event
"""
if market is None:
market = self.mar... |
simulate making a trade, broadcasts a trade event
| simulate_maker_market_trade | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_simulate_maker_market_trade(self, estimate_fee_mock):
"""
Test that we can set up a liquidity mining strategy, and a trade
"""
estimate_fee_mock.return_value = AddedToCostTradeFee(
percent=0, flat_fees=[TokenAmount('ETH', Decimal(0.00005))]
)
# initi... |
Test that we can set up a liquidity mining strategy, and a trade
| test_simulate_maker_market_trade | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_multiple_markets(self, estimate_fee_mock):
"""
Liquidity Mining supports one base asset but multiple quote assets. This shows that the user can successfully
provide liquidity for two different pairs and the market can execute the other side of them.
"""
estimate_fee_mock... |
Liquidity Mining supports one base asset but multiple quote assets. This shows that the user can successfully
provide liquidity for two different pairs and the market can execute the other side of them.
| test_multiple_markets | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_budget_allocation(self, estimate_fee_mock):
"""
Liquidity mining strategy budget allocation is different from pmm, it depends on the token base and it splits
its budget between the quote tokens.
"""
estimate_fee_mock.return_value = AddedToCostTradeFee(
percen... |
Liquidity mining strategy budget allocation is different from pmm, it depends on the token base and it splits
its budget between the quote tokens.
| test_budget_allocation | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_inventory_skew(self, estimate_fee_mock):
"""
When inventory_skew_enabled is true, the strategy will try to balance the amounts of base to match it
"""
estimate_fee_mock.return_value = AddedToCostTradeFee(
percent=0, flat_fees=[TokenAmount('ETH', Decimal(0.00005))]
... |
When inventory_skew_enabled is true, the strategy will try to balance the amounts of base to match it
| test_inventory_skew | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_volatility(self, estimate_fee_mock, get_mid_price_mock):
"""
Assert that volatility information is updated after the expected number of intervals
"""
estimate_fee_mock.return_value = AddedToCostTradeFee(
percent=0, flat_fees=[TokenAmount('ETH', Decimal(0.00005))]
... |
Assert that volatility information is updated after the expected number of intervals
| test_volatility | python | hummingbot/hummingbot | test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/liquidity_mining/test_liquidity_mining.py | Apache-2.0 |
def test_order_quantity_available_balance(self):
"""
When balance is below the specified order amount, checks if orders created
use the remaining available balance for the order size.
"""
strategy = PureMarketMakingStrategy()
strategy.init_params(
self.market_... |
When balance is below the specified order amount, checks if orders created
use the remaining available balance for the order size.
| test_order_quantity_available_balance | python | hummingbot/hummingbot | test/hummingbot/strategy/pure_market_making/test_pmm.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/pure_market_making/test_pmm.py | Apache-2.0 |
def test_strategy_starts_with_existing_position(self):
"""
Tests if the strategy can start
"""
self.strategy._position_mode_ready = True
self.clock.add_iterator(self.strategy)
self.perp_connector._account_positions[trading_pair] = Position(
trading_pair,
... |
Tests if the strategy can start
| test_strategy_starts_with_existing_position | python | hummingbot/hummingbot | test/hummingbot/strategy/spot_perpetual_arbitrage/test_spot_perpetual_arbitrage.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/spot_perpetual_arbitrage/test_spot_perpetual_arbitrage.py | Apache-2.0 |
def test_strategy_starts_with_existing_position_unmatched_pos_amount(self):
"""
Tests if the strategy start then stop when there is an existing position where position amount doesn't match
strategy order amount
"""
self.strategy._position_mode_ready = True
self.clock.add_... |
Tests if the strategy start then stop when there is an existing position where position amount doesn't match
strategy order amount
| test_strategy_starts_with_existing_position_unmatched_pos_amount | python | hummingbot/hummingbot | test/hummingbot/strategy/spot_perpetual_arbitrage/test_spot_perpetual_arbitrage.py | https://github.com/hummingbot/hummingbot/blob/master/test/hummingbot/strategy/spot_perpetual_arbitrage/test_spot_perpetual_arbitrage.py | Apache-2.0 |
def get_landmarks_from_image(self, image_or_path, detected_faces=None, return_bboxes=False,
return_landmark_score=False):
"""Predict the landmarks for each face present in the image.
This function predicts a set of 68 2D or 3D images, one for each image present.
... | Predict the landmarks for each face present in the image.
This function predicts a set of 68 2D or 3D images, one for each image present.
If detect_faces is None the method will also run a face detector.
Arguments:
image_or_path {string or numpy.array or torch.tensor} -- The input... | get_landmarks_from_image | python | 1adrianb/face-alignment | face_alignment/api.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/api.py | BSD-3-Clause |
def get_landmarks_from_batch(self, image_batch, detected_faces=None, return_bboxes=False,
return_landmark_score=False):
"""Predict the landmarks for each face present in the image.
This function predicts a set of 68 2D or 3D images, one for each image in a batch in para... | Predict the landmarks for each face present in the image.
This function predicts a set of 68 2D or 3D images, one for each image in a batch in parallel.
If detect_faces is None the method will also run a face detector.
Arguments:
image_batch {torch.tensor} -- The input images batc... | get_landmarks_from_batch | python | 1adrianb/face-alignment | face_alignment/api.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/api.py | BSD-3-Clause |
def get_landmarks_from_directory(self, path, extensions=['.jpg', '.png'], recursive=True, show_progress_bar=True,
return_bboxes=False, return_landmark_score=False):
"""Scan a directory for images with a given extension type(s) and predict the landmarks for each
f... | Scan a directory for images with a given extension type(s) and predict the landmarks for each
face present in the images found.
Arguments:
path {str} -- path to the target directory containing the images
Keyword Arguments:
extensions {list of str} -- list containin... | get_landmarks_from_directory | python | 1adrianb/face-alignment | face_alignment/api.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/api.py | BSD-3-Clause |
def transform_np(point, center, scale, resolution, invert=False):
"""Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
... | Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
Arguments:
point {numpy.array} -- the input 2D point
c... | transform_np | python | 1adrianb/face-alignment | face_alignment/utils.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py | BSD-3-Clause |
def _get_preds_fromhm(hm, idx, center=None, scale=None):
"""Obtain (x,y) coordinates given a set of N heatmaps and the
coresponding locations of the maximums. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {to... | Obtain (x,y) coordinates given a set of N heatmaps and the
coresponding locations of the maximums. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W, H]
... | _get_preds_fromhm | python | 1adrianb/face-alignment | face_alignment/utils.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py | BSD-3-Clause |
def create_bounding_box(target_landmarks, expansion_factor=0.0):
"""
gets a batch of landmarks and calculates a bounding box that includes all the landmarks per set of landmarks in
the batch
:param target_landmarks: batch of landmarks of dim (n x 68 x 2). Where n is the batch size
:param expansion_f... |
gets a batch of landmarks and calculates a bounding box that includes all the landmarks per set of landmarks in
the batch
:param target_landmarks: batch of landmarks of dim (n x 68 x 2). Where n is the batch size
:param expansion_factor: expands the bounding box by this factor. For example, a `expansio... | create_bounding_box | python | 1adrianb/face-alignment | face_alignment/utils.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py | BSD-3-Clause |
def get_image(image_or_path):
"""Reads an image from file or array/tensor and converts it to RGB (H,W,3).
Arguments:
tensor {Sstring, numpy.array or torch.tensor} -- [the input image or path to it]
"""
if isinstance(image_or_path, str):
try:
image = io.imread(image_or_path)
... | Reads an image from file or array/tensor and converts it to RGB (H,W,3).
Arguments:
tensor {Sstring, numpy.array or torch.tensor} -- [the input image or path to it]
| get_image | python | 1adrianb/face-alignment | face_alignment/utils.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py | BSD-3-Clause |
def batch_detect(net, img_batch, target_size=128, device='cuda'):
"""
Inputs:
- net: BlazeFace model
- img_batch: a numpy array or tensor of shape (Batch size, Channels, Height, Width)
- target_size: target size of the input image
Outputs:
- list of 2-dim numpy arrays with sh... |
Inputs:
- net: BlazeFace model
- img_batch: a numpy array or tensor of shape (Batch size, Channels, Height, Width)
- target_size: target size of the input image
Outputs:
- list of 2-dim numpy arrays with shape (faces_on_this_image, 5): x1, y1, x2, y2, confidence
(x1, y... | batch_detect | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/detect.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/detect.py | BSD-3-Clause |
def predict_on_image(self, img):
"""Makes a prediction on a single image.
Arguments:
img: a NumPy array of shape (H, W, 3) or a PyTorch tensor of
shape (3, H, W). The image's height and width should be
128 pixels.
Returns:
A tensor with... | Makes a prediction on a single image.
Arguments:
img: a NumPy array of shape (H, W, 3) or a PyTorch tensor of
shape (3, H, W). The image's height and width should be
128 pixels.
Returns:
A tensor with face detections.
| predict_on_image | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/net_blazeface.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/net_blazeface.py | BSD-3-Clause |
def predict_on_batch(self, x):
"""Makes a prediction on a batch of images.
Arguments:
x: a NumPy array of shape (b, H, W, 3) or a PyTorch tensor of
shape (b, 3, H, W). The height and width should be 128 pixels.
Returns:
A list containing a tensor of face ... | Makes a prediction on a batch of images.
Arguments:
x: a NumPy array of shape (b, H, W, 3) or a PyTorch tensor of
shape (b, 3, H, W). The height and width should be 128 pixels.
Returns:
A list containing a tensor of face detections for each image in
t... | predict_on_batch | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/net_blazeface.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/net_blazeface.py | BSD-3-Clause |
def _tensors_to_detections(self, raw_box_tensor, raw_score_tensor, anchors):
"""The output of the neural network is a tensor of shape (b, 896, 16)
containing the bounding box regressor predictions, as well as a tensor
of shape (b, 896, 1) with the classification confidences.
This functi... | The output of the neural network is a tensor of shape (b, 896, 16)
containing the bounding box regressor predictions, as well as a tensor
of shape (b, 896, 1) with the classification confidences.
This function converts these two "raw" tensors into proper detections.
Returns a list of (n... | _tensors_to_detections | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/net_blazeface.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/net_blazeface.py | BSD-3-Clause |
def _decode_boxes(self, raw_boxes, anchors):
"""Converts the predictions into actual coordinates using
the anchor boxes. Processes the entire batch at once.
"""
boxes = torch.zeros_like(raw_boxes)
x_center = raw_boxes[..., 0] / self.x_scale * \
anchors[:, 2] + anchor... | Converts the predictions into actual coordinates using
the anchor boxes. Processes the entire batch at once.
| _decode_boxes | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/net_blazeface.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/net_blazeface.py | BSD-3-Clause |
def _weighted_non_max_suppression(self, detections):
"""The alternative NMS method as mentioned in the BlazeFace paper:
"We replace the suppression algorithm with a blending strategy that
estimates the regression parameters of a bounding box as a weighted
mean between the overlapping pr... | The alternative NMS method as mentioned in the BlazeFace paper:
"We replace the suppression algorithm with a blending strategy that
estimates the regression parameters of a bounding box as a weighted
mean between the overlapping predictions."
The original MediaPipe code assigns the sco... | _weighted_non_max_suppression | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/net_blazeface.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/net_blazeface.py | BSD-3-Clause |
def resize_and_crop_batch(frames, dim):
"""
Center crop + resize to (dim x dim)
inputs:
- frames: list of images (numpy arrays)
- dim: output dimension size
"""
smframes = []
xshift, yshift = 0, 0
for i in range(len(frames)):
smframe, (xshift, yshift) = resize_and_cro... |
Center crop + resize to (dim x dim)
inputs:
- frames: list of images (numpy arrays)
- dim: output dimension size
| resize_and_crop_batch | python | 1adrianb/face-alignment | face_alignment/detection/blazeface/utils.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/blazeface/utils.py | BSD-3-Clause |
def batch_detect(net, img_batch, device):
"""
Inputs:
- img_batch: a torch.Tensor of shape (Batch size, Channels, Height, Width)
"""
if 'cuda' in device:
torch.backends.cudnn.benchmark = True
batch_size = img_batch.size(0)
img_batch = img_batch.to(device, dtype=torch.float32)
... |
Inputs:
- img_batch: a torch.Tensor of shape (Batch size, Channels, Height, Width)
| batch_detect | python | 1adrianb/face-alignment | face_alignment/detection/sfd/detect.py | https://github.com/1adrianb/face-alignment/blob/master/face_alignment/detection/sfd/detect.py | BSD-3-Clause |
def accuracy(output: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torch.Tensor]:
r"""
Computes the precision@k for the specified values of k
"""
maxk = min(max(topk), output.shape[1])
batch_size = target.shape[0]
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
corre... |
Computes the precision@k for the specified values of k
| accuracy | python | mit-han-lab/tiny-training | algorithm/core/utils/basic.py | https://github.com/mit-han-lab/tiny-training/blob/master/algorithm/core/utils/basic.py | MIT |
def nelem_saved_for_backward(model, sample_input, backward_config, verbose=True, plot=False):
"""
calculate the memory required when saving for backward
:param model:
:param sample_input:
:param backward_config:
:param verbose: whether to print log
:param plot: whether to plot the distributi... |
calculate the memory required when saving for backward
:param model:
:param sample_input:
:param backward_config:
:param verbose: whether to print log
:param plot: whether to plot the distribution
:return:
| nelem_saved_for_backward | python | mit-han-lab/tiny-training | algorithm/core/utils/partial_backward.py | https://github.com/mit-han-lab/tiny-training/blob/master/algorithm/core/utils/partial_backward.py | MIT |
def visit_tuple_getitem(self, op):
"""
input: op.tuple_value
args: op.index
output: op
"""
item_gradients = self.grads[hex(op.handle.value)][0]
arg = op.tuple_value
addr = hex(arg.handle.value)
if addr not in self.grads:
self.grads[addr... |
input: op.tuple_value
args: op.index
output: op
| visit_tuple_getitem | python | mit-han-lab/tiny-training | compilation/autodiff/auto_diff.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/auto_diff.py | MIT |
def mcumean_grad(orig, grad):
"""Returns grad broadcasted to data dims"""
data, axis = orig.args[0], _get_reduce_axis(orig)
shape = data.checked_type.concrete_shape
# dtype = data.checked_type.dtype
dtype = "float32"
grad, data = [relay.cast(_, dtype) for _ in (grad, data)]
if axis is None:... | Returns grad broadcasted to data dims | mcumean_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops.py | MIT |
def concatenate_grad(orig, grad):
"""
Returns the gradient of concatenate, which is just the downstream gradient
split across the inputs.
"""
assert len(orig.args) == 1
t = orig.args[0]
# calculate split indices. TODO(@altanh): support Any?
axis_dims = [ty.shape[orig.attrs.axis] for ty ... |
Returns the gradient of concatenate, which is just the downstream gradient
split across the inputs.
| concatenate_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def _get_reduce_axis(call):
"""Helper function that returns the reduce axis of the call as plain python ints."""
x, axis = call.args[0], call.attrs.axis
shape = x.checked_type.concrete_shape
# should never exclude when axis is None
assert not (axis is None and call.attrs.exclude)
if axis is No... | Helper function that returns the reduce axis of the call as plain python ints. | _get_reduce_axis | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def _unreduce_expand(x, axis):
"""Helper function that returns x expanded on the reduced dimensions in axis."""
# assume axis is sorted nonnegative ints
for ax in axis:
x = expand_dims(x, ax)
return x | Helper function that returns x expanded on the reduced dimensions in axis. | _unreduce_expand | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def batch_matmul_grad(orig, grad):
"""gradient for nn.batch_matmul: in einsum LHS_bik,RHS_bjk->RES_bij
grads: GRAD_OUT_bij,RHS_bjk->GRAD_IN_LHS_bik
GRAD_OUT_bij,LHS_bik->GRAD_IN_RHS_bjk
"""
lhs, rhs = orig.args
if (orig.attrs["transpose_a"], orig.attrs["transpose_b"]) == (True, True):
... | gradient for nn.batch_matmul: in einsum LHS_bik,RHS_bjk->RES_bij
grads: GRAD_OUT_bij,RHS_bjk->GRAD_IN_LHS_bik
GRAD_OUT_bij,LHS_bik->GRAD_IN_RHS_bjk
| batch_matmul_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def batch_flatten_grad(orig, grad):
"""Returns grad reshaped to data dims"""
data = orig.args[0]
return [reshape_like(grad, data)] | Returns grad reshaped to data dims | batch_flatten_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def transpose_grad(orig, grad):
"""Returns grad transposed over the complement of original transpose axes"""
orig_axes = orig.attrs.axes
if orig_axes:
dims = len(orig_axes)
new_axes = [0] * dims
for i in range(dims):
new_axes[int(orig_axes[i])] = i
else:
new_a... | Returns grad transposed over the complement of original transpose axes | transpose_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def variance_grad(orig, grad):
"""Note that we take mean as an argument in the variance node"""
data, data_mean, axis = orig.args[0], orig.args[1], _get_reduce_axis(orig)
unbiased = orig.attrs.unbiased
shape = data.checked_type.concrete_shape
if axis is None:
axis = list(range(len(data.check... | Note that we take mean as an argument in the variance node | variance_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def stack_grad(orig, grad):
"""
Returns grad split across stacked inputs.
"""
stack_axis = int(orig.attrs.axis)
sections = len(orig.args[0].checked_type.fields)
splits = split(grad, sections, stack_axis)
splits = Tuple([squeeze(x, axis=[stack_axis]) for x in splits])
return [splits] |
Returns grad split across stacked inputs.
| stack_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def squeeze_grad(orig, grad):
"""
Returns grad expanded to input size.
"""
# this should work, can't use expand_dims since we lose
# squeeze information when axis=None
return [reshape_like(grad, orig.args[0])] |
Returns grad expanded to input size.
| squeeze_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def expand_dims_grad(orig, grad):
"""
Returns grad squeezed on expanded dims.
"""
axis = int(orig.attrs.axis)
for _ in range(orig.attrs.num_newaxis):
grad = squeeze(grad, axis=[axis])
return [grad] |
Returns grad squeezed on expanded dims.
| expand_dims_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def gather_nd_grad(orig, grad):
"""
Returns the gradient of gather_nd, which is simply scatter_nd.
"""
data, indices = orig.args
return [
scatter_nd(zeros_like(data), indices, grad, mode="add"),
zeros_like(indices),
] |
Returns the gradient of gather_nd, which is simply scatter_nd.
| gather_nd_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def strided_slice_grad(orig, grad):
"""
Returns the gradient of strided_slice, which is equal to grad where the
input was sliced and zero elsewhere.
"""
assert (
orig.attrs.axes is None
), "grad for strided_slice with axes is not yet supported"
x = orig.args[0]
begin = get_const_... |
Returns the gradient of strided_slice, which is equal to grad where the
input was sliced and zero elsewhere.
| strided_slice_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def one_hot_grad(orig, grad):
"""
Returns the gradient of one_hot, which is the sum of grad at on and off
indices for on_value and off_value respectively.
"""
indices, on_value, off_value = orig.args
g_zeros = zeros_like(grad)
on_mask = equal(orig, on_value)
grad_on = _sum(where(on_mask... |
Returns the gradient of one_hot, which is the sum of grad at on and off
indices for on_value and off_value respectively.
| one_hot_grad | python | mit-han-lab/tiny-training | compilation/autodiff/diff_ops_bakup.py | https://github.com/mit-han-lab/tiny-training/blob/master/compilation/autodiff/diff_ops_bakup.py | MIT |
def _pending_calls(self) -> Generator[int, None, None]:
"""Yield all message IDs with pending calls."""
yield from self._pending_subscribes.keys()
yield from self._pending_unsubscribes.keys()
yield from self._pending_publishes.keys() | Yield all message IDs with pending calls. | _pending_calls | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
async def subscribe(
self,
/,
topic: SubscribeTopic,
qos: int = 0,
options: SubscribeOptions | None = None,
properties: Properties | None = None,
*args: Any, # noqa: ANN401
timeout: float | None = None,
**kwargs: Any, # noqa: ANN401
) -> tupl... | Subscribe to a topic or wildcard.
Args:
topic: The topic or wildcard to subscribe to.
qos: The requested QoS level for the subscription.
options: (MQTT v5.0 only) Optional paho-mqtt subscription options.
properties: (MQTT v5.0 only) Optional paho-mqtt properties.... | subscribe | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
async def unsubscribe(
self,
/,
topic: str | list[str],
properties: Properties | None = None,
*args: Any, # noqa: ANN401
timeout: float | None = None,
**kwargs: Any, # noqa: ANN401
) -> None:
"""Unsubscribe from a topic or wildcard.
Args:
... | Unsubscribe from a topic or wildcard.
Args:
topic: The topic or wildcard to unsubscribe from.
properties: (MQTT v5.0 only) Optional paho-mqtt properties.
*args: Additional positional arguments to pass to paho-mqtt's unsubscribe
method.
timeout: Th... | unsubscribe | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
async def publish(
self,
/,
topic: str,
payload: PayloadType = None,
qos: int = 0,
retain: bool = False, # noqa: FBT001, FBT002
properties: Properties | None = None,
*args: Any, # noqa: ANN401
timeout: float | None = None,
**kwargs: Any, ... | Publish a message to the broker.
Args:
topic: The topic to publish to.
payload: The message payload.
qos: The QoS level to use for publication.
retain: If set to ``True``, the message will be retained by the broker.
properties: (MQTT v5.0 only) Option... | publish | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
def _on_connect(
self,
client: mqtt.Client, # noqa: ARG002
userdata: Any, # noqa: ARG002, ANN401
flags: mqtt.ConnectFlags, # noqa: ARG002
reason_code: ReasonCode,
properties: Properties | None = None, # noqa: ARG002
) -> None:
"""Called when we receive a C... | Called when we receive a CONNACK message from the broker. | _on_connect | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
def _on_subscribe(
self,
client: mqtt.Client, # noqa: ARG002
userdata: Any, # noqa: ARG002, ANN401
mid: int,
reason_codes: list[ReasonCode],
properties: Properties | None = None, # noqa: ARG002
) -> None:
"""Called when we receive a SUBACK message from the ... | Called when we receive a SUBACK message from the broker. | _on_subscribe | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
def _on_unsubscribe(
self,
client: mqtt.Client, # noqa: ARG002
userdata: Any, # noqa: ARG002, ANN401
mid: int,
reason_codes: list[ReasonCode], # noqa: ARG002
properties: Properties | None = None, # noqa: ARG002
) -> None:
"""Called when we receive an UNSUB... | Called when we receive an UNSUBACK message from the broker. | _on_unsubscribe | python | empicano/aiomqtt | aiomqtt/client.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/client.py | BSD-3-Clause |
def matches(self, wildcard: WildcardLike) -> bool:
"""Check if the topic matches a given wildcard.
Args:
wildcard: The wildcard to match against.
Returns:
True if the topic matches the wildcard, False otherwise.
"""
if not isinstance(wildcard, Wildcard):... | Check if the topic matches a given wildcard.
Args:
wildcard: The wildcard to match against.
Returns:
True if the topic matches the wildcard, False otherwise.
| matches | python | empicano/aiomqtt | aiomqtt/topic.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/topic.py | BSD-3-Clause |
def recurse(tl: list[str], wl: list[str]) -> bool:
"""Recursively match topic levels with wildcard levels."""
if not tl:
return not wl or wl[0] == "#"
if not wl:
return False
if wl[0] == "#":
return True
if tl[0]... | Recursively match topic levels with wildcard levels. | recurse | python | empicano/aiomqtt | aiomqtt/topic.py | https://github.com/empicano/aiomqtt/blob/master/aiomqtt/topic.py | BSD-3-Clause |
async def test_client_unsubscribe() -> None:
"""Test that messages are no longer received after unsubscribing from a topic."""
topic_1 = TOPIC_PREFIX + "test_client_unsubscribe/1"
topic_2 = TOPIC_PREFIX + "test_client_unsubscribe/2"
async def handle(tg: anyio.abc.TaskGroup) -> None:
is_first_me... | Test that messages are no longer received after unsubscribing from a topic. | test_client_unsubscribe | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_client_context_is_reusable() -> None:
"""Test that a client context manager instance is reusable."""
topic = TOPIC_PREFIX + "test_client_is_reusable"
client = Client(HOSTNAME)
async with client:
await client.publish(topic, "foo")
async with client:
await client.publish... | Test that a client context manager instance is reusable. | test_client_context_is_reusable | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_client_context_is_not_reentrant() -> None:
"""Test that a client context manager instance is not reentrant."""
client = Client(HOSTNAME)
async with client:
with pytest.raises(MqttReentrantError):
async with client:
pass | Test that a client context manager instance is not reentrant. | test_client_context_is_not_reentrant | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aenter_state_reset_connect_failure() -> None:
"""Test that internal state is reset on CONNECT failure in ``aenter``."""
client = Client(hostname="invalid")
with pytest.raises(MqttError):
await client.__aenter__()
assert not client._lock.locked()
assert not client._connected.do... | Test that internal state is reset on CONNECT failure in ``aenter``. | test_aenter_state_reset_connect_failure | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aenter_state_reset_connack_timeout() -> None:
"""Test that internal state is reset on CONNACK timeout in ``aenter``."""
client = Client(HOSTNAME, timeout=0)
with pytest.raises(MqttError):
await client.__aenter__()
assert not client._lock.locked()
assert not client._connected.d... | Test that internal state is reset on CONNACK timeout in ``aenter``. | test_aenter_state_reset_connack_timeout | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aenter_state_reset_connack_negative() -> None:
"""Test that internal state is reset on negative CONNACK in ``aenter``."""
client = Client(HOSTNAME, username="invalid")
with pytest.raises(MqttError):
await client.__aenter__()
assert not client._lock.locked()
assert not client._... | Test that internal state is reset on negative CONNACK in ``aenter``. | test_aenter_state_reset_connack_negative | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aexit_without_prior_aenter() -> None:
"""Test that ``aexit`` without prior (or unsuccessful) ``aenter`` runs cleanly."""
client = Client(HOSTNAME)
await client.__aexit__(None, None, None) | Test that ``aexit`` without prior (or unsuccessful) ``aenter`` runs cleanly. | test_aexit_without_prior_aenter | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aexit_consecutive_calls() -> None:
"""Test that ``aexit`` runs cleanly when it was already called before."""
async with Client(HOSTNAME) as client:
await client.__aexit__(None, None, None) | Test that ``aexit`` runs cleanly when it was already called before. | test_aexit_consecutive_calls | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aexit_client_is_already_disconnected_success() -> None:
"""Test that ``aexit`` runs cleanly if client is already cleanly disconnected."""
async with Client(HOSTNAME) as client:
client._disconnected.set_result(None) | Test that ``aexit`` runs cleanly if client is already cleanly disconnected. | test_aexit_client_is_already_disconnected_success | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_aexit_client_is_already_disconnected_failure() -> None:
"""Test that ``aexit`` reraises if client is already disconnected with an error."""
client = Client(HOSTNAME)
await client.__aenter__()
client._disconnected.set_exception(RuntimeError)
with pytest.raises(RuntimeError):
aw... | Test that ``aexit`` reraises if client is already disconnected with an error. | test_aexit_client_is_already_disconnected_failure | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_messages_view_is_reusable() -> None:
"""Test that ``.messages`` is reusable after dis- and reconnection."""
topic = TOPIC_PREFIX + "test_messages_generator_is_reusable"
client = Client(HOSTNAME)
async with client:
client._disconnected.set_result(None)
with pytest.raises(Mq... | Test that ``.messages`` is reusable after dis- and reconnection. | test_messages_view_is_reusable | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_messages_view_multiple_tasks_concurrently() -> None:
"""Test that ``.messages`` can be used concurrently by multiple tasks."""
topic = TOPIC_PREFIX + "test_messages_view_multiple_tasks_concurrently"
async with Client(HOSTNAME) as client, anyio.create_task_group() as tg:
async def han... | Test that ``.messages`` can be used concurrently by multiple tasks. | test_messages_view_multiple_tasks_concurrently | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
async def test_messages_view_len() -> None:
"""Test that the ``__len__`` method of the messages view works correctly."""
topic = TOPIC_PREFIX + "test_messages_view_len"
count = 3
class TestClient(Client):
fut: asyncio.Future[None] = asyncio.Future()
def _on_message(
self,
... | Test that the ``__len__`` method of the messages view works correctly. | test_messages_view_len | python | empicano/aiomqtt | tests/test_client.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_client.py | BSD-3-Clause |
def test_topic_validation() -> None:
"""Test that Topic raises Exceptions for invalid topics."""
with pytest.raises(TypeError):
Topic(True) # type: ignore[arg-type] # noqa: FBT003
with pytest.raises(TypeError):
Topic(1.0) # type: ignore[arg-type]
with pytest.raises(TypeError):
... | Test that Topic raises Exceptions for invalid topics. | test_topic_validation | python | empicano/aiomqtt | tests/test_topic.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_topic.py | BSD-3-Clause |
def test_wildcard_validation() -> None:
"""Test that Wildcard raises Exceptions for invalid wildcards."""
with pytest.raises(TypeError):
Wildcard(True) # type: ignore[arg-type] # noqa: FBT003
with pytest.raises(TypeError):
Wildcard(1.0) # type: ignore[arg-type]
with pytest.raises(TypeE... | Test that Wildcard raises Exceptions for invalid wildcards. | test_wildcard_validation | python | empicano/aiomqtt | tests/test_topic.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_topic.py | BSD-3-Clause |
def test_topic_matches() -> None:
"""Test that Topic.matches() does and doesn't match some test wildcards."""
topic = Topic("a/b/c")
assert topic.matches("a/b/c")
assert topic.matches("a/+/c")
assert topic.matches("+/+/+")
assert topic.matches("+/#")
assert topic.matches("#")
assert topi... | Test that Topic.matches() does and doesn't match some test wildcards. | test_topic_matches | python | empicano/aiomqtt | tests/test_topic.py | https://github.com/empicano/aiomqtt/blob/master/tests/test_topic.py | BSD-3-Clause |
def yaml_to_cli_args(yaml_file_path: str) -> List[str]:
"""
Convert a YAML file to structured CLI configuration arguments.
Args:
yaml_file_path (str): Path to the YAML file
Returns:
List[str]: List of CLI arguments in the format "key=value" or "nested.key=value"
Example:
>... |
Convert a YAML file to structured CLI configuration arguments.
Args:
yaml_file_path (str): Path to the YAML file
Returns:
List[str]: List of CLI arguments in the format "key=value" or "nested.key=value"
Example:
>>> yaml_to_cli_args("config.yaml")
['wandb.mode=disable... | yaml_to_cli_args | python | inclusionAI/AReaL | benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | https://github.com/inclusionAI/AReaL/blob/master/benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | Apache-2.0 |
def _flatten_dict_to_cli_args(data: dict, parent_key: str = "") -> List[str]:
"""
Recursively flatten a nested dictionary into CLI arguments.
Args:
data (dict): Dictionary to flatten
parent_key (str): Current parent key path
Returns:
List[str]: Flattened CLI arguments
"""
... |
Recursively flatten a nested dictionary into CLI arguments.
Args:
data (dict): Dictionary to flatten
parent_key (str): Current parent key path
Returns:
List[str]: Flattened CLI arguments
| _flatten_dict_to_cli_args | python | inclusionAI/AReaL | benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | https://github.com/inclusionAI/AReaL/blob/master/benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | Apache-2.0 |
def _format_value(value: Any) -> str:
"""
Format a value for CLI argument representation.
Args:
value: The value to format
Returns:
str: Formatted string representation of the value
"""
if isinstance(value, bool):
return str(value).lower()
elif isinstance(value, (in... |
Format a value for CLI argument representation.
Args:
value: The value to format
Returns:
str: Formatted string representation of the value
| _format_value | python | inclusionAI/AReaL | benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | https://github.com/inclusionAI/AReaL/blob/master/benchmark/verl_v0_3_0_post1_76084d3/build_cmd.py | Apache-2.0 |
def distribute(n, iterable):
"""Distribute the items from *iterable* among *n* smaller iterables.
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
[2, 4, 6]
If the length of *iterable* is not evenly divisible by *n*,... | Distribute the items from *iterable* among *n* smaller iterables.
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
[2, 4, 6]
If the length of *iterable* is not evenly divisible by *n*, then the
length of the returned... | distribute | python | inclusionAI/AReaL | evaluation/code_eval.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/code_eval.py | Apache-2.0 |
def undistribute(iterable):
"""
Undoes https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distribute .
Re-interleaves results that have been split using more_itertools.distribute:
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, ... |
Undoes https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distribute .
Re-interleaves results that have been split using more_itertools.distribute:
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
... | undistribute | python | inclusionAI/AReaL | evaluation/code_eval.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/code_eval.py | Apache-2.0 |
def distribute(n, iterable):
"""Distribute the items from *iterable* among *n* smaller iterables.
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
[2, 4, 6]
If the length of *iterable* is not evenly divisible by *n*,... | Distribute the items from *iterable* among *n* smaller iterables.
>>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
>>> list(group_1)
[1, 3, 5]
>>> list(group_2)
[2, 4, 6]
If the length of *iterable* is not evenly divisible by *n*, then the
length of the returned... | distribute | python | inclusionAI/AReaL | evaluation/math_eval.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/math_eval.py | Apache-2.0 |
def extract_program_output(pred_str, last_only=True):
"""Extract output between ```output\n...\n```, use regex, there might be
multiple outputs, each output may have multiple lines."""
outputs = re.findall(r"```output\n(.*?)\n```", pred_str, re.DOTALL)
if last_only:
return outputs[-1] if len(out... | Extract output between ```output
...
```, use regex, there might be
multiple outputs, each output may have multiple lines. | extract_program_output | python | inclusionAI/AReaL | evaluation/trajectory.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/trajectory.py | Apache-2.0 |
def run_test(sample, test=None, debug=False, timeout=6):
"""
if test(generated_code) is not None it'll try to run the code.
otherwise it'll just return an input and output pair.
"""
# Disable functionalities that can make destructive changes to the test.
reliability_guard()
if debug:
... |
if test(generated_code) is not None it'll try to run the code.
otherwise it'll just return an input and output pair.
| run_test | python | inclusionAI/AReaL | evaluation/code_verifier/testing_util.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/code_verifier/testing_util.py | Apache-2.0 |
def reliability_guard(maximum_memory_bytes=None):
"""
This disables various destructive functions and prevents the generated code
from interfering with the test (e.g. fork bomb, killing other processes,
removing filesystem files, etc.)
WARNING
This function is NOT a security sandbox. Untrusted c... |
This disables various destructive functions and prevents the generated code
from interfering with the test (e.g. fork bomb, killing other processes,
removing filesystem files, etc.)
WARNING
This function is NOT a security sandbox. Untrusted code, including, model-
generated code, should not be ... | reliability_guard | python | inclusionAI/AReaL | evaluation/code_verifier/testing_util.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/code_verifier/testing_util.py | Apache-2.0 |
def handle_gcd_lcm(f, args):
"""Return the result of gcd() or lcm(), as UnevaluatedExpr.
f: str - name of function ("gcd" or "lcm")
args: List[Expr] - list of function arguments
"""
args = tuple(map(sympy.nsimplify, args))
# gcd() and lcm() don't support evaluate=False
return sympy.Uneval... | Return the result of gcd() or lcm(), as UnevaluatedExpr.
f: str - name of function ("gcd" or "lcm")
args: List[Expr] - list of function arguments
| handle_gcd_lcm | python | inclusionAI/AReaL | evaluation/latex2sympy/latex2sympy2.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/latex2sympy/latex2sympy2.py | Apache-2.0 |
def get_simple_examples(func):
"""Returns an array of tuples, containing the string `input`, sympy
`output` using the provided sympy `func`, and `symbolically` boolean for
calling `compare`."""
return [
("1.1", func(1.1), False),
("6.9", func(6.9), False),
("3.5", func(3.5), Fals... | Returns an array of tuples, containing the string `input`, sympy
`output` using the provided sympy `func`, and `symbolically` boolean for
calling `compare`. | get_simple_examples | python | inclusionAI/AReaL | evaluation/latex2sympy/tests/context.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/latex2sympy/tests/context.py | Apache-2.0 |
def test_exp_command_symbol_multiplied():
"""\\exponentialE is NOT a function, so using the following notation
equates to multiplication."""
assert_equal("\\exponentialE (3)", E * 3)
assert_equal("\\exponentialE \\left( 3\\right)", E * 3)
assert_equal("\\exponentialE \\times 3", E * 3) | \exponentialE is NOT a function, so using the following notation
equates to multiplication. | test_exp_command_symbol_multiplied | python | inclusionAI/AReaL | evaluation/latex2sympy/tests/exp_test.py | https://github.com/inclusionAI/AReaL/blob/master/evaluation/latex2sympy/tests/exp_test.py | Apache-2.0 |
def process_math_data(file_path: str) -> List[Dict]:
"""Process math dataset from JSON/JSONL file"""
if not file_path:
return []
raw_data = load_jsonl(file_path)
processed = []
for index, item in enumerate(raw_data):
processed.append(
{
"task": "math",
... | Process math dataset from JSON/JSONL file | process_math_data | python | inclusionAI/AReaL | examples/data_preprocess/codeforce_process.py | https://github.com/inclusionAI/AReaL/blob/master/examples/data_preprocess/codeforce_process.py | Apache-2.0 |
def process_code_data(file_path: str) -> List[Dict]:
"""Process code dataset from JSONL file"""
if not file_path:
return []
raw_data = load_jsonl(file_path)
processed = []
for item in raw_data:
# Field extraction and transformation
input_output = item["code_test_cases"]
... | Process code dataset from JSONL file | process_code_data | python | inclusionAI/AReaL | examples/data_preprocess/codeforce_process.py | https://github.com/inclusionAI/AReaL/blob/master/examples/data_preprocess/codeforce_process.py | Apache-2.0 |
def load_id2info(file_path: Path) -> Dict:
"""Load ID mapping file with structure validation"""
try:
with file_path.open("r", encoding="utf-8") as f:
data = json.load(f)
if not all(isinstance(v, dict) and "solutions" in v for v in data.values()):
raise ValueError(... | Load ID mapping file with structure validation | load_id2info | python | inclusionAI/AReaL | examples/data_preprocess/math_process.py | https://github.com/inclusionAI/AReaL/blob/master/examples/data_preprocess/math_process.py | Apache-2.0 |
def main():
"""
Command line entry point
Example usage:
python math_process.py \
--prompts_path ./input/prompts.jsonl \
--id2info_path ./input/id2info.json \
--output_path ./output/processed.jsonl
"""
parser = argparse.ArgumentParser(
description="Math dataset proc... |
Command line entry point
Example usage:
python math_process.py --prompts_path ./input/prompts.jsonl --id2info_path ./input/id2info.json --output_path ./output/processed.jsonl
| main | python | inclusionAI/AReaL | examples/data_preprocess/math_process.py | https://github.com/inclusionAI/AReaL/blob/master/examples/data_preprocess/math_process.py | Apache-2.0 |
def download_from_huggingface(
repo_id: str, filename: str, revision: str = "main", repo_type: str = "dataset"
) -> str:
"""
Download a file from a HuggingFace Hub repository.
"""
try:
from huggingface_hub import hf_hub_download
except ImportError:
raise ImportError(
... |
Download a file from a HuggingFace Hub repository.
| download_from_huggingface | python | inclusionAI/AReaL | realhf/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/utils.py | Apache-2.0 |
def load_hf_or_local_file(path: str) -> str:
"""
Load a file from a HuggingFace Hub repository or a local file.
hf://<org>/<repo>/<filename>
hf://<org>/<repo>@<revision>/<filename>
e.g,
hf-dataset://inclusionAI/AReaL-RL-Data/data/boba_106k_0319.jsonl
=>
repo_type = dataset
repo_id =... |
Load a file from a HuggingFace Hub repository or a local file.
hf://<org>/<repo>/<filename>
hf://<org>/<repo>@<revision>/<filename>
e.g,
hf-dataset://inclusionAI/AReaL-RL-Data/data/boba_106k_0319.jsonl
=>
repo_type = dataset
repo_id = inclusionAI/AReaL-RL-Data
filename = data/boba_... | load_hf_or_local_file | python | inclusionAI/AReaL | realhf/utils.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/utils.py | Apache-2.0 |
def new(cls, mb_spec: "MicroBatchSpec", **kwargs):
"""Create new spec with updated fields while maintaining Omegaconf compatibility."""
fields = dict(
n_mbs=mb_spec.n_mbs,
max_tokens_per_mb=mb_spec.max_tokens_per_mb,
)
fields.update(kwargs)
return cls(**fi... | Create new spec with updated fields while maintaining Omegaconf compatibility. | new | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def __repr__(self):
"""Returns formatted string representation: '{class}[-critic]'."""
s = f"{self._class}"
if self.is_critic:
s += "-critic"
return s | Returns formatted string representation: '{class}[-critic]'. | __repr__ | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def __str__(self):
"""Returns compact string representation: 'Parallel(mp=X,pp=Y,dp=Z)'."""
return (
f"Parallel(mp={self.tensor_parallel_size},"
f"pp={self.pipeline_parallel_size},"
f"dp={self.data_parallel_size})"
) | Returns compact string representation: 'Parallel(mp=X,pp=Y,dp=Z)'. | __str__ | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def parallelism_eq(this, other):
"""Compare parallelism configurations (excluding sequence parallelism).
Note:
Implemented as static method to avoid OmegaConf compatibility issues.
"""
return (
(this.tensor_parallel_size == other.tensor_parallel_size)
... | Compare parallelism configurations (excluding sequence parallelism).
Note:
Implemented as static method to avoid OmegaConf compatibility issues.
| parallelism_eq | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def print_config_help(
config, prefix: str = "", parent_name: str = "", indent: int = 0
) -> None:
"""Prints help for a structured config with proper indentation and smart default display"""
if not is_dataclass(config):
return
for field in fields(config):
value = getattr(config, field.n... | Prints help for a structured config with proper indentation and smart default display | print_config_help | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def print_config_values(
config,
prefix: str = "",
parent_name: str = "",
indent: int = 0,
show_types: bool = True,
) -> None:
"""Prints current values with clean indentation and subtle separation"""
console.print() # Add space before
top_rule = Rule("Current Configuration Begin", styl... | Prints current values with clean indentation and subtle separation | print_config_values | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def _print_config_values_internal(
console: Console,
config,
prefix: str,
parent_name: str,
indent: int,
show_types: bool,
) -> None:
"""Internal recursive function that does the actual printing"""
if not is_dataclass(config):
return
for field in fields(config):
valu... | Internal recursive function that does the actual printing | _print_config_values_internal | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def print_runtime_helper(args):
"""Print comprehensive help with rich formatting"""
exp_type = args.__class__.__name__
# Main help panel
console.print(
Panel.fit(
f"[header]Setting {exp_type} with the Following Values[/header]",
border_style="border",
),
... | Print comprehensive help with rich formatting | print_runtime_helper | python | inclusionAI/AReaL | realhf/api/cli_args.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/cli_args.py | Apache-2.0 |
def gather(cls, samples: List["SequenceSample"], keys: Optional[List[str]] = None):
"""Gather a list of SequenceSample objects into a single batch.
:param samples: A list of SequenceSample objects to be gathered.
:type samples: List[SequenceSample]
:param keys: The keys to be gathered. ... | Gather a list of SequenceSample objects into a single batch.
:param samples: A list of SequenceSample objects to be gathered.
:type samples: List[SequenceSample]
:param keys: The keys to be gathered. Only a subset of keys can
be gathered. If None, the keys from the first sample will... | gather | python | inclusionAI/AReaL | realhf/api/core/data_api.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/core/data_api.py | Apache-2.0 |
def split_with_spec(self, spec: SequenceSplitSpec) -> List["SequenceSample"]:
"""Split the data according to the given spec."""
samples = []
data_offset = {k: 0 for k in self.keys}
for start, end in spec.partitions:
new_seqlens = {
k: lens_list[start:end] for ... | Split the data according to the given spec. | split_with_spec | python | inclusionAI/AReaL | realhf/api/core/data_api.py | https://github.com/inclusionAI/AReaL/blob/master/realhf/api/core/data_api.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.