project_name
string
class_name
string
class_modifiers
string
class_implements
int64
class_extends
int64
function_name
string
function_body
string
cyclomatic_complexity
int64
NLOC
int64
num_parameter
int64
num_token
int64
num_variable
int64
start_line
int64
end_line
int64
function_index
int64
function_params
string
function_variable
string
function_return_type
string
function_body_line_type
string
function_num_functions
int64
function_num_lines
int64
outgoing_function_count
int64
outgoing_function_names
string
incoming_function_count
int64
incoming_function_names
string
lexical_representation
string
pytorch_ao
public
public
0
0
compute_axial_cis
def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0, device=None):freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim))freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim))t_x, t_y = init_t_xy(end_x, end_y, de...
1
15
5
167
4
173
188
173
null
['freqs_x', 'freqs_cis_x', 'freqs_y', 'freqs_cis_y']
None
null
0
0
0
null
0
null
The function (compute_axial_cis) defined within the public class called public.The function start at line 173 and ends at 188. It contains 15 lines of code and it has a cyclomatic complexity of 1. It takes 5 parameters, represented as [173.0] and does not return any value..
pytorch_ao
public
public
0
0
reshape_for_broadcast
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):ndim = x.ndimassert 0 <= 1 < ndimassert freqs_cis.shape == (x.shape[-2], x.shape[-1])shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]return freqs_cis.view(*shape)
3
6
2
80
2
191
196
191
null
['ndim', 'shape']
None
null
0
0
0
null
0
null
The function (reshape_for_broadcast) defined within the public class called public.The function start at line 191 and ends at 196. It contains 6 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [191.0] and does not return any value..
pytorch_ao
public
public
0
0
apply_rotary_enc
def apply_rotary_enc(xq: torch.Tensor,xk: torch.Tensor,freqs_cis: torch.Tensor,repeat_freqs_k: bool = False,):xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))xk_ = (torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))if xk.shape[-2] != 0else None)freqs_cis = reshape_for_broadcast(freqs...
5
24
4
266
6
199
226
199
null
['r', 'freqs_cis', 'xk_out', 'xk_', 'xq_out', 'xq_']
None
null
0
0
0
null
0
null
The function (apply_rotary_enc) defined within the public class called public.The function start at line 199 and ends at 226. It contains 24 lines of code and it has a cyclomatic complexity of 5. It takes 4 parameters, represented as [199.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,image_encoder,memory_attention,memory_encoder,num_maskmem=7,# default 1 input frame + 6 previous framesimage_size=512,backbone_stride=16,# stride of the image backbone outputsigmoid_scale_for_mem_enc=1.0,# scale factor for mask sigmoid probsigmoid_bias_for_mem_enc=0.0,# bias factor for mask sigmoid pr...
11
112
36
669
0
26
198
26
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 26 and ends at 198. It contains 112 lines of code and it has a cyclomatic complexity of 11. It takes 36 parameters, represented as [26.0] and does not return any value..
pytorch_ao
public
public
0
0
device
def device(self):return next(self.parameters()).device
1
2
1
16
0
201
202
201
null
[]
None
null
0
0
0
null
0
null
The function (device) defined within the public class called public.The function start at line 201 and ends at 202. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, *args, **kwargs):raise NotImplementedError("Please use the corresponding methods in SAM2VideoPredictor for inference or SAM2Train for training/fine-tuning""See notebooks/video_predictor_example.ipynb for an inference example.")
1
5
3
17
0
204
208
204
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 204 and ends at 208. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [204.0] and does not return any value..
pytorch_ao
public
public
0
0
_build_sam_heads
def _build_sam_heads(self):"""Build SAM-style prompt encoder and mask decoder."""self.sam_prompt_embed_dim = self.hidden_dimself.sam_image_embedding_size = self.image_size // self.backbone_stride# build PromptEncoder and MaskDecoder from SAM# (their hyperparameters like `mask_in_chans=16` are from SAM code)self.sam_pro...
5
42
1
249
0
210
258
210
null
[]
None
null
0
0
0
null
0
null
The function (_build_sam_heads) defined within the public class called public.The function start at line 210 and ends at 258. It contains 42 lines of code and it has a cyclomatic complexity of 5. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
_forward_sam_heads
def _forward_sam_heads(self,backbone_features,point_inputs=None,mask_inputs=None,high_res_features=None,multimask_output=False,):"""Forward SAM prompt encoders and mask heads.Inputs:- backbone_features: image features of [B, C, H, W] shape- point_inputs: a dictionary with "point_coords" and "point_labels", where1) "poi...
12
95
6
538
0
260
416
260
null
[]
None
null
0
0
0
null
0
null
The function (_forward_sam_heads) defined within the public class called public.The function start at line 260 and ends at 416. It contains 95 lines of code and it has a cyclomatic complexity of 12. It takes 6 parameters, represented as [260.0] and does not return any value..
pytorch_ao
public
public
0
0
_use_mask_as_output
def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):"""Directly turn binary `mask_inputs` into a output mask logits without using SAM.(same input and output shapes as in _forward_sam_heads above)."""# Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).out_sca...
4
39
4
248
0
418
468
418
null
[]
None
null
0
0
0
null
0
null
The function (_use_mask_as_output) defined within the public class called public.The function start at line 418 and ends at 468. It contains 39 lines of code and it has a cyclomatic complexity of 4. It takes 4 parameters, represented as [418.0] and does not return any value..
pytorch_ao
public
public
0
0
forward_image
def forward_image(self, img_batch: torch.Tensor):"""Get the image feature on the input batch."""backbone_out = self.image_encoder(img_batch)if self.use_high_res_features_in_sam:# precompute projected level 0 and level 1 features in SAM decoder# to avoid running it again on every SAM click# NOTE: These are 1x1 convoluti...
2
10
2
71
0
470
483
470
null
[]
None
null
0
0
0
null
0
null
The function (forward_image) defined within the public class called public.The function start at line 470 and ends at 483. It contains 10 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [470.0] and does not return any value..
pytorch_ao
public
public
0
0
_prepare_backbone_features
def _prepare_backbone_features(self, backbone_out):"""Prepare and flatten visual features."""backbone_out = backbone_out.copy()assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levelsfeature_maps = backbone_out["backbone_fpn"][-se...
4
10
2
148
0
485
499
485
null
[]
None
null
0
0
0
null
0
null
The function (_prepare_backbone_features) defined within the public class called public.The function start at line 485 and ends at 499. It contains 10 lines of code and it has a cyclomatic complexity of 4. It takes 2 parameters, represented as [485.0] and does not return any value..
pytorch_ao
public
public
0
0
_prepare_memory_conditioned_features
def _prepare_memory_conditioned_features(self,frame_idx,is_init_cond_frame,current_vision_feats,current_vision_pos_embeds,feat_sizes,output_dict,num_frames,track_in_reverse=False,# tracking in reverse time order (for demo usage)):"""Fuse the current frame's visual feature map with previous memory."""B = current_vision_...
34
138
9
999
0
501
687
501
null
[]
None
null
0
0
0
null
0
null
The function (_prepare_memory_conditioned_features) defined within the public class called public.The function start at line 501 and ends at 687. It contains 138 lines of code and it has a cyclomatic complexity of 34. It takes 9 parameters, represented as [501.0] and does not return any value..
pytorch_ao
public
public
0
0
_encode_new_memory
def _encode_new_memory(self,current_vision_feats,feat_sizes,pred_masks_high_res,object_score_logits,is_mask_from_pts,):"""Encode the current image and its prediction into a memory feature."""B = current_vision_feats[-1].size(1)# batch size on this frameC = self.hidden_dimH, W = feat_sizes[-1]# top-level (lowest-resolut...
10
40
6
253
0
689
739
689
null
[]
None
null
0
0
0
null
0
null
The function (_encode_new_memory) defined within the public class called public.The function start at line 689 and ends at 739. It contains 40 lines of code and it has a cyclomatic complexity of 10. It takes 6 parameters, represented as [689.0] and does not return any value..
pytorch_ao
public
public
0
0
_track_step
def _track_step(self,frame_idx,is_init_cond_frame,current_vision_feats,current_vision_pos_embeds,feat_sizes,point_inputs,mask_inputs,output_dict,num_frames,track_in_reverse,prev_sam_mask_logits,):current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}# High-resolution feature maps for the SAM head, res...
10
56
12
330
0
741
806
741
null
[]
None
null
0
0
0
null
0
null
The function (_track_step) defined within the public class called public.The function start at line 741 and ends at 806. It contains 56 lines of code and it has a cyclomatic complexity of 10. It takes 12 parameters, represented as [741.0] and does not return any value..
pytorch_ao
public
public
0
0
_encode_memory_in_output
def _encode_memory_in_output(self,current_vision_feats,feat_sizes,point_inputs,run_mem_encoder,high_res_masks,object_score_logits,current_out,):if run_mem_encoder and self.num_maskmem > 0:high_res_masks_for_mem_enc = high_res_masksmaskmem_features, maskmem_pos_enc = self._encode_new_memory(current_vision_feats=current_...
3
24
8
92
0
808
831
808
null
[]
None
null
0
0
0
null
0
null
The function (_encode_memory_in_output) defined within the public class called public.The function start at line 808 and ends at 831. It contains 24 lines of code and it has a cyclomatic complexity of 3. It takes 8 parameters, represented as [808.0] and does not return any value..
pytorch_ao
public
public
0
0
track_step
def track_step(self,frame_idx,is_init_cond_frame,current_vision_feats,current_vision_pos_embeds,feat_sizes,point_inputs,mask_inputs,output_dict,num_frames,track_in_reverse=False,# tracking in reverse time order (for demo usage)# Whether to run the memory encoder on the predicted masks. Sometimes we might want# to skip ...
2
52
13
160
0
834
899
834
null
[]
None
null
0
0
0
null
0
null
The function (track_step) defined within the public class called public.The function start at line 834 and ends at 899. It contains 52 lines of code and it has a cyclomatic complexity of 2. It takes 13 parameters, represented as [834.0] and does not return any value..
pytorch_ao
public
public
0
0
_use_multimask
def _use_multimask(self, is_init_cond_frame, point_inputs):"""Whether to use multimask output in the SAM head."""num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)multimask_output = (self.multimask_output_in_samand (is_init_cond_frame or self.multimask_output_for_tracking)and (self.multimask_...
5
8
3
56
0
901
909
901
null
[]
None
null
0
0
0
null
0
null
The function (_use_multimask) defined within the public class called public.The function start at line 901 and ends at 909. It contains 8 lines of code and it has a cyclomatic complexity of 5. It takes 3 parameters, represented as [901.0] and does not return any value..
pytorch_ao
public
public
0
0
_apply_non_overlapping_constraints
def _apply_non_overlapping_constraints(self, pred_masks):"""Apply non-overlapping constraints to the object scores in pred_masks. Here wekeep only the highest scoring object at each spatial location in pred_masks."""batch_size = pred_masks.size(0)if batch_size == 1:return pred_masksdevice = pred_masks.device# "max_obj_...
2
10
2
96
0
911
929
911
null
[]
None
null
0
0
0
null
0
null
The function (_apply_non_overlapping_constraints) defined within the public class called public.The function start at line 911 and ends at 929. It contains 10 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [911.0] and does not return any value..
pytorch_ao
public
public
0
0
select_closest_cond_frames
def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):"""Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`that are temporally closest to the current frame at `frame_idx`. Here, we take- a) the closest conditioning frame before `frame_idx` (if any);- b) the close...
14
23
3
197
6
19
61
19
null
['unselected_outputs', 'selected_outputs', 'inds_remain', 'idx_after', 'idx_before', 'num_remain']
None
null
0
0
0
null
0
null
The function (select_closest_cond_frames) defined within the public class called public.The function start at line 19 and ends at 61. It contains 23 lines of code and it has a cyclomatic complexity of 14. It takes 3 parameters, represented as [19.0] and does not return any value..
pytorch_ao
public
public
0
0
get_1d_sine_pe
def get_1d_sine_pe(pos_inds, dim, temperature=10000):"""Get 1D sine positional embedding as in the original Transformer paper."""pe_dim = dim // 2dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)pos_embed = pos_inds.unsqueeze(-1) / dim_tpos_embed...
1
7
3
84
3
64
74
64
null
['pos_embed', 'dim_t', 'pe_dim']
None
null
0
0
0
null
0
null
The function (get_1d_sine_pe) defined within the public class called public.The function start at line 64 and ends at 74. It contains 7 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [64.0] and does not return any value..
pytorch_ao
public
public
0
0
get_activation_fn
def get_activation_fn(activation):"""Return an activation function given a string"""if activation == "relu":return F.reluif activation == "gelu":return F.geluif activation == "glu":return F.gluraise RuntimeError(f"activation should be relu/gelu, not {activation}.")
4
8
1
39
0
77
85
77
null
[]
None
null
0
0
0
null
0
null
The function (get_activation_fn) defined within the public class called public.The function start at line 77 and ends at 85. It contains 8 lines of code and it has a cyclomatic complexity of 4. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
get_clones
def get_clones(module, N):return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
2
2
2
28
0
88
89
88
null
[]
None
null
0
0
0
null
0
null
The function (get_clones) defined within the public class called public.The function start at line 88 and ends at 89. It contains 2 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [88.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self, drop_prob=0.0, scale_by_keep=True):super(DropPath, self).__init__()self.drop_prob = drop_probself.scale_by_keep = scale_by_keep
1
4
3
35
0
94
97
94
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 94 and ends at 97. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [94.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x):if self.drop_prob == 0.0 or not self.training:return xkeep_prob = 1 - self.drop_probshape = (x.shape[0],) + (1,) * (x.ndim - 1)random_tensor = x.new_empty(shape).bernoulli_(keep_prob)if keep_prob > 0.0 and self.scale_by_keep:random_tensor.div_(keep_prob)return x * random_tensor
5
9
2
88
0
99
107
99
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 99 and ends at 107. It contains 9 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [99.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,input_dim: int,hidden_dim: int,output_dim: int,num_layers: int,activation: nn.Module = nn.ReLU,sigmoid_output: bool = False,) -> None:super().__init__()self.num_layers = num_layersh = [hidden_dim] * (num_layers - 1)self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [outpu...
2
17
7
111
0
113
129
113
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 113 and ends at 129. It contains 17 lines of code and it has a cyclomatic complexity of 2. It takes 7 parameters, represented as [113.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x):for i, layer in enumerate(self.layers):x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x)if self.sigmoid_output:x = F.sigmoid(x)return x
4
6
2
58
0
131
136
131
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 131 and ends at 136. It contains 6 lines of code and it has a cyclomatic complexity of 4. It takes 2 parameters, represented as [131.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self, num_channels: int, eps: float = 1e-6) -> None:super().__init__()self.weight = nn.Parameter(torch.ones(num_channels))self.bias = nn.Parameter(torch.zeros(num_channels))self.eps = eps
1
5
3
61
0
142
146
142
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 142 and ends at 146. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [142.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x: torch.Tensor) -> torch.Tensor:u = x.mean(1, keepdim=True)s = (x - u).pow(2).mean(1, keepdim=True)x = (x - u) / torch.sqrt(s + self.eps)x = self.weight[:, None, None] * x + self.bias[:, None, None]return x
1
6
2
93
0
148
153
148
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 148 and ends at 153. It contains 6 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [148.0] and does not return any value..
pytorch_ao
public
public
0
0
sample_box_points
def sample_box_points(masks: torch.Tensor,noise: float = 0.1,# SAM defaultnoise_bound: int = 20,# SAM defaulttop_left_label: int = 2,bottom_right_label: int = 3,) -> Tuple[np.array, np.array]:"""Sample a noised version of the top left and bottom right corners of a given `bbox`Inputs:- masks: [B, 1, H,W] boxes, dtype=to...
3
30
5
294
10
156
199
156
null
['img_bounds', 'bbox_w', 'max_dy', 'device', 'bbox_h', 'box_noise', 'box_labels', 'max_dx', 'noise_bound', 'box_coords']
None
null
0
0
0
null
0
null
The function (sample_box_points) defined within the public class called public.The function start at line 156 and ends at 199. It contains 30 lines of code and it has a cyclomatic complexity of 3. It takes 5 parameters, represented as [156.0] and does not return any value..
pytorch_ao
public
public
0
0
sample_random_points_from_errors
def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):"""Sample `num_pt` random points (along with their labels) independently from the error regions.Inputs:- gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool- pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None- num_pt: int, number of point...
4
22
3
235
11
202
249
202
null
['fp_masks', 'points', 'device', 'pts_x', 'pts_noise', 'fn_masks', 'pts_y', 'pred_masks', 'labels', 'all_correct', 'pts_idx']
None
null
0
0
0
null
0
null
The function (sample_random_points_from_errors) defined within the public class called public.The function start at line 202 and ends at 249. It contains 22 lines of code and it has a cyclomatic complexity of 4. It takes 3 parameters, represented as [202.0] and does not return any value..
pytorch_ao
public
public
0
0
sample_one_point_from_error_center
def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):"""Sample 1 random point (along with its label) from the center of each error region,that is, the point with the largest distance to the boundary of each error region.This is the RITM sampling method from https://github.com/saic-vul/ritm_interac...
8
37
3
398
16
252
314
252
null
['fn_mask_dt', 'fp_masks', 'fn_mask', 'points', 'fp_mask_dt_flat', 'is_positive', 'fp_mask', 'device', 'fp_mask_dt', 'pt_idx', 'fn_masks', 'fn_argmax', 'pred_masks', 'fp_argmax', 'fn_mask_dt_flat', 'labels']
None
null
0
0
0
null
0
null
The function (sample_one_point_from_error_center) defined within the public class called public.The function start at line 252 and ends at 314. It contains 37 lines of code and it has a cyclomatic complexity of 8. It takes 3 parameters, represented as [252.0] and does not return any value..
pytorch_ao
public
public
0
0
get_next_point
def get_next_point(gt_masks, pred_masks, method):if method == "uniform":return sample_random_points_from_errors(gt_masks, pred_masks)elif method == "center":return sample_one_point_from_error_center(gt_masks, pred_masks)else:raise ValueError(f"unknown sampling method {method}")
3
7
3
41
0
317
323
317
null
[]
None
null
0
0
0
null
0
null
The function (get_next_point) defined within the public class called public.The function start at line 317 and ends at 323. It contains 7 lines of code and it has a cyclomatic complexity of 3. It takes 3 parameters, represented as [317.0] and does not return any value..
pytorch_ao
public
public
0
0
do_pool
def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor:if pool is None:return x# (B, H, W, C) -> (B, C, H, W)x = x.permute(0, 3, 1, 2)x = pool(x)# (B, C, H', W') -> (B, H', W', C)x = x.permute(0, 2, 3, 1)if norm:x = norm(x)return x
3
9
3
79
1
24
35
24
null
['x']
None
null
0
0
0
null
0
null
The function (do_pool) defined within the public class called public.The function start at line 24 and ends at 35. It contains 9 lines of code and it has a cyclomatic complexity of 3. It takes 3 parameters, represented as [24.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,dim: int,dim_out: int,num_heads: int,q_pool: nn.Module = None,):super().__init__()self.dim = dimself.dim_out = dim_outself.num_heads = num_headsself.q_pool = q_poolself.qkv = nn.Linear(dim, dim_out * 3)self.proj = nn.Linear(dim_out, dim_out)
1
14
5
79
0
39
53
39
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 39 and ends at 53. It contains 14 lines of code and it has a cyclomatic complexity of 1. It takes 5 parameters, represented as [39.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x: torch.Tensor) -> torch.Tensor:B, H, W, _ = x.shape# qkv with shape (B, H * W, 3, nHead, C)qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1)# q, k, v with shape (B, H * W, nheads, C)q, k, v = torch.unbind(qkv, 2)# Q pooling (for downsample at stage changes)if self.q_pool:q = do_pool(q.resha...
4
32
2
310
0
55
96
55
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 55 and ends at 96. It contains 32 lines of code and it has a cyclomatic complexity of 4. It takes 2 parameters, represented as [55.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,dim: int,dim_out: int,num_heads: int,mlp_ratio: float = 4.0,drop_path: float = 0.0,norm_layer: Union[nn.Module, str] = "LayerNorm",q_stride: Tuple[int, int] = None,act_layer: nn.Module = nn.GELU,window_size: int = 0,):super().__init__()if isinstance(norm_layer, str):norm_layer = partial(getattr(nn, no...
5
41
10
257
0
100
147
100
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 100 and ends at 147. It contains 41 lines of code and it has a cyclomatic complexity of 5. It takes 10 parameters, represented as [100.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x: torch.Tensor) -> torch.Tensor:shortcut = x# B, H, W, Cx = self.norm1(x)# Skip connectionif self.dim != self.dim_out:shortcut = do_pool(self.proj(x), self.pool)# Window partitionwindow_size = self.window_sizeif window_size > 0:H, W = x.shape[1], x.shape[2]x, pad_hw = window_partition(x, window_size)...
5
21
2
206
0
149
181
149
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 149 and ends at 181. It contains 21 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [149.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,embed_dim: int = 96,# initial embed dimnum_heads: int = 1,# initial number of headsdrop_path_rate: float = 0.0,# stochastic depthq_pool: int = 3,# number of q_pool stagesq_stride: Tuple[int, int] = (2, 2),# downsample stride bet. stagesstages: Tuple[int, ...] = (2, 3, 16, 3),# blocks per stagedim_mul:...
12
78
7
568
0
189
286
189
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 189 and ends at 286. It contains 78 lines of code and it has a cyclomatic complexity of 12. It takes 7 parameters, represented as [189.0] and does not return any value..
pytorch_ao
public
public
0
0
_get_pos_embed
def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor:h, w = hwwindow_embed = self.pos_embed_windowpos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic")pos_embed = pos_embed + window_embed.tile([x // y for x, y in zip(pos_embed.shape, window_embed.shape)])pos_embed = pos_embed.permute(0, 2, 3, ...
1
9
2
78
0
288
296
288
null
[]
None
null
0
0
0
null
0
null
The function (_get_pos_embed) defined within the public class called public.The function start at line 288 and ends at 296. It contains 9 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [288.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:x = self.patch_embed(x)# x: (B, H, W, C)# Add pos embedx = x + self._get_pos_embed(x.shape[1:3])outputs = []for i, blk in enumerate(self.blocks):x = blk(x)if (i == self.stage_ends[-1]) or (i in self.stage_ends and self.return_interm_layers):feats = x.permute(0, 3...
5
12
2
112
0
298
314
298
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 298 and ends at 314. It contains 12 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [298.0] and does not return any value..
pytorch_ao
public
public
0
0
get_layer_id
def get_layer_id(self, layer_name):# https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33num_layers = self.get_num_layers()if layer_name.find("rel_pos") != -1:return num_layers + 1elif layer_name.find("pos_embed") != -1:return 0elif layer_name.find("patch_embed") != -1:return 0elif layer_name.find("...
5
12
2
95
0
316
329
316
null
[]
None
null
0
0
0
null
0
null
The function (get_layer_id) defined within the public class called public.The function start at line 316 and ends at 329. It contains 12 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [316.0] and does not return any value..
pytorch_ao
public
public
0
0
get_num_layers
def get_num_layers(self) -> int:return len(self.blocks)
1
2
1
14
0
331
332
331
null
[]
None
null
0
0
0
null
0
null
The function (get_num_layers) defined within the public class called public.The function start at line 331 and ends at 332. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,trunk: nn.Module,neck: nn.Module,scalp: int = 0,):super().__init__()self.trunk = trunkself.neck = neckself.scalp = scalpassert self.trunk.channel_list == self.neck.backbone_channel_list, (f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel...
1
13
4
63
0
15
27
15
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 15 and ends at 27. It contains 13 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [15.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, sample: torch.Tensor):# Forward through backbonewith torch.autograd.profiler.record_function("self.neck(self.trunk(sample))"):from torchao._models.sam2.map_tensor import MapTensor, to_map_tensorif isinstance(sample, MapTensor):features, pos = self.neck(self.trunk(sample.elems.flatten(0, 1)))features =...
5
18
2
171
0
29
50
29
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 29 and ends at 50. It contains 18 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [29.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,position_encoding: nn.Module,d_model: int,backbone_channel_list: List[int],kernel_size: int = 1,stride: int = 1,padding: int = 0,fpn_interp_model: str = "bilinear",fuse_type: str = "sum",fpn_top_down_levels: Optional[List[int]] = None,):"""Initialize the neck:param trunk: the backbone:param position_e...
3
36
10
192
0
60
108
60
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 60 and ends at 108. It contains 36 lines of code and it has a cyclomatic complexity of 3. It takes 10 parameters, represented as [60.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, xs: List[torch.Tensor]):out = [None] * len(self.convs)pos = [None] * len(self.convs)assert len(xs) == len(self.convs)# fpn forward pass# see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.pyprev_features = None# forward in top-down order (from low to high res...
6
28
2
208
0
110
141
110
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 110 and ends at 141. It contains 28 lines of code and it has a cyclomatic complexity of 6. It takes 2 parameters, represented as [110.0] and does not return any value..
pytorch_ao
public
public
0
0
window_partition
def window_partition(x, window_size):"""Partition into non-overlapping windows with padding if needed.Args:x (tensor): input tokens with [B, H, W, C].window_size (int): window size.Returns:windows: windows after partition with [B * num_windows, window_size, window_size, C].(Hp, Wp): padded height and width before parti...
3
12
2
137
4
16
38
16
null
['x', 'pad_w', 'pad_h', 'windows']
None
null
0
0
0
null
0
null
The function (window_partition) defined within the public class called public.The function start at line 16 and ends at 38. It contains 12 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [16.0] and does not return any value..
pytorch_ao
public
public
0
0
window_unpartition
def window_unpartition(windows, window_size, pad_hw, hw):"""Window unpartition into original sequences and removing padding.Args:x (tensor): input tokens with [B * num_windows, window_size, window_size, C].window_size (int): window size.pad_hw (Tuple): padded height and width (Hp, Wp).hw (Tuple): original height and wi...
3
11
4
105
2
41
62
41
null
['x', 'B']
None
null
0
0
0
null
0
null
The function (window_unpartition) defined within the public class called public.The function start at line 41 and ends at 62. It contains 11 lines of code and it has a cyclomatic complexity of 3. It takes 4 parameters, represented as [41.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,kernel_size: Tuple[int, ...] = (7, 7),stride: Tuple[int, ...] = (4, 4),padding: Tuple[int, ...] = (3, 3),in_chans: int = 3,embed_dim: int = 768,):"""Args:kernel_size (Tuple): kernel size of the projection layer.stride (Tuple): stride of the projection layer.padding (Tuple): padding size of the project...
1
12
3
95
0
70
89
70
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 70 and ends at 89. It contains 12 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [70.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.proj(x)# B C H W -> B H W Cx = x.permute(0, 2, 3, 1)return x
1
4
2
39
0
91
95
91
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 91 and ends at 95. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [91.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,*,transformer_dim: int,transformer: nn.Module,num_multimask_outputs: int = 3,activation: Type[nn.Module] = nn.GELU,iou_head_depth: int = 3,iou_head_hidden_dim: int = 256,use_high_res_features: bool = False,iou_prediction_use_sigmoid=False,dynamic_multimask_via_stability=False,dynamic_multimask_stabili...
6
69
15
356
0
16
109
16
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 16 and ends at 109. It contains 69 lines of code and it has a cyclomatic complexity of 6. It takes 15 parameters, represented as [16.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self,image_embeddings: torch.Tensor,image_pe: torch.Tensor,sparse_prompt_embeddings: torch.Tensor,dense_prompt_embeddings: torch.Tensor,multimask_output: bool,repeat_image: bool,high_res_features: Optional[List[torch.Tensor]] = None,) -> Tuple[torch.Tensor, torch.Tensor]:"""Predict masks given image and pro...
6
31
8
210
0
111
167
111
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 111 and ends at 167. It contains 31 lines of code and it has a cyclomatic complexity of 6. It takes 8 parameters, represented as [111.0] and does not return any value..
pytorch_ao
public
public
0
0
predict_masks
def predict_masks(self,image_embeddings: torch.Tensor,image_pe: torch.Tensor,sparse_prompt_embeddings: torch.Tensor,dense_prompt_embeddings: torch.Tensor,repeat_image: bool,high_res_features: Optional[List[torch.Tensor]] = None,) -> Tuple[torch.Tensor, torch.Tensor]:"""Predicts masks. See 'forward' for more details."""...
6
77
7
627
0
169
267
169
null
[]
None
null
0
0
0
null
0
null
The function (predict_masks) defined within the public class called public.The function start at line 169 and ends at 267. It contains 77 lines of code and it has a cyclomatic complexity of 6. It takes 7 parameters, represented as [169.0] and does not return any value..
pytorch_ao
public
public
0
0
_get_stability_scores
def _get_stability_scores(self, mask_logits):"""Compute stability scores of the mask logits based on the IoU between upper andlower thresholds."""mask_logits = mask_logits.flatten(-2)stability_delta = self.dynamic_multimask_stability_deltaarea_i = torch.sum(mask_logits > stability_delta, dim=-1).float()area_u = torch.s...
1
7
2
81
0
269
279
269
null
[]
None
null
0
0
0
null
0
null
The function (_get_stability_scores) defined within the public class called public.The function start at line 269 and ends at 279. It contains 7 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [269.0] and does not return any value..
pytorch_ao
public
public
0
0
_dynamic_multimask_via_stability
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):"""When outputting a single mask, if the stability score from the current single-maskoutput (based on output token 0) falls below a threshold, we instead select frommulti-mask outputs (based on output token 1~3) the mask with the highest predic...
1
26
3
182
0
281
317
281
null
[]
None
null
0
0
0
null
0
null
The function (_dynamic_multimask_via_stability) defined within the public class called public.The function start at line 281 and ends at 317. It contains 26 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [281.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,embed_dim: int,image_embedding_size: Tuple[int, int],input_image_size: Tuple[int, int],mask_in_chans: int,activation: Type[nn.Module] = nn.GELU,) -> None:"""Encodes prompts for input to SAM's mask decoder.Arguments:embed_dim (int): The prompts' embedding dimensionimage_embedding_size (tuple(int, int))...
2
33
6
213
0
17
65
17
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 17 and ends at 65. It contains 33 lines of code and it has a cyclomatic complexity of 2. It takes 6 parameters, represented as [17.0] and does not return any value..
pytorch_ao
public
public
0
0
get_dense_pe
def get_dense_pe(self) -> torch.Tensor:"""Returns the positional encoding used to encode point prompts,applied to a dense set of points the shape of the image encoding.Returns:torch.Tensor: Positional encoding with shape1x(embed_dim)x(embedding_h)x(embedding_w)"""return self.pe_layer(self.image_embedding_size).unsqueez...
1
2
1
24
0
67
76
67
null
[]
None
null
0
0
0
null
0
null
The function (get_dense_pe) defined within the public class called public.The function start at line 67 and ends at 76. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
_embed_points
def _embed_points(self,points: torch.Tensor,labels: torch.Tensor,pad: bool,) -> torch.Tensor:"""Embeds point prompts."""points = points + 0.5# Shift to center of pixelif pad:padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)p...
2
41
4
322
0
78
127
78
null
[]
None
null
0
0
0
null
0
null
The function (_embed_points) defined within the public class called public.The function start at line 78 and ends at 127. It contains 41 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [78.0] and does not return any value..
pytorch_ao
public
public
0
0
_embed_boxes
def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:"""Embeds box prompts."""boxes = boxes + 0.5# Shift to center of pixelcoords = boxes.reshape(-1, 2, 2)corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)corner_embedding[:, 0, :] += self.point_embeddings[2].weightcorner_embeddin...
1
9
2
86
0
129
138
129
null
[]
None
null
0
0
0
null
0
null
The function (_embed_boxes) defined within the public class called public.The function start at line 129 and ends at 138. It contains 9 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [129.0] and does not return any value..
pytorch_ao
public
public
0
0
_embed_masks
def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:"""Embeds mask inputs."""mask_embedding = self.mask_downscaling(masks)return mask_embedding
1
3
2
26
0
140
143
140
null
[]
None
null
0
0
0
null
0
null
The function (_embed_masks) defined within the public class called public.The function start at line 140 and ends at 143. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [140.0] and does not return any value..
pytorch_ao
public
public
0
0
_get_batch_size
def _get_batch_size(self,points: Optional[Tuple[torch.Tensor, torch.Tensor]],boxes: Optional[torch.Tensor],masks: Optional[torch.Tensor],) -> int:"""Gets the batch size of the output given the batch size of the input prompts."""if points is not None:return points[0].shape[0]elif boxes is not None:return boxes.shape[0]e...
4
14
4
89
0
145
161
145
null
[]
None
null
0
0
0
null
0
null
The function (_get_batch_size) defined within the public class called public.The function start at line 145 and ends at 161. It contains 14 lines of code and it has a cyclomatic complexity of 4. It takes 4 parameters, represented as [145.0] and does not return any value..
pytorch_ao
public
public
0
0
_get_device
def _get_device(self) -> torch.device:return self.point_embeddings[0].weight.device
1
2
1
20
0
163
164
163
null
[]
None
null
0
0
0
null
0
null
The function (_get_device) defined within the public class called public.The function start at line 163 and ends at 164. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self,points: Optional[Tuple[torch.Tensor, torch.Tensor]],boxes: Optional[torch.Tensor],masks: Optional[torch.Tensor],) -> Tuple[torch.Tensor, torch.Tensor]:"""Embeds different types of prompts, returning both sparse and denseembeddings.Arguments:points (tuple(torch.Tensor, torch.Tensor) or none): point coor...
4
24
4
224
0
166
214
166
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 166 and ends at 214. It contains 24 lines of code and it has a cyclomatic complexity of 4. It takes 4 parameters, represented as [166.0] and does not return any value..
pytorch_ao
public
public
0
0
sdp_kernel_context
def sdp_kernel_context(dropout_p):"""Get the context for the attention scaled dot-product kernel. We use Flash Attentionby default, but fall back to all available kernels if Flash Attention fails."""if ALLOW_ALL_KERNELS:return contextlib.nullcontext()return torch.backends.cuda.sdp_kernel(enable_flash=USE_FLASH_ATTN,# i...
4
8
1
47
0
31
44
31
null
[]
None
null
0
0
0
null
0
null
The function (sdp_kernel_context) defined within the public class called public.The function start at line 31 and ends at 44. It contains 8 lines of code and it has a cyclomatic complexity of 4. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,depth: int,embedding_dim: int,num_heads: int,mlp_dim: int,activation: Type[nn.Module] = nn.ReLU,attention_downsample_rate: int = 2,) -> None:"""A transformer decoder that attends to an input image usingqueries whose positional embedding is supplied.Args:depth (int): number of layers in the transformer...
2
30
7
150
0
48
91
48
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 48 and ends at 91. It contains 30 lines of code and it has a cyclomatic complexity of 2. It takes 7 parameters, represented as [48.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self,image_embedding: Tensor,image_pe: Tensor,point_embedding: Tensor,) -> Tuple[Tensor, Tensor]:"""Args:image_embedding (torch.Tensor): image to attend to. Should be shapeB x embedding_dim x h x w for any h and w.image_pe (torch.Tensor): the positional encoding to add to the image. Musthave the same shape ...
2
24
4
152
0
93
137
93
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 93 and ends at 137. It contains 24 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [93.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,embedding_dim: int,num_heads: int,mlp_dim: int = 2048,activation: Type[nn.Module] = nn.ReLU,attention_downsample_rate: int = 2,skip_first_layer_pe: bool = False,) -> None:"""A transformer block with four layers: (1) self-attention of sparseinputs, (2) cross attention of sparse inputs to dense inputs, ...
1
25
7
158
0
141
182
141
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 141 and ends at 182. It contains 25 lines of code and it has a cyclomatic complexity of 1. It takes 7 parameters, represented as [141.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:# Self attention blockif self.skip_first_layer_pe:queries = self.self_attn(q=queries, k=queries, v=queries)else:q = queries + query_peattn_out = self.self_attn(q=q, k=q, v=queries)queries = queries + attn_outquer...
2
24
5
196
0
184
215
184
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 184 and ends at 215. It contains 24 lines of code and it has a cyclomatic complexity of 2. It takes 5 parameters, represented as [184.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,embedding_dim: int,num_heads: int,downsample_rate: int = 1,dropout: float = 0.0,kv_in_dim: int = None,) -> None:super().__init__()self.embedding_dim = embedding_dimself.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dimself.internal_dim = embedding_dim // downsample_rateself.num_heads =...
2
21
6
148
0
224
246
224
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 224 and ends at 246. It contains 21 lines of code and it has a cyclomatic complexity of 2. It takes 6 parameters, represented as [224.0] and does not return any value..
pytorch_ao
public
public
0
0
_separate_heads
def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:b, n, c = x.shapex = x.reshape(b, n, num_heads, c // num_heads)return x.transpose(1, 2)# B x N_heads x N_tokens x C_per_head
1
4
3
47
0
248
251
248
null
[]
None
null
0
0
0
null
0
null
The function (_separate_heads) defined within the public class called public.The function start at line 248 and ends at 251. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [248.0] and does not return any value..
pytorch_ao
public
public
0
0
_recombine_heads
def _recombine_heads(self, x: Tensor) -> Tensor:b, n_heads, n_tokens, c_per_head = x.shapex = x.transpose(1, 2)return x.reshape(b, n_tokens, n_heads * c_per_head)# B x N_tokens x C
1
4
2
45
0
253
256
253
null
[]
None
null
0
0
0
null
0
null
The function (_recombine_heads) defined within the public class called public.The function start at line 253 and ends at 256. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [253.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:# Input projectionsq = self.q_proj(q)k = self.k_proj(k)v = self.v_proj(v)# Separate into headsq = self._separate_heads(q, self.num_heads)k = self._separate_heads(k, self.num_heads)v = self._separate_heads(v, self.num_heads)dropout_p = self.dropout_p if self.t...
2
14
4
147
0
258
293
258
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 258 and ends at 293. It contains 14 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [258.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,*args,rope_theta=10000.0,# whether to repeat q rope to match k length# this is needed for cross-attention to memoriesrope_k_repeat=False,feat_sizes=(32, 32),# [w, h] for stride 16 feats at 512 resolution**kwargs,):super().__init__(*args, **kwargs)self.compute_cis = partial(compute_axial_cis, dim=self....
1
15
6
87
0
299
316
299
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 299 and ends at 316. It contains 15 lines of code and it has a cyclomatic complexity of 1. It takes 6 parameters, represented as [299.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0) -> Tensor:# Input projectionsq = self.q_proj(q)k = self.k_proj(k)v = self.v_proj(v)# Separate into headsq = self._separate_heads(q, self.num_heads)k = self._separate_heads(k, self.num_heads)v = self._separate_heads(v, self.num_heads)# Apply...
4
30
5
280
0
318
373
318
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 318 and ends at 373. It contains 30 lines of code and it has a cyclomatic complexity of 4. It takes 5 parameters, represented as [318.0] and does not return any value..
pytorch_ao
public
public
0
0
__len__
def __len__(self):return self.b
1
2
1
9
0
25
26
25
null
[]
None
null
0
0
0
null
0
null
The function (__len__) defined within the public class called public.The function start at line 25 and ends at 26. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
nt_index_select_dim_0
def nt_index_select_dim_0(nt, index):values = nt.values()offsets = nt.offsets()lengths = offsets.diff()offsets_index = offsets[index].cpu()lengths_index = lengths[index].cpu()indices = [o + torch.arange(l) for (o, l) in zip(offsets_index, lengths_index)]indices = torch.cat(indices).to(values.device)values_index = torch...
2
11
2
123
7
29
39
29
null
['values_index', 'offsets_index', 'values', 'offsets', 'lengths', 'indices', 'lengths_index']
None
null
0
0
0
null
0
null
The function (nt_index_select_dim_0) defined within the public class called public.The function start at line 29 and ends at 39. It contains 11 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [29.0] and does not return any value..
pytorch_ao
public
public
0
0
nt_cat_dim_0
def nt_cat_dim_0(nts: List[torch.Tensor]):all_values = []all_lengths = []for nt in nts:all_values.append(nt.values())all_lengths.append(nt.offsets().diff())new_values = torch.cat(all_values)new_lengths = torch.cat(all_lengths)return torch.nested.nested_tensor_from_jagged(new_values, lengths=new_lengths)
2
9
1
78
4
42
50
42
null
['new_lengths', 'all_values', 'all_lengths', 'new_values']
None
null
0
0
0
null
0
null
The function (nt_cat_dim_0) defined within the public class called public.The function start at line 42 and ends at 50. It contains 9 lines of code and it has a cyclomatic complexity of 2. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self, **kwargs) -> None:for v in kwargs.values():assert isinstance(v, (list, np.ndarray, torch.Tensor, RLEData)), ("MaskData only supports list, numpy arrays, and torch tensors.")self._stats = dict(**kwargs)
2
6
2
51
0
60
65
60
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 60 and ends at 65. It contains 6 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [60.0] and does not return any value..
pytorch_ao
public
public
0
0
__setitem__
def __setitem__(self, key: str, item: Any) -> None:assert isinstance(item, (list, np.ndarray, torch.Tensor, RLEData)), ("MaskData only supports list, numpy arrays, and torch tensors.")self._stats[key] = item
1
5
3
46
0
67
71
67
null
[]
None
null
0
0
0
null
0
null
The function (__setitem__) defined within the public class called public.The function start at line 67 and ends at 71. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [67.0] and does not return any value..
pytorch_ao
public
public
0
0
__delitem__
def __delitem__(self, key: str) -> None:del self._stats[key]
1
2
2
18
0
73
74
73
null
[]
None
null
0
0
0
null
0
null
The function (__delitem__) defined within the public class called public.The function start at line 73 and ends at 74. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [73.0] and does not return any value..
pytorch_ao
public
public
0
0
__getitem__
def __getitem__(self, key: str) -> Any:return self._stats[key]
1
2
2
18
0
76
77
76
null
[]
None
null
0
0
0
null
0
null
The function (__getitem__) defined within the public class called public.The function start at line 76 and ends at 77. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [76.0] and does not return any value..
pytorch_ao
public
public
0
0
items
def items(self) -> ItemsView[str, Any]:return self._stats.items()
1
2
1
20
0
79
80
79
null
[]
None
null
0
0
0
null
0
null
The function (items) defined within the public class called public.The function start at line 79 and ends at 80. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
filter
def filter(self, keep: torch.Tensor) -> None:for k, v in self._stats.items():if v is None:self._stats[k] = Noneelif isinstance(v, torch.Tensor):# self._stats[k] = v[torch.as_tensor(keep, device=v.device)]self._stats[k] = v[keep]elif isinstance(v, np.ndarray):self._stats[k] = v[keep.detach().cpu().numpy()]elif isinstanc...
12
23
2
228
0
82
105
82
null
[]
None
null
0
0
0
null
0
null
The function (filter) defined within the public class called public.The function start at line 82 and ends at 105. It contains 23 lines of code and it has a cyclomatic complexity of 12. It takes 2 parameters, represented as [82.0] and does not return any value..
pytorch_ao
public
public
0
0
cat
def cat(self, new_stats: "MaskData") -> None:for k, v in new_stats.items():if k not in self._stats or self._stats[k] is None:self._stats[k] = deepcopy(v)elif isinstance(v, torch.Tensor):self._stats[k] = torch.cat([self._stats[k], v], dim=0)elif isinstance(v, np.ndarray):self._stats[k] = np.concatenate([self._stats[k], ...
8
24
2
269
0
107
130
107
null
[]
None
null
0
0
0
null
0
null
The function (cat) defined within the public class called public.The function start at line 107 and ends at 130. It contains 24 lines of code and it has a cyclomatic complexity of 8. It takes 2 parameters, represented as [107.0] and does not return any value..
pytorch_ao
public
public
0
0
to_numpy
def to_numpy(self) -> None:for k, v in self._stats.items():if isinstance(v, torch.Tensor):self._stats[k] = v.float().detach().cpu().numpy()
3
4
1
54
0
132
135
132
null
[]
None
null
0
0
0
null
0
null
The function (to_numpy) defined within the public class called public.The function start at line 132 and ends at 135. It contains 4 lines of code and it has a cyclomatic complexity of 3. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
is_box_near_crop_edge_torch
def is_box_near_crop_edge_torch(boxes: torch.Tensor,crop_box: List[int],crop_box_torch: torch.Tensor,orig_box_torch: torch.Tensor,atol: float = 20.0,) -> torch.Tensor:"""Filter masks at the edge of a crop, but not at the edge of the original image."""boxes = uncrop_boxes_xyxy(boxes, crop_box).float()near_crop_edge = to...
1
12
5
122
3
138
150
138
null
['near_image_edge', 'near_crop_edge', 'boxes']
None
null
0
0
0
null
0
null
The function (is_box_near_crop_edge_torch) defined within the public class called public.The function start at line 138 and ends at 150. It contains 12 lines of code and it has a cyclomatic complexity of 1. It takes 5 parameters, represented as [138.0] and does not return any value..
pytorch_ao
public
public
0
0
is_box_near_crop_edge
def is_box_near_crop_edge(boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0) -> torch.Tensor:crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)return is_box_near_crop_edge_to...
1
8
4
88
2
153
160
153
null
['orig_box_torch', 'crop_box_torch']
None
null
0
0
0
null
0
null
The function (is_box_near_crop_edge) defined within the public class called public.The function start at line 153 and ends at 160. It contains 8 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [153.0] and does not return any value..
pytorch_ao
public
public
0
0
box_xyxy_to_xywh
def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:box_xywh = deepcopy(box_xyxy)box_xywh[2] = box_xywh[2] - box_xywh[0]box_xywh[3] = box_xywh[3] - box_xywh[1]return box_xywh
1
5
1
49
1
163
167
163
null
['box_xywh']
None
null
0
0
0
null
0
null
The function (box_xyxy_to_xywh) defined within the public class called public.The function start at line 163 and ends at 167. It contains 5 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
batch_iterator
def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:assert len(args) > 0 and all(len(a) == len(args[0]) for a in args), ("Batched iteration must have inputs of all the same size.")n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)for b in range(n_batches):yield [arg[...
5
7
2
92
1
170
176
170
null
['n_batches']
None
null
0
0
0
null
0
null
The function (batch_iterator) defined within the public class called public.The function start at line 170 and ends at 176. It contains 7 lines of code and it has a cyclomatic complexity of 5. It takes 2 parameters, represented as [170.0] and does not return any value..
pytorch_ao
public
public
0
0
mask_to_rle_pytorch
def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:"""Encodes masks to an uncompressed RLE, in the format expected bypycoco tools."""# Put in fortran order and flatten h,wb, h, w = tensor.shapetensor = tensor.permute(0, 2, 1).flatten(1)# Compute change indicesdiff = tensor[:, 1:] ^ tensor[:, :-1]chan...
3
20
1
224
7
179
207
179
null
['out', 'cur_idxs', 'tensor', 'btw_idxs', 'change_indices', 'counts', 'diff']
None
null
0
0
0
null
0
null
The function (mask_to_rle_pytorch) defined within the public class called public.The function start at line 179 and ends at 207. It contains 20 lines of code and it has a cyclomatic complexity of 3. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
rle_to_mask
def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:"""Compute a binary mask from an uncompressed RLE."""h, w = rle["size"]mask = np.empty(h * w, dtype=bool)idx = 0parity = Falsefor count in rle["counts"]:mask[idx : idx + count] = parityidx += countparity ^= Truemask = mask.reshape(w, h)return mask.transpose()# Put in C...
2
11
1
85
3
210
221
210
null
['idx', 'mask', 'parity']
None
null
0
0
0
null
0
null
The function (rle_to_mask) defined within the public class called public.The function start at line 210 and ends at 221. It contains 11 lines of code and it has a cyclomatic complexity of 2. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
_mask_to_rle_pytorch_2_0_0
def _mask_to_rle_pytorch_2_0_0(tensor: torch.Tensor) -> (torch.Tensor, torch.Tensor):"""Encodes masks to an uncompressed RLE, in the format expected bypycoco tools."""# Put in fortran order and flatten h,wb, h, w = tensor.shapetensor = tensor.permute(0, 2, 1).flatten(1)# Compute change indicesdiff = tensor[:, 1:] ^ ten...
1
8
1
123
3
225
243
225
null
['a', 'tensor', 'diff']
None
null
0
0
0
null
0
null
The function (_mask_to_rle_pytorch_2_0_0) defined within the public class called public.The function start at line 225 and ends at 243. It contains 8 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
_mask_to_rle_pytorch_2_0_1
def _mask_to_rle_pytorch_2_0_1(tensor: torch.Tensor, diff: torch.Tensor, change_indices: torch.Tensor) -> (torch.Tensor, torch.Tensor):tensor = tensor.permute(0, 2, 1).flatten(1)alt_lens = diff.sum(dim=1)all_cur_idx = change_indices[:, 1]if all_cur_idx.numel() == 0:all_cur_idx_0 = all_cur_idxall_cur_idx_1 = all_cur_idx...
2
17
3
159
8
247
267
247
null
['all_cur_idx_0', 'counts_init', 'all_cur_idx', 'alt_lens', 'alt_lens_nt', 'tensor', 'all_btw_idx', 'all_cur_idx_1']
None
null
0
0
0
null
0
null
The function (_mask_to_rle_pytorch_2_0_1) defined within the public class called public.The function start at line 247 and ends at 267. It contains 17 lines of code and it has a cyclomatic complexity of 2. It takes 3 parameters, represented as [247.0] and does not return any value..
pytorch_ao
public
public
0
0
_mask_to_rle_pytorch_2_0
def _mask_to_rle_pytorch_2_0(tensor: torch.Tensor) -> RLEData:b, h, w = tensor.shapewith torch.autograd.profiler.record_function("mask_to_rle_pytorch_2: _mask_to_rle_pytorch_2_0_0"):diff = _mask_to_rle_pytorch_2_0_0(tensor)with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2: nonzero"):# NOTE: While we c...
2
19
1
139
3
270
294
270
null
['change_indices', 'num_chunks', 'diff']
None
null
0
0
0
null
0
null
The function (_mask_to_rle_pytorch_2_0) defined within the public class called public.The function start at line 270 and ends at 294. It contains 19 lines of code and it has a cyclomatic complexity of 2. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
_mask_to_rle_pytorch_2_1
def _mask_to_rle_pytorch_2_1(rle_data: RLEData):with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2: Encode run length"):out = []alt_lens = rle_data.alt_lens_nt.offsets().diff()all_btw_idx = rle_data.alt_lens_nt.values()alt_lens = alt_lens.tolist()all_btw_idx = all_btw_idx.tolist()counts_init = rle_data...
3
18
1
152
7
297
315
297
null
['out', 'counts_init', 'alt_lens', 'offset', 'all_btw_idx', 'btw_idxs', 'counts']
None
null
0
0
0
null
0
null
The function (_mask_to_rle_pytorch_2_1) defined within the public class called public.The function start at line 297 and ends at 315. It contains 18 lines of code and it has a cyclomatic complexity of 3. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
mask_to_rle_pytorch_2
def mask_to_rle_pytorch_2(tensor: torch.Tensor) -> List[Dict[str, Any]]:with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2"):return _mask_to_rle_pytorch_2_1(_mask_to_rle_pytorch_2_0(tensor))
1
3
1
39
0
318
320
318
null
[]
None
null
0
0
0
null
0
null
The function (mask_to_rle_pytorch_2) defined within the public class called public.The function start at line 318 and ends at 320. It contains 3 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
area_from_rle
def area_from_rle(rle: Dict[str, Any]) -> int:return sum(rle["counts"][1::2])
1
2
1
27
0
323
324
323
null
[]
None
null
0
0
0
null
0
null
The function (area_from_rle) defined within the public class called public.The function start at line 323 and ends at 324. It contains 2 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
calculate_stability_score
def calculate_stability_score(masks: torch.Tensor, mask_threshold: float, threshold_offset: float) -> torch.Tensor:"""Computes the stability score for a batch of masks. The stabilityscore is the IoU between the binary masks obtained by thresholdingthe predicted mask logits at high and low values."""# One mask is always...
1
14
3
100
2
329
349
329
null
['intersections', 'unions']
None
null
0
0
0
null
0
null
The function (calculate_stability_score) defined within the public class called public.The function start at line 329 and ends at 349. It contains 14 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [329.0] and does not return any value..
pytorch_ao
public
public
0
0
build_point_grid
def build_point_grid(n_per_side: int) -> np.ndarray:"""Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""offset = 1 / (2 * n_per_side)points_one_side = np.linspace(offset, 1 - offset, n_per_side)points_x = np.tile(points_one_side[None, :], (n_per_side, 1))points_y = np.tile(points_one_side[:, None], (1, n_p...
1
7
1
100
5
352
359
352
null
['points', 'points_one_side', 'points_x', 'offset', 'points_y']
None
null
0
0
0
null
0
null
The function (build_point_grid) defined within the public class called public.The function start at line 352 and ends at 359. It contains 7 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
build_all_layer_point_grids
def build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> List[np.ndarray]:"""Generates point grids for all crop layers."""points_by_layer = []for i in range(n_layers + 1):n_points = int(n_per_side / (scale_per_layer**i))points_by_layer.append(build_point_grid(n_points))return points_by_l...
2
8
3
60
2
362
370
362
null
['n_points', 'points_by_layer']
None
null
0
0
0
null
0
null
The function (build_all_layer_point_grids) defined within the public class called public.The function start at line 362 and ends at 370. It contains 8 lines of code and it has a cyclomatic complexity of 2. It takes 3 parameters, represented as [362.0] and does not return any value..