nnInteractive 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. nnInteractive/__init__.py +3 -0
  2. nnInteractive/inference/__init__.py +0 -0
  3. nnInteractive/inference/cvpr2025_challenge_baseline/__init__.py +0 -0
  4. nnInteractive/inference/cvpr2025_challenge_baseline/predict.py +173 -0
  5. nnInteractive/inference/inference_session.py +1400 -0
  6. nnInteractive/interaction/__init__.py +0 -0
  7. nnInteractive/interaction/point.py +166 -0
  8. nnInteractive/supervoxel/setup.py +4 -0
  9. nnInteractive/supervoxel/src/metadata.py +118 -0
  10. nnInteractive/supervoxel/src/reader.py +175 -0
  11. nnInteractive/supervoxel/src/run.py +136 -0
  12. nnInteractive/supervoxel/src/sam2/__init__.py +2 -0
  13. nnInteractive/supervoxel/src/sam2/sam2/__init__.py +11 -0
  14. nnInteractive/supervoxel/src/sam2/sam2/automatic_mask_generator.py +434 -0
  15. nnInteractive/supervoxel/src/sam2/sam2/benchmark.py +86 -0
  16. nnInteractive/supervoxel/src/sam2/sam2/build_sam.py +172 -0
  17. nnInteractive/supervoxel/src/sam2/sam2/modeling/__init__.py +5 -0
  18. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/__init__.py +5 -0
  19. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/hieradet.py +305 -0
  20. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/image_encoder.py +132 -0
  21. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/utils.py +89 -0
  22. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_attention.py +167 -0
  23. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_encoder.py +179 -0
  24. nnInteractive/supervoxel/src/sam2/sam2/modeling/position_encoding.py +217 -0
  25. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/__init__.py +5 -0
  26. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/mask_decoder.py +274 -0
  27. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/prompt_encoder.py +194 -0
  28. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/transformer.py +293 -0
  29. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_base.py +879 -0
  30. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_utils.py +315 -0
  31. nnInteractive/supervoxel/src/sam2/sam2/sam2_image_predictor.py +433 -0
  32. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor.py +1171 -0
  33. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor_legacy.py +1125 -0
  34. nnInteractive/supervoxel/src/sam2/sam2/utils/__init__.py +5 -0
  35. nnInteractive/supervoxel/src/sam2/sam2/utils/amg.py +332 -0
  36. nnInteractive/supervoxel/src/sam2/sam2/utils/misc.py +488 -0
  37. nnInteractive/supervoxel/src/sam2/sam2/utils/transforms.py +108 -0
  38. nnInteractive/supervoxel/src/sam2/setup.py +174 -0
  39. nnInteractive/supervoxel/src/sam2/training/__init__.py +5 -0
  40. nnInteractive/supervoxel/src/sam2/training/dataset/__init__.py +5 -0
  41. nnInteractive/supervoxel/src/sam2/training/dataset/sam2_datasets.py +176 -0
  42. nnInteractive/supervoxel/src/sam2/training/dataset/transforms.py +481 -0
  43. nnInteractive/supervoxel/src/sam2/training/dataset/utils.py +102 -0
  44. nnInteractive/supervoxel/src/sam2/training/dataset/vos_dataset.py +154 -0
  45. nnInteractive/supervoxel/src/sam2/training/dataset/vos_raw_dataset.py +290 -0
  46. nnInteractive/supervoxel/src/sam2/training/dataset/vos_sampler.py +103 -0
  47. nnInteractive/supervoxel/src/sam2/training/dataset/vos_segment_loader.py +289 -0
  48. nnInteractive/supervoxel/src/sam2/training/loss_fns.py +290 -0
  49. nnInteractive/supervoxel/src/sam2/training/model/__init__.py +5 -0
  50. nnInteractive/supervoxel/src/sam2/training/model/sam2.py +515 -0
  51. nnInteractive/supervoxel/src/sam2/training/optimizer.py +462 -0
  52. nnInteractive/supervoxel/src/sam2/training/scripts/sav_frame_extraction_submitit.py +157 -0
  53. nnInteractive/supervoxel/src/sam2/training/train.py +232 -0
  54. nnInteractive/supervoxel/src/sam2/training/trainer.py +1051 -0
  55. nnInteractive/supervoxel/src/sam2/training/utils/__init__.py +5 -0
  56. nnInteractive/supervoxel/src/sam2/training/utils/checkpoint_utils.py +328 -0
  57. nnInteractive/supervoxel/src/sam2/training/utils/data_utils.py +166 -0
  58. nnInteractive/supervoxel/src/sam2/training/utils/distributed.py +560 -0
  59. nnInteractive/supervoxel/src/sam2/training/utils/logger.py +236 -0
  60. nnInteractive/supervoxel/src/sam2/training/utils/train_utils.py +275 -0
  61. nnInteractive/supervoxel/src/supervoxel.py +198 -0
  62. nnInteractive/trainer/__init__.py +0 -0
  63. nnInteractive/trainer/nnInteractiveTrainer.py +24 -0
  64. nnInteractive/utils/__init__.py +0 -0
  65. nnInteractive/utils/bboxes.py +217 -0
  66. nnInteractive/utils/checkpoint_cleansing.py +9 -0
  67. nnInteractive/utils/crop.py +268 -0
  68. nnInteractive/utils/erosion_dilation.py +48 -0
  69. nnInteractive/utils/inference_helpers.py +45 -0
  70. nnInteractive/utils/os_shennanigans.py +16 -0
  71. nnInteractive/utils/rounding.py +13 -0
  72. nninteractive-2.0.0.dist-info/METADATA +511 -0
  73. nninteractive-2.0.0.dist-info/RECORD +76 -0
  74. nninteractive-2.0.0.dist-info/WHEEL +5 -0
  75. nninteractive-2.0.0.dist-info/licenses/LICENSE +201 -0
  76. nninteractive-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,232 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ import os
9
+ import random
10
+ import sys
11
+ import traceback
12
+ from argparse import ArgumentParser
13
+
14
+ import submitit
15
+ import torch
16
+
17
+ from hydra import compose, initialize_config_module
18
+ from hydra.utils import instantiate
19
+
20
+ from iopath.common.file_io import g_pathmgr
21
+ from omegaconf import OmegaConf
22
+
23
+ from training.utils.train_utils import makedir, register_omegaconf_resolvers
24
+
25
+ os.environ["HYDRA_FULL_ERROR"] = "1"
26
+
27
+
28
+ def single_proc_run(local_rank, main_port, cfg, world_size):
29
+ """Single GPU process"""
30
+ os.environ["MASTER_ADDR"] = "localhost"
31
+ os.environ["MASTER_PORT"] = str(main_port)
32
+ os.environ["RANK"] = str(local_rank)
33
+ os.environ["LOCAL_RANK"] = str(local_rank)
34
+ os.environ["WORLD_SIZE"] = str(world_size)
35
+ try:
36
+ register_omegaconf_resolvers()
37
+ except Exception as e:
38
+ logging.info(e)
39
+
40
+ trainer = instantiate(cfg.trainer, _recursive_=False)
41
+ trainer.run()
42
+
43
+
44
+ def single_node_runner(cfg, main_port: int):
45
+ assert cfg.launcher.num_nodes == 1
46
+ num_proc = cfg.launcher.gpus_per_node
47
+ torch.multiprocessing.set_start_method("spawn") # CUDA runtime does not support `fork`
48
+ if num_proc == 1:
49
+ # directly call single_proc so we can easily set breakpoints
50
+ # mp.spawn does not let us set breakpoints
51
+ single_proc_run(local_rank=0, main_port=main_port, cfg=cfg, world_size=num_proc)
52
+ else:
53
+ mp_runner = torch.multiprocessing.start_processes
54
+ args = (main_port, cfg, num_proc)
55
+ # Note: using "fork" below, "spawn" causes time and error regressions. Using
56
+ # spawn changes the default multiprocessing context to spawn, which doesn't
57
+ # interact well with the dataloaders (likely due to the use of OpenCV).
58
+ mp_runner(single_proc_run, args=args, nprocs=num_proc, start_method="spawn")
59
+
60
+
61
+ def format_exception(e: Exception, limit=20):
62
+ traceback_str = "".join(traceback.format_tb(e.__traceback__, limit=limit))
63
+ return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
64
+
65
+
66
+ class SubmititRunner(submitit.helpers.Checkpointable):
67
+ """A callable which is passed to submitit to launch the jobs."""
68
+
69
+ def __init__(self, port, cfg):
70
+ self.cfg = cfg
71
+ self.port = port
72
+ self.has_setup = False
73
+
74
+ def run_trainer(self):
75
+ job_env = submitit.JobEnvironment()
76
+ # Need to add this again so the hydra.job.set_env PYTHONPATH
77
+ # is also set when launching jobs.
78
+ add_pythonpath_to_sys_path()
79
+ os.environ["MASTER_ADDR"] = job_env.hostnames[0]
80
+ os.environ["MASTER_PORT"] = str(self.port)
81
+ os.environ["RANK"] = str(job_env.global_rank)
82
+ os.environ["LOCAL_RANK"] = str(job_env.local_rank)
83
+ os.environ["WORLD_SIZE"] = str(job_env.num_tasks)
84
+
85
+ register_omegaconf_resolvers()
86
+ cfg_resolved = OmegaConf.to_container(self.cfg, resolve=False)
87
+ cfg_resolved = OmegaConf.create(cfg_resolved)
88
+
89
+ trainer = instantiate(cfg_resolved.trainer, _recursive_=False)
90
+ trainer.run()
91
+
92
+ def __call__(self):
93
+ job_env = submitit.JobEnvironment()
94
+ self.setup_job_info(job_env.job_id, job_env.global_rank)
95
+ try:
96
+ self.run_trainer()
97
+ except Exception as e:
98
+ # Log the exception. Then raise it again (as what SubmititRunner currently does).
99
+ message = format_exception(e)
100
+ logging.error(message)
101
+ raise e
102
+
103
+ def setup_job_info(self, job_id, rank):
104
+ """Set up slurm job info"""
105
+ self.job_info = {
106
+ "job_id": job_id,
107
+ "rank": rank,
108
+ "cluster": self.cfg.get("cluster", None),
109
+ "experiment_log_dir": self.cfg.launcher.experiment_log_dir,
110
+ }
111
+
112
+ self.has_setup = True
113
+
114
+
115
+ def add_pythonpath_to_sys_path():
116
+ if "PYTHONPATH" not in os.environ or not os.environ["PYTHONPATH"]:
117
+ return
118
+ sys.path = os.environ["PYTHONPATH"].split(":") + sys.path
119
+
120
+
121
+ def main(args) -> None:
122
+ cfg = compose(config_name=args.config)
123
+ if cfg.launcher.experiment_log_dir is None:
124
+ cfg.launcher.experiment_log_dir = os.path.join(os.getcwd(), "sam2_logs", args.config)
125
+ print("###################### Train App Config ####################")
126
+ print(OmegaConf.to_yaml(cfg))
127
+ print("############################################################")
128
+
129
+ add_pythonpath_to_sys_path()
130
+ makedir(cfg.launcher.experiment_log_dir)
131
+ with g_pathmgr.open(os.path.join(cfg.launcher.experiment_log_dir, "config.yaml"), "w") as f:
132
+ f.write(OmegaConf.to_yaml(cfg))
133
+
134
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
135
+ cfg_resolved = OmegaConf.create(cfg_resolved)
136
+
137
+ with g_pathmgr.open(os.path.join(cfg.launcher.experiment_log_dir, "config_resolved.yaml"), "w") as f:
138
+ f.write(OmegaConf.to_yaml(cfg_resolved, resolve=True))
139
+
140
+ submitit_conf = cfg.get("submitit", None)
141
+ assert submitit_conf is not None, "Missing submitit config"
142
+
143
+ submitit_dir = cfg.launcher.experiment_log_dir
144
+ submitit_dir = os.path.join(submitit_dir, "submitit_logs")
145
+ # Priotrize cmd line args
146
+ cfg.launcher.gpus_per_node = args.num_gpus if args.num_gpus is not None else cfg.launcher.gpus_per_node
147
+ cfg.launcher.num_nodes = args.num_nodes if args.num_nodes is not None else cfg.launcher.num_nodes
148
+ submitit_conf.use_cluster = args.use_cluster if args.use_cluster is not None else submitit_conf.use_cluster
149
+ if submitit_conf.use_cluster:
150
+ executor = submitit.AutoExecutor(folder=submitit_dir)
151
+ submitit_conf.partition = args.partition if args.partition is not None else submitit_conf.get("partition", None)
152
+ submitit_conf.account = args.account if args.account is not None else submitit_conf.get("account", None)
153
+ submitit_conf.qos = args.qos if args.qos is not None else submitit_conf.get("qos", None)
154
+ job_kwargs = {
155
+ "timeout_min": 60 * submitit_conf.timeout_hour,
156
+ "name": (submitit_conf.name if hasattr(submitit_conf, "name") else args.config),
157
+ "slurm_partition": submitit_conf.partition,
158
+ "gpus_per_node": cfg.launcher.gpus_per_node,
159
+ "tasks_per_node": cfg.launcher.gpus_per_node, # one task per GPU
160
+ "cpus_per_task": submitit_conf.cpus_per_task,
161
+ "nodes": cfg.launcher.num_nodes,
162
+ "slurm_additional_parameters": {
163
+ "exclude": " ".join(submitit_conf.get("exclude_nodes", [])),
164
+ },
165
+ }
166
+ if "include_nodes" in submitit_conf:
167
+ assert len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes, "Not enough nodes"
168
+ job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(submitit_conf["include_nodes"])
169
+ if submitit_conf.account is not None:
170
+ job_kwargs["slurm_additional_parameters"]["account"] = submitit_conf.account
171
+ if submitit_conf.qos is not None:
172
+ job_kwargs["slurm_additional_parameters"]["qos"] = submitit_conf.qos
173
+
174
+ if submitit_conf.get("mem_gb", None) is not None:
175
+ job_kwargs["mem_gb"] = submitit_conf.mem_gb
176
+ elif submitit_conf.get("mem", None) is not None:
177
+ job_kwargs["slurm_mem"] = submitit_conf.mem
178
+
179
+ if submitit_conf.get("constraints", None) is not None:
180
+ job_kwargs["slurm_constraint"] = submitit_conf.constraints
181
+
182
+ if submitit_conf.get("comment", None) is not None:
183
+ job_kwargs["slurm_comment"] = submitit_conf.comment
184
+
185
+ # Supports only cpu-bind option within srun_args. New options can be added here
186
+ if submitit_conf.get("srun_args", None) is not None:
187
+ job_kwargs["slurm_srun_args"] = []
188
+ if submitit_conf.srun_args.get("cpu_bind", None) is not None:
189
+ job_kwargs["slurm_srun_args"].extend(["--cpu-bind", submitit_conf.srun_args.cpu_bind])
190
+
191
+ print("###################### SLURM Config ####################")
192
+ print(job_kwargs)
193
+ print("##########################################")
194
+ executor.update_parameters(**job_kwargs)
195
+
196
+ main_port = random.randint(submitit_conf.port_range[0], submitit_conf.port_range[1])
197
+ runner = SubmititRunner(main_port, cfg)
198
+ job = executor.submit(runner)
199
+ print(f"Submitit Job ID: {job.job_id}")
200
+ runner.setup_job_info(job.job_id, rank=0)
201
+ else:
202
+ cfg.launcher.num_nodes = 1
203
+ main_port = random.randint(submitit_conf.port_range[0], submitit_conf.port_range[1])
204
+ single_node_runner(cfg, main_port)
205
+
206
+
207
+ if __name__ == "__main__":
208
+
209
+ initialize_config_module("sam2", version_base="1.2")
210
+ parser = ArgumentParser()
211
+ parser.add_argument(
212
+ "-c",
213
+ "--config",
214
+ required=True,
215
+ type=str,
216
+ help="path to config file (e.g. configs/sam2.1_training/sam2.1_hiera_b+_MOSE_finetune.yaml)",
217
+ )
218
+ parser.add_argument(
219
+ "--use-cluster",
220
+ type=int,
221
+ default=None,
222
+ help="whether to launch on a cluster, 0: run locally, 1: run on a cluster",
223
+ )
224
+ parser.add_argument("--partition", type=str, default=None, help="SLURM partition")
225
+ parser.add_argument("--account", type=str, default=None, help="SLURM account")
226
+ parser.add_argument("--qos", type=str, default=None, help="SLURM qos")
227
+ parser.add_argument("--num-gpus", type=int, default=None, help="number of GPUS per node")
228
+ parser.add_argument("--num-nodes", type=int, default=None, help="Number of nodes")
229
+ args = parser.parse_args()
230
+ args.use_cluster = bool(args.use_cluster) if args.use_cluster is not None else None
231
+ register_omegaconf_resolvers()
232
+ main(args)