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
_get_cache_path
def _get_cache_path(key, ext):filename = f"{hashlib.sha256(key).hexdigest()}{ext}"cache_dir = _THIS_DIR / "gen_images"cache_dir.mkdir(parents=True, exist_ok=True)return cache_dir / filename
1
5
2
32
2
32
36
32
null
['cache_dir', 'filename']
None
null
0
0
0
null
0
null
The function (_get_cache_path) defined within the public class called public.The function start at line 32 and ends at 36. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [32.0] and does not return any value..
pytorch_ao
public
public
0
0
_download
def _download(url, path):response = requests.get(url)response.raise_for_status()with open(path, "wb") as file:file.write(response.content)
1
5
2
38
1
39
43
39
null
['response']
None
null
0
0
0
null
0
null
The function (_download) defined within the public class called public.The function start at line 39 and ends at 43. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [39.0] and does not return any value..
pytorch_ao
public
public
0
0
_fetch_image
def _fetch_image(url):path = _get_cache_path(url.encode("utf-8"), ext=".svg")if not path.exists():_download(url, path)return os.sep + str(path.relative_to(_THIS_DIR))
2
5
1
48
1
46
50
46
null
['path']
None
null
0
0
0
null
0
null
The function (_fetch_image) defined within the public class called public.The function start at line 46 and ends at 50. It contains 5 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
_get_relpath
def _get_relpath(target, base):target = os.sep + targetbase = os.sep + basetarget_path, filename = os.path.split(target)rel_path = os.path.relpath(target_path, os.path.dirname(base))return os.path.normpath(os.path.join(rel_path, filename))
1
6
2
70
3
53
58
53
null
['rel_path', 'target', 'base']
None
null
0
0
0
null
0
null
The function (_get_relpath) defined within the public class called public.The function start at line 53 and ends at 58. It contains 6 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [53.0] and does not return any value..
pytorch_ao
public
public
0
0
run
def run(self, params, alt, section) -> List[nodes.Node]:url = f"https://img.shields.io/static/v1?{urlencode(params, quote_via=quote)}"path = _fetch_image(url)self.arguments = [path]self.options["alt"] = altif "class" not in self.options:self.options["class"] = []self.options["class"].append("shield-badge")target = _get...
2
11
4
100
0
62
72
62
null
[]
None
null
0
0
0
null
0
null
The function (run) defined within the public class called public.The function start at line 62 and ends at 72. It contains 11 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [62.0] and does not return any value..
pytorch_ao
public
public
0
0
run
def run(self):para = nodes.paragraph()self.state.nested_parse(StringList(_CARDLIST_START.split("\n")), self.content_offset, para)return [para]
1
6
1
38
0
127
132
127
null
[]
None
null
0
0
0
null
0
null
The function (run) defined within the public class called public.The function start at line 127 and ends at 132. It contains 6 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
run
def run(self):for key in ["header", "card_description", "link"]:if key not in self.options:raise ValueError(f"Key: `{key}` is missing")header = self.options["header"]link = self.options["link"]card_description = self.options["card_description"]tags = self.options.get("tags", "")if "image" in self.options:image = "<img ...
4
23
1
153
0
144
169
144
null
[]
None
null
0
0
0
null
0
null
The function (run) defined within the public class called public.The function start at line 144 and ends at 169. It contains 23 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
run
def run(self):para = nodes.paragraph()self.state.nested_parse(StringList(_CARDLIST_START.split("\n")), self.content_offset, para)return [para]
1
6
1
38
0
173
178
127
null
[]
None
null
0
0
0
null
0
null
The function (run) defined within the public class called public.The function start at line 173 and ends at 178. It contains 6 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
profiler_runner
def profiler_runner(path, fn, *args, **kwargs):with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,],record_shapes=True,) as prof:result = fn(*args, **kwargs)print(f"Saving trace under {path}")prof.export_chrome_trace(path)return result
1
12
4
72
1
17
28
17
null
['result']
None
null
0
0
0
null
0
null
The function (profiler_runner) defined within the public class called public.The function start at line 17 and ends at 28. It contains 12 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [17.0] and does not return any value..
pytorch_ao
public
public
0
0
show_anns
def show_anns(anns):if len(anns) == 0:returnsorted_anns = sorted(anns, key=(lambda x: x["area"]), reverse=True)ax = plt.gca()ax.set_autoscale_on(False)img = np.ones((sorted_anns[0]["segmentation"].shape[0],sorted_anns[0]["segmentation"].shape[1],4,))img[:, :, 3] = 0ms = []for ann in sorted_anns:m = ann["segmentation"]m...
3
22
1
164
6
31
53
31
null
['color_mask', 'img', 'm', 'sorted_anns', 'ax', 'ms']
None
null
0
0
0
null
0
null
The function (show_anns) defined within the public class called public.The function start at line 31 and ends at 53. It contains 22 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
timestamped_print
def timestamped_print(*args, **kwargs):# Get the current timestamptimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")# Prepend the timestamp to the original print argumentsprint(f"[{timestamp}]", *args, **kwargs)
1
3
2
32
1
25
29
25
null
['timestamp']
None
null
0
0
0
null
0
null
The function (timestamped_print) defined within the public class called public.The function start at line 25 and ends at 29. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [25.0] and does not return any value..
pytorch_ao
public
public
0
0
_get_center_point
def _get_center_point(mask):"""This is a rudimentary version of https://arxiv.org/pdf/2304.02643.pdf,section D.1.Point SamplingFrom the paper: "The first point is chosen deterministically as the pointfarthest from the object boundary."The code below is an approximation of this.First, we try to calculate the center of m...
20
55
1
324
10
34
142
34
null
['cur_col_idx', 'DISTANCE_GOOD_ENOUGH_THRESHOLD', 'max_distances', 'distance', 'global_coords', 'global_min_max_distance', 'cur_point', 'min_max_distance', 'cur_row_idx', 'distances_to_check_deg']
None
null
0
0
0
null
0
null
The function (_get_center_point) defined within the public class called public.The function start at line 34 and ends at 142. It contains 55 lines of code and it has a cyclomatic complexity of 20. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
main_docstring
def main_docstring():return f"""Args:checkpoint_path (str): Path to folder containing checkpoints from https://github.com/facebookresearch/sam2?tab=readme-ov-file#download-checkpointsmodel_type (str): Choose from one of {", ".join(MODEL_TYPES_TO_MODEL.keys())}input_path (str): Path to input imageoutput_path (str): Path...
1
1
0
7
0
155
162
155
null
[]
None
null
0
0
0
null
0
null
The function (main_docstring) defined within the public class called public.The function start at line 155 and ends at 162. It contains 1 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
main
def main(checkpoint_path,model_type,input_paths,amg_mask_folder,output_folder,output_format="png",verbose=False,fast=False,furious=False,load_fast="",overwrite=False,store_image=False,baseline=False,):# Input path validationinput_paths = [Path(input_path.strip())for input_path in Path(input_paths).read_text().splitline...
27
125
13
713
14
165
307
165
null
['image_tensor', 'points', 'rle_dict', 'masks', 'output_json_paths', 'input_paths', 'input_bytes', 'output_bytes', 'rle_json_paths', 'ax', 'filenames', 'buf', 'marker_size', 'output_image_paths']
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 165 and ends at 307. It contains 125 lines of code and it has a cyclomatic complexity of 27. It takes 13 parameters, represented as [165.0] and does not return any value..
pytorch_ao
public
public
0
0
main_docstring
def main_docstring():return f"""Args:checkpoint_path (str): Path to folder containing checkpoints from https://github.com/facebookresearch/sam2?tab=readme-ov-file#download-checkpointsmodel_type (str): Choose from one of {", ".join(MODEL_TYPES_TO_MODEL.keys())}input_path (str): Path to input imageoutput_path (str): Path...
1
1
0
7
0
25
32
25
null
[]
None
null
0
0
0
null
0
null
The function (main_docstring) defined within the public class called public.The function start at line 25 and ends at 32. It contains 1 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
main_headless
def main_headless(checkpoint_path,model_type,input_bytes,points_per_batch=1024,output_format="png",verbose=False,fast=False,furious=False,load_fast="",):device = "cuda"sam2_checkpoint, model_cfg = model_type_to_paths(checkpoint_path, model_type)if verbose:print(f"Loading model {sam2_checkpoint} with config {model_cfg}"...
7
44
9
223
6
35
80
35
null
['image_tensor', 'mask_generator', 'masks', 'device', 'sam2', 'buf']
None
null
0
0
0
null
0
null
The function (main_headless) defined within the public class called public.The function start at line 35 and ends at 80. It contains 44 lines of code and it has a cyclomatic complexity of 7. It takes 9 parameters, represented as [35.0] and does not return any value..
pytorch_ao
public
public
0
0
main
def main(checkpoint_path,model_type,input_path,output_path,points_per_batch=1024,output_format="png",verbose=False,fast=False,furious=False,load_fast="",):input_bytes = bytearray(open(input_path, "rb").read())output_bytes = main_headless(checkpoint_path,model_type,input_bytes,points_per_batch=points_per_batch,output_fo...
1
26
10
102
2
83
108
83
null
['input_bytes', 'output_bytes']
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 83 and ends at 108. It contains 26 lines of code and it has a cyclomatic complexity of 1. It takes 10 parameters, represented as [83.0] and does not return any value..
pytorch_ao
public
public
0
0
build
def build(self):import osimport numpy as npimport torchif self.baseline:from sam2.automatic_mask_generator import SAM2AutomaticMaskGeneratorfrom sam2.build_sam import build_sam2else:from torchao._models.sam2.automatic_mask_generator import (SAM2AutomaticMaskGenerator,)from torchao._models.sam2.build_sam import build_sa...
8
80
1
393
0
82
174
82
null
[]
None
null
0
0
0
null
0
null
The function (build) defined within the public class called public.The function start at line 82 and ends at 174. It contains 80 lines of code and it has a cyclomatic complexity of 8. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
decode_img_bytes
def decode_img_bytes(self, img_bytes_tensor, baseline=False):import torchimage_tensor = self.file_bytes_to_image_tensor(img_bytes_tensor)from torchvision.transforms import v2if not self.baseline:image_tensor = torch.from_numpy(image_tensor)image_tensor = image_tensor.permute((2, 0, 1))image_tensor = image_tensor.cuda()...
2
10
3
81
0
176
187
176
null
[]
None
null
0
0
0
null
0
null
The function (decode_img_bytes) defined within the public class called public.The function start at line 176 and ends at 187. It contains 10 lines of code and it has a cyclomatic complexity of 2. It takes 3 parameters, represented as [176.0] and does not return any value..
pytorch_ao
public
public
0
0
upload_rle.upload_rle_inner
def upload_rle_inner(input_bytes):image_tensor = self.file_bytes_to_image_tensor(input_bytes)masks = self.mask_generator.generate(image_tensor)return self.masks_to_rle_dict(masks)
1
4
1
30
0
191
194
191
null
[]
None
null
0
0
0
null
0
null
The function (upload_rle.upload_rle_inner) defined within the public class called public.The function start at line 191 and ends at 194. It contains 4 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
upload_rle
async def upload_rle(self, image):def upload_rle_inner(input_bytes):image_tensor = self.file_bytes_to_image_tensor(input_bytes)masks = self.mask_generator.generate(image_tensor)return self.masks_to_rle_dict(masks)return upload_rle_inner(bytearray(await image.read()))
1
3
2
22
0
190
196
190
null
[]
None
null
0
0
0
null
0
null
The function (upload_rle) defined within the public class called public.The function start at line 190 and ends at 196. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [190.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_amg_rle
def inference_amg_rle(self, input_bytes) -> dict:image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("amg", image_tensor, self.mask_generator)return self.masks_to_rle_dict(masks)
1
4
2
38
0
199
202
199
null
[]
None
null
0
0
0
null
0
null
The function (inference_amg_rle) defined within the public class called public.The function start at line 199 and ends at 202. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [199.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_amg_meta
def inference_amg_meta(self, input_bytes) -> dict:image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("amg", image_tensor, self.mask_generator)rle_dict = self.masks_to_rle_dict(masks)masks = {}for key in rle_dict:masks[key] = {"segmentation": rle_dict[key],"area": self.area_from_rle(rle_dict[key]),"...
2
12
2
93
0
205
216
205
null
[]
None
null
0
0
0
null
0
null
The function (inference_amg_meta) defined within the public class called public.The function start at line 205 and ends at 216. It contains 12 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [205.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_sps_rle
def inference_sps_rle(self, input_bytes, prompts) -> dict:import numpy as npprompts = np.array(prompts)prompts_label = np.array([1] * len(prompts))image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("sps",image_tensor,self.mask_generator,center_points=prompts,center_points_label=prompts_label,)masks...
1
15
3
101
0
219
234
219
null
[]
None
null
0
0
0
null
0
null
The function (inference_sps_rle) defined within the public class called public.The function start at line 219 and ends at 234. It contains 15 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [219.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_mps_rle
def inference_mps_rle(self, input_bytes, prompts) -> dict:import numpy as npprompts = np.array(prompts)prompts_label = np.array([1] * len(prompts))image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("mps",image_tensor,self.mask_generator,center_points=prompts,center_points_label=prompts_label,)masks...
2
15
3
97
0
237
252
237
null
[]
None
null
0
0
0
null
0
null
The function (inference_mps_rle) defined within the public class called public.The function start at line 237 and ends at 252. It contains 15 lines of code and it has a cyclomatic complexity of 2. It takes 3 parameters, represented as [237.0] and does not return any value..
pytorch_ao
public
public
0
0
plot_image_tensor
def plot_image_tensor(self, image_tensor, masks, output_format, prompts=None):from io import BytesIOimport matplotlib.pyplot as pltfig = plt.figure(figsize=(image_tensor.shape[1] / 100.0, image_tensor.shape[0] / 100.0),dpi=100,)plt.imshow(image_tensor)self.show_anns(masks, self.rle_to_mask, sort_by_area=False, seed=42)...
2
29
5
190
0
254
284
254
null
[]
None
null
0
0
0
null
0
null
The function (plot_image_tensor) defined within the public class called public.The function start at line 254 and ends at 284. It contains 29 lines of code and it has a cyclomatic complexity of 2. It takes 5 parameters, represented as [254.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_amg
def inference_amg(self, input_bytes, output_format="png"):image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("amg", image_tensor, self.mask_generator)return self.plot_image_tensor(image_tensor, masks, output_format)
1
4
3
44
0
287
290
287
null
[]
None
null
0
0
0
null
0
null
The function (inference_amg) defined within the public class called public.The function start at line 287 and ends at 290. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [287.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_sps
def inference_sps(self, input_bytes, prompts, output_format="png"):import numpy as npprompts = np.array(prompts)prompts_label = np.array([1] * len(prompts))image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("sps",image_tensor,self.mask_generator,center_points=prompts,center_points_label=prompts_lab...
1
17
4
111
0
293
310
293
null
[]
None
null
0
0
0
null
0
null
The function (inference_sps) defined within the public class called public.The function start at line 293 and ends at 310. It contains 17 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [293.0] and does not return any value..
pytorch_ao
public
public
0
0
inference_mps
def inference_mps(self, input_bytes, prompts, output_format="png"):import numpy as npprompts = np.array(prompts)prompts_label = np.array([1] * len(prompts))image_tensor = self.decode_img_bytes(input_bytes)masks = self.gen_masks("mps",image_tensor,self.mask_generator,center_points=prompts,center_points_label=prompts_lab...
2
17
4
107
0
313
330
313
null
[]
None
null
0
0
0
null
0
null
The function (inference_mps) defined within the public class called public.The function start at line 313 and ends at 330. It contains 17 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [313.0] and does not return any value..
pytorch_ao
public
public
0
0
get_center_points
def get_center_points(task_type, meta_path):with open(meta_path, "r") as file:amg_masks = list(json.load(file).values())amg_masks = sorted(amg_masks, key=(lambda x: x["area"]), reverse=True)# center points for biggest area first.center_points = [mask["center_point"] for mask in amg_masks]if task_type == "sps":center_po...
3
8
2
80
2
333
341
333
null
['amg_masks', 'center_points']
None
null
0
0
0
null
0
null
The function (get_center_points) defined within the public class called public.The function start at line 333 and ends at 341. It contains 8 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [333.0] and does not return any value..
pytorch_ao
public
public
0
0
timed_print
def timed_print(msg):from datetime import datetimecurrent_time = datetime.now()timestamp_with_nanoseconds = (current_time.strftime("%Y-%m-%d %H:%M:%S.")+ f"{current_time.microsecond * 1000:09d}")print(f"{str(timestamp_with_nanoseconds)}: {msg}")
1
8
1
34
2
344
352
344
null
['timestamp_with_nanoseconds', 'current_time']
None
null
0
0
0
null
0
null
The function (timed_print) defined within the public class called public.The function start at line 344 and ends at 352. 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
main.run_all
async def run_all(outputs):outputs = await asyncio.gather(*outputs)return outputs
1
3
1
17
0
442
444
442
null
[]
None
null
0
0
0
null
0
null
The function (main.run_all) defined within the public class called public.The function start at line 442 and ends at 444. 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
main
def main(task_type,input_paths,output_directory,output_rle=False,output_meta=False,meta_paths=None,baseline=False,name=None,):assert task_type in ["amg", "sps", "mps"]if task_type in ["sps", "mps"]:assert meta_paths is not Noneinput_paths = open(input_paths).read().split("\n")[:-1]for input_path in input_paths:assert P...
22
95
8
618
13
355
460
355
null
['outputs', 'output_path', 'output_paths', 'center_points', 'key', 'meta_paths', 'input_paths', 'output_directory', 'model', 'input_bytes', 'name', 'meta_path', 'meta_mapping']
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 355 and ends at 460. It contains 95 lines of code and it has a cyclomatic complexity of 22. It takes 8 parameters, represented as [355.0] 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
16
27
16
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 16 and ends at 27. 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
iou
def iou(mask1, mask2):assert mask1.dim() == 2assert mask2.dim() == 2intersection = torch.logical_and(mask1, mask2)union = torch.logical_or(mask1, mask2)return intersection.sum(dim=(-1, -2)) / union.sum(dim=(-1, -2))
1
6
2
73
2
36
41
36
null
['union', 'intersection']
None
null
0
0
0
null
0
null
The function (iou) defined within the public class called public.The function start at line 36 and ends at 41. It contains 6 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [36.0] 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
44
45
44
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 44 and ends at 45. 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
compare_masks
def compare_masks(masks, ref_masks, order_by_area=False, verbose=False):v0_areas = []v1_areas = []v0_masks = []v1_masks = []for k0 in ref_masks:assert k0 in masks, f"Expected {k0} to be in return data"v0_area = area_from_rle(ref_masks[k0])v1_area = area_from_rle(masks[k0])v0_areas.append(v0_area)v1_areas.append(v1_area...
8
33
4
276
11
48
84
48
null
['v0_areas', 'v1_area', 'v1_mask', 'v1_areas', 'miou_count', 'v0_area', 'v1_masks', 'miou_sum', 'equal_count', 'v0_masks', 'v0_mask']
None
null
0
0
0
null
0
null
The function (compare_masks) defined within the public class called public.The function start at line 48 and ends at 84. It contains 33 lines of code and it has a cyclomatic complexity of 8. It takes 4 parameters, represented as [48.0] and does not return any value..
pytorch_ao
public
public
0
0
compare_masks_str
def compare_masks_str(str0, str1, strict):masks0 = json.loads(str0)masks1 = json.loads(str1)if masks0.keys() != masks1.keys():if strict:return None, None, True# TODO: We might not want to order_by_area when comparing# masks from specific input points.m, e = compare_masks(masks0, masks1, order_by_area=True)return m, e, ...
3
8
3
67
2
87
97
87
null
['masks0', 'masks1']
None
null
0
0
0
null
0
null
The function (compare_masks_str) defined within the public class called public.The function start at line 87 and ends at 97. It contains 8 lines of code and it has a cyclomatic complexity of 3. It takes 3 parameters, represented as [87.0] and does not return any value..
pytorch_ao
public
public
0
0
compare
def compare(path0, path1, strict=False, compare_folders=False):# path0 are candidates and path1 the ground truthfail_count = 0miou_sum = 0.0miou_count = 0if compare_folders:path0, path1 = Path(path0), Path(path1)assert path0.is_dir()assert path1.is_dir()mask_files0 = [f.relative_to(path0) for f in list(path0.rglob("*.j...
9
29
4
256
5
100
131
100
null
['mask_files0', 'mask_files1', 'miou_count', 'miou_sum', 'fail_count']
None
null
0
0
0
null
0
null
The function (compare) defined within the public class called public.The function start at line 100 and ends at 131. It contains 29 lines of code and it has a cyclomatic complexity of 9. It takes 4 parameters, represented as [100.0] and does not return any value..
pytorch_ao
public
public
0
0
main
def main(path0, path1, strict=False, compare_folders=False):miou_count, miou_sum, fail_count = compare(path0, path1, strict=strict, compare_folders=compare_folders)print(f"fail_count: {fail_count} mIoU: {miou_sum / miou_count}")
1
5
4
40
0
134
138
134
null
[]
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 134 and ends at 138. It contains 5 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [134.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self,predictor: Optional[SAM2ImagePredictor],batch_size=1,points_per_batch=1024,aoti_compiled_model=None,furious=False,):super().__init__()self.predictor = predictorself.batch_size = batch_sizeself.points_per_batch = points_per_batchself.aoti_compiled_model = aoti_compiled_modelself.furious = furious
1
14
6
61
0
30
43
30
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 30 and ends at 43. It contains 14 lines of code and it has a cyclomatic complexity of 1. It takes 6 parameters, represented as [30.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self,high_res_feats,image_embed,image_pe,point_coords,point_labels,boxes: Optional[torch.Tensor] = None,mask_input: Optional[torch.Tensor] = None,multimask_output: bool = True,):assert high_res_feats[0].size() == (self.batch_size, 32, 256, 256)assert high_res_feats[1].size() == (self.batch_size, 64, 128, 12...
3
52
9
317
0
45
100
45
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 45 and ends at 100. It contains 52 lines of code and it has a cyclomatic complexity of 3. It takes 9 parameters, represented as [45.0] and does not return any value..
pytorch_ao
public
public
0
0
aot_compile
def aot_compile(model_directory,name,fn,sample_args,sample_kwargs=None,options=None,overwrite=False,):path = Path(model_directory) / Path(f"{name}.pt2")if path.exists() and not overwrite:raise ValueError(f"{path} already exists and overwrite is {overwrite}")print(f"Saving at {path=}")if options is None:options = {"max_...
4
26
7
121
4
103
128
103
null
['output_path', 'exported', 'options', 'path']
None
null
0
0
0
null
0
null
The function (aot_compile) defined within the public class called public.The function start at line 103 and ends at 128. It contains 26 lines of code and it has a cyclomatic complexity of 4. It takes 7 parameters, represented as [103.0] and does not return any value..
pytorch_ao
public
public
0
0
aot_load
def aot_load(path):return torch._export.aot_load(path, "cuda")
1
2
1
16
0
131
132
131
null
[]
None
null
0
0
0
null
0
null
The function (aot_load) defined within the public class called public.The function start at line 131 and ends at 132. 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, module, fn_name):super().__init__()self.module = moduleself.fn_name = fn_name
1
4
3
26
0
136
139
136
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 136 and ends at 139. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [136.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, *args):return getattr(self.module, self.fn_name)(*args)
1
2
2
23
0
141
142
141
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 141 and ends at 142. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [141.0] and does not return any value..
pytorch_ao
public
public
0
0
export_model
def export_model(mask_generator,model_directory,task_type,furious=False,batch_size=1,points_per_batch=None,overwrite=False,):if furious:set_furious(mask_generator)assert task_type in TASK_TYPES, f"Expected {task_type} to be one of {TASK_TYPES}"if task_type in ["sps", "amg"]:assert points_per_batch is not None, (f"Speci...
8
233
7
868
9
145
384
145
null
['example_input_image_pe', 'sam2_image_predict_masks', 'example_input_point_coords', 'example_input', 'example_input_image_embed', 'example_input_args', 'example_input_high_res_feats', 'example_input_kwargs', 'example_input_point_labels']
None
null
0
0
0
null
0
null
The function (export_model) defined within the public class called public.The function start at line 145 and ends at 384. It contains 233 lines of code and it has a cyclomatic complexity of 8. It takes 7 parameters, represented as [145.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self, aoti_compiled_model):super().__init__()self.aoti_compiled_model = aoti_compiled_model
1
3
2
19
0
388
390
388
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 388 and ends at 390. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [388.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, *args, **kwargs):return self.aoti_compiled_model(*args, **kwargs)
1
2
3
22
0
392
393
392
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 392 and ends at 393. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [392.0] and does not return any value..
pytorch_ao
public
public
0
0
__init__
def __init__(self, module, fn_name):super().__init__()self.module = moduleself.fn_name = fn_name
1
4
3
26
0
397
400
136
null
[]
None
null
0
0
0
null
0
null
The function (__init__) defined within the public class called public.The function start at line 397 and ends at 400. It contains 4 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [136.0] and does not return any value..
pytorch_ao
public
public
0
0
forward
def forward(self, *args):return self.aoti_compiled_model(*args)
1
2
2
16
0
402
403
402
null
[]
None
null
0
0
0
null
0
null
The function (forward) defined within the public class called public.The function start at line 402 and ends at 403. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [402.0] and does not return any value..
pytorch_ao
public
public
0
0
get_dense_pe
def get_dense_pe(self, *args, **kwargs) -> torch.Tensor:return self.other.get_dense_pe(*args, **kwargs)
1
2
3
28
0
405
406
405
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 405 and ends at 406. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [405.0] and does not return any value..
pytorch_ao
public
public
0
0
load_exported_model
def load_exported_model(mask_generator,model_directory,task_type,furious=False,batch_size=1,points_per_batch=1024,):if furious:set_furious(mask_generator)assert task_type in TASK_TYPES, f"Expected {task_type} to be one of {TASK_TYPES}"t0 = time.time()path = Path(model_directory) / Path("sam2_image_encoder.pt2")assert p...
10
63
6
409
4
409
477
409
null
['path', 'pkg_m', 't0', 'pkg']
None
null
0
0
0
null
0
null
The function (load_exported_model) defined within the public class called public.The function start at line 409 and ends at 477. It contains 63 lines of code and it has a cyclomatic complexity of 10. It takes 6 parameters, represented as [409.0] and does not return any value..
pytorch_ao
public
public
0
0
set_fast
def set_fast(mask_generator, task_type, loaded_exported_model=False, allow_recompiles=True):assert task_type in TASK_TYPES, f"Expected {task_type} to be one of {TASK_TYPES}"if not loaded_exported_model:# TODO: Using CUDA graphs can cause numerical differences?mask_generator.predictor.model.image_encoder = torch.compile...
7
47
4
283
0
480
536
480
null
[]
None
null
0
0
0
null
0
null
The function (set_fast) defined within the public class called public.The function start at line 480 and ends at 536. It contains 47 lines of code and it has a cyclomatic complexity of 7. It takes 4 parameters, represented as [480.0] and does not return any value..
pytorch_ao
public
public
0
0
set_furious
def set_furious(mask_generator):mask_generator.predictor.model.image_encoder = (mask_generator.predictor.model.image_encoder.to(torch.float16))# NOTE: Not baseline featuremask_generator.predictor._image_dtype = torch.float16mask_generator.predictor._transforms_device = mask_generator.predictor.devicetorch.set_float32_m...
1
11
1
92
0
539
551
539
null
[]
None
null
0
0
0
null
0
null
The function (set_furious) defined within the public class called public.The function start at line 539 and ends at 551. It contains 11 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
profiler_runner
def profiler_runner(path, fn, *args, **kwargs):with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,],record_shapes=True,) as prof:result = fn(*args, **kwargs)prof.export_chrome_trace(path)return result
1
11
4
67
1
29
39
29
null
['result']
None
null
0
0
0
null
0
null
The function (profiler_runner) 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 1. It takes 4 parameters, represented as [29.0] and does not return any value..
pytorch_ao
public
public
0
0
memory_runner
def memory_runner(path, fn, *args, **kwargs):print("Start memory recording")torch.cuda.synchronize()torch.cuda.memory._record_memory_history(True, trace_alloc_max_entries=100000, trace_alloc_record_context=True)result = fn(*args, **kwargs)torch.cuda.synchronize()snapshot = torch.cuda.memory._snapshot()print("Finish mem...
1
14
4
96
2
42
58
42
null
['result', 'snapshot']
None
null
0
0
0
null
0
null
The function (memory_runner) defined within the public class called public.The function start at line 42 and ends at 58. It contains 14 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [42.0] and does not return any value..
pytorch_ao
public
public
0
0
latencies_statistics
def latencies_statistics(data):# Convert the list to a NumPy arraydata_array = np.array(data)# Calculate the meanmean = np.mean(data_array)# Calculate the medianmedian = np.median(data_array)# Calculate the 90th percentilep90 = np.percentile(data_array, 90)# Calculate the 95th percentilep95 = np.percentile(data_array, ...
6
28
1
211
10
61
97
61
null
['max', 'p999', 'mean', 'data_array', 'p90', 'statistics_dict', 'argmax', 'p99', 'p95', 'median']
None
null
0
0
0
null
0
null
The function (latencies_statistics) defined within the public class called public.The function start at line 61 and ends at 97. It contains 28 lines of code and it has a cyclomatic complexity of 6. The function does not take any parameters and does not return any value..
pytorch_ao
public
public
0
0
timestamped_print
def timestamped_print(*args, **kwargs):# Get the current timestamptimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")# Prepend the timestamp to the original print argumentsprint(f"[{timestamp}]", *args, **kwargs)
1
3
2
32
1
100
104
100
null
['timestamp']
None
null
0
0
0
null
0
null
The function (timestamped_print) defined within the public class called public.The function start at line 100 and ends at 104. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [100.0] and does not return any value..
pytorch_ao
public
public
0
0
gen_masks_baseline
def gen_masks_baseline(task_type,image_tensor,mask_generator,center_points=None,center_points_label=None,):if task_type != "amg":assert center_points is not Noneassert center_points_label is not Noneif task_type == "amg":masks = mask_generator.generate(image_tensor)elif task_type == "sps":mask_generator.predictor.set_i...
6
37
5
235
2
108
144
108
null
['mask', 'masks']
None
null
0
0
0
null
0
null
The function (gen_masks_baseline) defined within the public class called public.The function start at line 108 and ends at 144. It contains 37 lines of code and it has a cyclomatic complexity of 6. It takes 5 parameters, represented as [108.0] and does not return any value..
pytorch_ao
public
public
0
0
gen_masks_ao_batch
def gen_masks_ao_batch(task_type,image_tensors,mask_generator,batch_size,center_points_batch=None,center_points_label_batch=None,):assert isinstance(image_tensors, list)assert len(image_tensors) <= batch_size# NOTE: We could create a smaller padding image of 0 size, but# image transforms will resize to full size anyway...
11
76
6
433
5
148
230
148
null
['result_masks', 'masks', 'center_points_label_torch_batch', 'center_points_torch_batch', 'scores']
None
null
0
0
0
null
0
null
The function (gen_masks_ao_batch) defined within the public class called public.The function start at line 148 and ends at 230. It contains 76 lines of code and it has a cyclomatic complexity of 11. It takes 6 parameters, represented as [148.0] and does not return any value..
pytorch_ao
public
public
0
0
gen_masks_ao
def gen_masks_ao(task_type,image_tensor,mask_generator,center_points=None,center_points_label=None,):if task_type == "amg":masks = mask_generator.generate(image_tensor)elif task_type == "sps":mask_generator.predictor.set_image(image_tensor)masks, scores, _ = mask_generator.predictor.predict(point_coords=center_points,p...
5
44
5
244
4
234
286
234
null
['scores', 'masks', 'center_points_torch', 'center_points_label_torch']
None
null
0
0
0
null
0
null
The function (gen_masks_ao) defined within the public class called public.The function start at line 234 and ends at 286. It contains 44 lines of code and it has a cyclomatic complexity of 5. It takes 5 parameters, represented as [234.0] and does not return any value..
pytorch_ao
public
public
0
0
gen_masks
def gen_masks(task_type,image_tensors,mask_generator,center_points_batch,center_points_label_batch,baseline,verbose,batch_size,):if verbose:for image_tensor in image_tensors:timestamped_print(f"Generating mask of size {tuple(image_tensor.shape)}.")if baseline:masks_batch = []for data_i in zip(image_tensors, center_poin...
8
46
8
169
2
289
334
289
null
['masks', 'masks_batch']
None
null
0
0
0
null
0
null
The function (gen_masks) defined within the public class called public.The function start at line 289 and ends at 334. It contains 46 lines of code and it has a cyclomatic complexity of 8. It takes 8 parameters, represented as [289.0] and does not return any value..
pytorch_ao
public
public
0
0
data_from_file_path
def data_from_file_path(task_type, verbose, meta_path, input_path, gpu_preproc, baseline):center_points, center_points_label = None, Noneif task_type != "amg":if verbose:timestamped_print(f"Loading meta from {meta_path}")with open(meta_path, "r") as file:amg_masks = list(json.load(file).values())amg_masks = sorted(amg_...
6
24
6
185
4
337
365
337
null
['amg_masks', 'center_points_label', 'img_bytes_tensor', 'center_points']
None
null
0
0
0
null
0
null
The function (data_from_file_path) defined within the public class called public.The function start at line 337 and ends at 365. It contains 24 lines of code and it has a cyclomatic complexity of 6. It takes 6 parameters, represented as [337.0] and does not return any value..
pytorch_ao
public
public
0
0
decode_img_bytes
def decode_img_bytes(img_bytes_tensors, gpu_preproc, baseline):image_tensors = []for img_bytes_tensor in img_bytes_tensors:with record_function("decode image bytes"):if gpu_preproc:image_tensor = file_bytes_to_image_tensor(img_bytes_tensor)from torchvision.transforms import ToTensor, v2if not baseline:image_tensor = to...
5
22
3
131
2
368
391
368
null
['image_tensors', 'image_tensor']
None
null
0
0
0
null
0
null
The function (decode_img_bytes) defined within the public class called public.The function start at line 368 and ends at 391. It contains 22 lines of code and it has a cyclomatic complexity of 5. It takes 3 parameters, represented as [368.0] and does not return any value..
pytorch_ao
public
public
0
0
rle_dict_from_masks
def rle_dict_from_masks(task_type, masks, mask_to_rle_pytorch):with record_function("mask_to_rle_pytorch"):if task_type == "sps":masks = mask_to_rle_pytorch(masks.unsqueeze(0))[0]masks = [{"segmentation": masks}]elif task_type == "mps":masks = mask_to_rle_pytorch(masks)masks = [{"segmentation": mask} for mask in masks]...
4
11
3
81
2
394
406
394
null
['masks', 'rle_dict']
None
null
0
0
0
null
0
null
The function (rle_dict_from_masks) defined within the public class called public.The function start at line 394 and ends at 406. It contains 11 lines of code and it has a cyclomatic complexity of 4. It takes 3 parameters, represented as [394.0] and does not return any value..
pytorch_ao
public
public
0
0
save_rle_dict_to_path
def save_rle_dict_to_path(rle_dict, output_rle_json_path, verbose):with record_function("json.dumps"):if verbose:timestamped_print(f"Storing rle under {output_rle_json_path}")output_rle_json_path.parent.mkdir(parents=False, exist_ok=True)with open(output_rle_json_path, "w") as file:file.write(json.dumps(rle_dict, inden...
2
7
3
62
0
409
415
409
null
[]
None
null
0
0
0
null
0
null
The function (save_rle_dict_to_path) defined within the public class called public.The function start at line 409 and ends at 415. It contains 7 lines of code and it has a cyclomatic complexity of 2. It takes 3 parameters, represented as [409.0] and does not return any value..
pytorch_ao
public
public
0
0
batched_zip
def batched_zip(input_paths, output_image_paths, output_rle_json_paths, meta_paths, batch_size):i = 0batch = []for input_path, output_image_path, output_rle_json_path, meta_path in zip(input_paths, output_image_paths, output_rle_json_paths, meta_paths):if i == batch_size:yield batchi = 0batch = []batch.append((input_pa...
4
16
5
81
2
418
433
418
null
['i', 'batch']
None
null
0
0
0
null
0
null
The function (batched_zip) defined within the public class called public.The function start at line 418 and ends at 433. It contains 16 lines of code and it has a cyclomatic complexity of 4. It takes 5 parameters, represented as [418.0] and does not return any value..
pytorch_ao
public
public
0
0
main_docstring
def main_docstring():return f"""Args:checkpoint_path (str): Path to folder containing checkpoints from https://github.com/facebookresearch/sam2?tab=readme-ov-file#download-checkpointsmodel_type (str): Choose from one of {", ".join(MODEL_TYPES_TO_MODEL.keys())}input_path (str): Path to input imageoutput_path (str): Path...
1
1
0
7
0
441
448
441
null
[]
None
null
0
0
0
null
0
null
The function (main_docstring) defined within the public class called public.The function start at line 441 and ends at 448. It contains 1 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
main
def main(checkpoint_path,model_type,task_type,input_paths,output_folder,points_per_batch=1024,output_format="png",verbose=False,fast=False,furious=False,overwrite=False,baseline=False,meta_folder=None,export_model="",load_exported_model="",num_images=None,allow_recompiles=False,quiet=False,gpu_preproc=False,batch_size=...
38
193
21
1,005
25
454
668
454
null
['t1', 'end_time', 'num_images', 'output_rle_json_paths', 'mask_generator', 'device', 'image_tensors', 'total_time', 'sam2', 'latencies', 'all_output_rle_json_paths', 'filenames', 'start_time', 'masks_batch', 'rle_dicts', 'num_batches', 'all_input_paths', 'input_paths', 'meta_paths', 'all_stats', 'output_image_paths', ...
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 454 and ends at 668. It contains 193 lines of code and it has a cyclomatic complexity of 38. It takes 21 parameters, represented as [454.0] and does not return any value..
pytorch_ao
public
public
0
0
cond_mkdir
def cond_mkdir(path, overwrite, resume, dry):if not dry:path.mkdir(exist_ok=(overwrite or resume), parents=True)
3
3
4
31
0
19
21
19
null
[]
None
null
0
0
0
null
0
null
The function (cond_mkdir) defined within the public class called public.The function start at line 19 and ends at 21. It contains 3 lines of code and it has a cyclomatic complexity of 3. It takes 4 parameters, represented as [19.0] and does not return any value..
pytorch_ao
public
public
0
0
run_script_with_args
def run_script_with_args(positional_args, keyword_args, dry=False, environ=None):assert isinstance(positional_args, list)assert isinstance(keyword_args, dict)# Construct the command with the base argumentscommand = ["python"] + positional_args# Add any additional arguments in the '--arg value' stylefor arg, value in ke...
7
28
4
209
4
24
56
24
null
['result', 'env_vars', 'command', 'environ']
None
null
0
0
0
null
0
null
The function (run_script_with_args) defined within the public class called public.The function start at line 24 and ends at 56. It contains 28 lines of code and it has a cyclomatic complexity of 7. It takes 4 parameters, represented as [24.0] and does not return any value..
pytorch_ao
public
public
0
0
main.run
def run(task, output_path: Path, kwargs, baseline_folder=None, environ=None):if baseline_folder is not None:baseline_folder = output_base_path / baseline_folderoutput_path = output_base_path / output_pathall_stats_file = Path(str(output_path) + "_stats.json")if all_stats_file.exists() and resume:with open(all_stats_fil...
19
70
5
487
0
81
153
81
null
[]
None
null
0
0
0
null
0
null
The function (main.run) defined within the public class called public.The function start at line 81 and ends at 153. It contains 70 lines of code and it has a cyclomatic complexity of 19. It takes 5 parameters, represented as [81.0] and does not return any value..
pytorch_ao
public
public
0
0
main.run_annotate
def run_annotate(image_paths, baseline_folder: Path, output_path: Path, overwrite, dry):output_path = output_base_path / output_pathbaseline_folder = output_base_path / baseline_folderif resume and output_path.exists():return None, Noneif not dry:output_path.mkdir(exist_ok=(overwrite or resume))stdout, stderr = run_scr...
5
21
5
91
0
155
175
155
null
[]
None
null
0
0
0
null
0
null
The function (main.run_annotate) defined within the public class called public.The function start at line 155 and ends at 175. It contains 21 lines of code and it has a cyclomatic complexity of 5. It takes 5 parameters, represented as [155.0] and does not return any value..
pytorch_ao
public
public
0
0
main.run_with_compare
def run_with_compare(task, output_path: Path, kwargs, environ=None):return run(task,output_path,kwargs,baseline_folder=f"baseline_{ttype}",environ=environ,)
1
8
4
34
0
188
195
188
null
[]
None
null
0
0
0
null
0
null
The function (main.run_with_compare) defined within the public class called public.The function start at line 188 and ends at 195. It contains 8 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [188.0] and does not return any value..
pytorch_ao
public
public
0
0
main.rwc_curry
def rwc_curry(output_path: Path, kwargs, environ):return run_with_compare(ttype,f"{ttype}_ao_ppb_{ppb}_" + output_path,kwargs | ppb_kwarg | meta_kwarg | batch_size_kwarg,environ=environ,)
1
7
3
34
0
205
211
205
null
[]
None
null
0
0
0
null
0
null
The function (main.rwc_curry) defined within the public class called public.The function start at line 205 and ends at 211. It contains 7 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [205.0] and does not return any value..
pytorch_ao
public
public
0
0
main.r_curry
def r_curry(output_path: Path, kwargs, environ):return run(ttype,f"{ttype}_ao_ppb_{ppb}_" + output_path,kwargs | ppb_kwarg | meta_kwarg | batch_size_kwarg,environ=environ,)
1
7
3
34
0
213
219
213
null
[]
None
null
0
0
0
null
0
null
The function (main.r_curry) defined within the public class called public.The function start at line 213 and ends at 219. It contains 7 lines of code and it has a cyclomatic complexity of 1. It takes 3 parameters, represented as [213.0] and does not return any value..
pytorch_ao
public
public
0
0
main
def main(image_paths,output_base_path,dry=False,overwrite=False,resume=False,batch_size=1,):assert batch_size > 0print("batch_size: ", batch_size)output_base_path = Path(output_base_path)print("output_base_path: ", output_base_path)result_csv_path = output_base_path / "result.csv"if not dry and not overwrite and result...
12
150
6
721
26
59
348
59
null
['batch_size_kwarg', 'environ_furious', 'environ_fast_load', 'furious_load_kwarg', 'run_script_time', 'output_path', 'all_keys', 'environ_load', 'normalized_data', 'results', 'ppb_kwarg', 'output_base_path', 'export_model_path', 'baseline_folder', 'ppb', 'kwargs', 'meta_kwarg', 'fast_load_kwarg', 'all_stats', 'load_exp...
None
null
0
0
0
null
0
null
The function (main) defined within the public class called public.The function start at line 59 and ends at 348. It contains 150 lines of code and it has a cyclomatic complexity of 12. It takes 6 parameters, represented as [59.0] and does not return any value..
pytorch_ao
public
public
0
0
download_file
def download_file(url, download_dir):# Create the directory if it doesn't existdownload_dir = Path(download_dir)download_dir.mkdir(parents=True, exist_ok=True)# Extract the file name from the URLfile_name = url.split("/")[-1]# Define the full path for the downloaded filefile_path = download_dir / file_name# Download th...
2
12
2
97
4
49
65
49
null
['download_dir', 'file_path', 'file_name', 'response']
None
null
0
0
0
null
0
null
The function (download_file) defined within the public class called public.The function start at line 49 and ends at 65. It contains 12 lines of code and it has a cyclomatic complexity of 2. It takes 2 parameters, represented as [49.0] and does not return any value..
pytorch_ao
public
public
0
0
example_shapes
def example_shapes():return [(848, 480, 3),(720, 1280, 3),(848, 480, 3),(1280, 720, 3),(480, 848, 3),(1080, 1920, 3),(1280, 720, 3),(1280, 720, 3),(720, 1280, 3),(848, 480, 3),(480, 848, 3),(864, 480, 3),(1920, 1080, 3),(1920, 1080, 3),(1280, 720, 3),(1232, 672, 3),(848, 480, 3),(848, 480, 3),(1920, 1080, 3),(1080, 192...
1
35
0
263
0
68
102
68
null
[]
None
null
0
0
0
null
0
null
The function (example_shapes) defined within the public class called public.The function start at line 68 and ends at 102. It contains 35 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
example_shapes_2
def example_shapes_2():return [(1080, 1920, 3),(1920, 1080, 3),(1920, 1080, 3),(1080, 1920, 3),(848, 480, 3),(864, 480, 3),(720, 1280, 3),(864, 480, 3),(848, 480, 3),(848, 480, 3),(848, 480, 3),(848, 480, 3),(720, 1280, 3),(864, 480, 3),(480, 848, 3),(1280, 720, 3),(720, 1280, 3),(1080, 1920, 3),(1080, 1920, 3),(1280, ...
1
35
0
263
0
105
139
105
null
[]
None
null
0
0
0
null
0
null
The function (example_shapes_2) defined within the public class called public.The function start at line 105 and ends at 139. It contains 35 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
iou
def iou(mask1, mask2):assert mask1.dim() == 2assert mask2.dim() == 2intersection = torch.logical_and(mask1, mask2)union = torch.logical_or(mask1, mask2)return intersection.sum(dim=(-1, -2)) / union.sum(dim=(-1, -2))
1
6
2
73
2
145
150
145
null
['union', 'intersection']
None
null
0
0
0
null
0
null
The function (iou) defined within the public class called public.The function start at line 145 and ends at 150. It contains 6 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [145.0] and does not return any value..
pytorch_ao
public
public
0
0
show_anns
def show_anns(anns, rle_to_mask, sort_by_area=True, seed=None):if len(anns) == 0:returnif sort_by_area:sorted_anns = sorted(anns, key=(lambda x: x["area"]), reverse=True)else:sorted_anns = annsax = plt.gca()ax.set_autoscale_on(False)for ann in sorted_anns:ann["segmentation"] = rle_to_mask(ann["segmentation"])img = np.o...
5
28
4
207
6
153
183
153
null
['color_mask', 'img', 'm', 'sorted_anns', 'ax', 'ms']
None
null
0
0
0
null
0
null
The function (show_anns) defined within the public class called public.The function start at line 153 and ends at 183. It contains 28 lines of code and it has a cyclomatic complexity of 5. It takes 4 parameters, represented as [153.0] and does not return any value..
pytorch_ao
public
public
0
0
profiler_runner
def profiler_runner(path, fn, *args, **kwargs):with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,],record_shapes=True,) as prof:result = fn(*args, **kwargs)prof.export_chrome_trace(path)return result
1
11
4
67
1
186
196
186
null
['result']
None
null
0
0
0
null
0
null
The function (profiler_runner) defined within the public class called public.The function start at line 186 and ends at 196. It contains 11 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [186.0] and does not return any value..
pytorch_ao
public
public
0
0
memory_runner
def memory_runner(path, fn, *args, **kwargs):print("Start memory recording")torch.cuda.synchronize()torch.cuda.memory._record_memory_history(True, trace_alloc_max_entries=100000, trace_alloc_record_context=True)result = fn(*args, **kwargs)torch.cuda.synchronize()snapshot = torch.cuda.memory._snapshot()print("Finish mem...
1
14
4
96
2
199
215
199
null
['result', 'snapshot']
None
null
0
0
0
null
0
null
The function (memory_runner) defined within the public class called public.The function start at line 199 and ends at 215. It contains 14 lines of code and it has a cyclomatic complexity of 1. It takes 4 parameters, represented as [199.0] and does not return any value..
pytorch_ao
public
public
0
0
image_tensor_to_masks
def image_tensor_to_masks(example_image, mask_generator):masks = mask_generator.generate(example_image)return masks
1
3
2
17
1
218
220
218
null
['masks']
None
null
0
0
0
null
0
null
The function (image_tensor_to_masks) defined within the public class called public.The function start at line 218 and ends at 220. It contains 3 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [218.0] and does not return any value..
pytorch_ao
public
public
0
0
image_tensors_to_masks
def image_tensors_to_masks(example_images, mask_generator):return mask_generator.generate_batch(example_images)
1
2
2
14
0
223
224
223
null
[]
None
null
0
0
0
null
0
null
The function (image_tensors_to_masks) defined within the public class called public.The function start at line 223 and ends at 224. It contains 2 lines of code and it has a cyclomatic complexity of 1. It takes 2 parameters, represented as [223.0] and does not return any value..
pytorch_ao
public
public
0
0
file_bytes_to_image_tensor
def file_bytes_to_image_tensor(file_bytes, output_format="numpy"):image_array = np.asarray(file_bytes, dtype=np.uint8)example_image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)example_image = cv2.cvtColor(example_image, cv2.COLOR_BGR2RGB)if output_format == "numpy":return example_imageif output_format not in ["torch"]...
3
12
2
81
2
227
239
227
null
['example_image', 'image_array']
None
null
0
0
0
null
0
null
The function (file_bytes_to_image_tensor) defined within the public class called public.The function start at line 227 and ends at 239. It contains 12 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [227.0] and does not return any value..
pytorch_ao
public
public
0
0
masks_to_rle_dict
def masks_to_rle_dict(masks):ret_data = {}for mask_id in range(len(masks)):ret_data[f"mask_{mask_id}"] = masks[mask_id]["segmentation"]return ret_data
2
5
1
35
1
242
246
242
null
['ret_data']
None
null
0
0
0
null
0
null
The function (masks_to_rle_dict) defined within the public class called public.The function start at line 242 and ends at 246. It contains 5 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
process_batch
def process_batch(batch, mask_generator):t = time.time()image_tensors = [image_tensor for (image_tensor, _) in batch]if len(batch) == 1:print(f"Processing batch of len {len(batch)} using generate")masks = [mask_generator.generate(image_tensors[0])]else:print(f"Processing batch of len {len(batch)} using generate_batch")...
3
12
2
78
3
254
265
254
null
['image_tensors', 't', 'masks']
None
null
0
0
0
null
0
null
The function (process_batch) defined within the public class called public.The function start at line 254 and ends at 265. It contains 12 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [254.0] and does not return any value..
pytorch_ao
public
public
0
0
batch_worker
async def batch_worker(mask_generator, batch_size, *, pad_batch=True, furious=False):while True:batch = []while len(batch) < batch_size and not request_queue.empty():batch.append(await request_queue.get())if batch:padded_batch = batchif pad_batch:padded_batch = batch + ([batch[-1]] * (batch_size - len(batch)))results =...
7
13
4
119
3
268
282
268
null
['results', 'batch', 'padded_batch']
None
null
0
0
0
null
0
null
The function (batch_worker) defined within the public class called public.The function start at line 268 and ends at 282. It contains 13 lines of code and it has a cyclomatic complexity of 7. It takes 4 parameters, represented as [268.0] and does not return any value..
pytorch_ao
public
public
0
0
lifespan
async def lifespan(app: FastAPI):# Startup logicmask_generator = app.state.mask_generatorbatch_size = app.state.batch_sizefurious = app.state.furioustask = asyncio.create_task(batch_worker(mask_generator, batch_size, furious=furious))yield# Shutdown logic (if needed)task.cancel()
1
9
1
51
4
286
296
286
null
['mask_generator', 'furious', 'batch_size', 'task']
None
null
0
0
0
null
0
null
The function (lifespan) defined within the public class called public.The function start at line 286 and ends at 296. It contains 9 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
benchmark_fn
def benchmark_fn(func, inp, mask_generator, warmup=3, runs=10):torch.cuda.empty_cache()torch.cuda.reset_peak_memory_stats()logging.info("Running {warmup} warmup iterations.")for _ in range(warmup):func(inp, mask_generator)logging.info("Running {runs} benchmark iterations.")t = time.time()for _ in range(runs):func(inp, ...
3
14
5
109
2
299
312
299
null
['t', 'avg_time_per_run']
None
null
0
0
0
null
0
null
The function (benchmark_fn) defined within the public class called public.The function start at line 299 and ends at 312. It contains 14 lines of code and it has a cyclomatic complexity of 3. It takes 5 parameters, represented as [299.0] and does not return any value..
pytorch_ao
public
public
0
0
max_memory_allocated_stats
def max_memory_allocated_stats():max_memory_allocated_bytes = torch.cuda.max_memory_allocated()_, total_memory = torch.cuda.mem_get_info()max_memory_allocated_percentage = int(100 * (max_memory_allocated_bytes / total_memory))return {"bytes": max_memory_allocated_bytes,"percentage": max_memory_allocated_percentage,}
1
10
0
47
2
315
324
315
null
['max_memory_allocated_bytes', 'max_memory_allocated_percentage']
None
null
0
0
0
null
0
null
The function (max_memory_allocated_stats) defined within the public class called public.The function start at line 315 and ends at 324. It contains 10 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
max_memory_allocated
def max_memory_allocated():stats = max_memory_allocated_stats()mib = stats["bytes"] >> 20print(f"max_memory_allocated_bytes: {mib}MiB")print(f"max_memory_allocated_percentage: {stats['percentage']}%")return mib, stats["percentage"]
1
6
0
35
2
327
332
327
null
['mib', 'stats']
None
null
0
0
0
null
0
null
The function (max_memory_allocated) defined within the public class called public.The function start at line 327 and ends at 332. It contains 6 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
unittest_fn
def unittest_fn(masks, ref_masks, order_by_area=False, verbose=False):from compare_rle_lists import compare_masksmiou, equal_count = compare_masks(masks, ref_masks, order_by_area=order_by_area, verbose=verbose)if equal_count == len(masks):print("Masks exactly match reference.")else:print(f"mIoU is {miou} with equal cou...
2
9
4
56
0
335
344
335
null
[]
None
null
0
0
0
null
0
null
The function (unittest_fn) defined within the public class called public.The function start at line 335 and ends at 344. It contains 9 lines of code and it has a cyclomatic complexity of 2. It takes 4 parameters, represented as [335.0] and does not return any value..
pytorch_ao
public
public
0
0
main_docstring
def main_docstring():return f"""Args:checkpoint_path (str): Path to folder containing checkpoints from https://github.com/facebookresearch/sam2?tab=readme-ov-file#download-checkpointsmodel_type (str): Choose from one of {", ".join(MODEL_TYPES_TO_MODEL.keys())}"""
1
1
0
7
0
370
375
370
null
[]
None
null
0
0
0
null
0
null
The function (main_docstring) defined within the public class called public.The function start at line 370 and ends at 375. It contains 1 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
model_type_to_paths
def model_type_to_paths(checkpoint_path, model_type):if model_type not in MODEL_TYPES_TO_CONFIG.keys():raise ValueError(f"Expected model_type to be one of {', '.join(MODEL_TYPES_TO_MODEL.keys())} but got {model_type}")sam2_checkpoint = Path(checkpoint_path) / Path(MODEL_TYPES_TO_MODEL[model_type])if not sam2_checkpoint...
3
14
2
75
2
378
391
378
null
['model_cfg', 'sam2_checkpoint']
None
null
0
0
0
null
0
null
The function (model_type_to_paths) defined within the public class called public.The function start at line 378 and ends at 391. It contains 14 lines of code and it has a cyclomatic complexity of 3. It takes 2 parameters, represented as [378.0] and does not return any value..
pytorch_ao
public
public
0
0
set_autoquant
def set_autoquant(mask_generator, autoquant_type, min_sqnr):import torchaofrom torchao import autoquant# NOTE: Not baseline featureif autoquant_type == "autoquant":mask_generator.predictor.model.image_encoder = autoquant(mask_generator.predictor.model.image_encoder, min_sqnr=min_sqnr)elif autoquant_type == "autoquant-f...
4
23
3
139
0
394
419
394
null
[]
None
null
0
0
0
null
0
null
The function (set_autoquant) defined within the public class called public.The function start at line 394 and ends at 419. It contains 23 lines of code and it has a cyclomatic complexity of 4. It takes 3 parameters, represented as [394.0] and does not return any value..
pytorch_ao
public
public
0
0
main.upload_rle
async def upload_rle(image: UploadFile = File(...)):image_tensor = file_bytes_to_image_tensor(bytearray(await image.read()))response_future = asyncio.Future()await request_queue.put((image_tensor, response_future))masks = await response_futurereturn masks_to_rle_dict(masks)
1
6
1
53
0
677
682
677
null
[]
None
null
0
0
0
null
0
null
The function (main.upload_rle) defined within the public class called public.The function start at line 677 and ends at 682. It contains 6 lines of code and it has a cyclomatic complexity of 1. The function does not take any parameters and does not return any value..