Skip to content

Commit e20cbe9

Browse files
bottlerfacebook-github-bot
authored andcommitted
test fixes and lints
Summary: - followup recent pyre change D63415925 - make tests remove temporary files - weights_only=True in torch.load - lint fixes 3 test fixes from VRehnberg in #1914 - imageio channels fix - frozen decorator in test_config - load_blobs positional Reviewed By: MichaelRamamonjisoa Differential Revision: D66162167 fbshipit-source-id: 7737e174691b62f1708443a4fae07343cec5bfeb
1 parent c17e6f9 commit e20cbe9

21 files changed

+48
-45
lines changed

dev/linter.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,5 @@ then
3636

3737
echo "Running pyre..."
3838
echo "To restart/kill pyre server, run 'pyre restart' or 'pyre kill' in fbcode/"
39-
( cd ~/fbsource/fbcode; pyre -l vision/fair/pytorch3d/ )
39+
( cd ~/fbsource/fbcode; arc pyre check //vision/fair/pytorch3d/... )
4040
fi

packaging/pytorch3d/meta.yaml

-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ requirements:
3232

3333
build:
3434
string: py{{py}}_{{ environ['CU_VERSION'] }}_pyt{{ environ['PYTORCH_VERSION_NODOT']}}
35-
# script: LD_LIBRARY_PATH=$PREFIX/lib:$BUILD_PREFIX/lib:$LD_LIBRARY_PATH python setup.py install --single-version-externally-managed --record=record.txt # [not win]
3635
script: python setup.py install --single-version-externally-managed --record=record.txt # [not win]
3736
script_env:
3837
- CUDA_HOME
@@ -57,7 +56,6 @@ test:
5756
- pandas
5857
- sqlalchemy
5958
commands:
60-
#pytest .
6159
python -m unittest discover -v -s tests -t .
6260

6361

projects/implicitron_trainer/impl/model_factory.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,9 @@ def __call__(
116116
"cuda:%d" % 0: "cuda:%d" % accelerator.local_process_index
117117
}
118118
model_state_dict = torch.load(
119-
model_io.get_model_path(model_path), map_location=map_location
119+
model_io.get_model_path(model_path),
120+
map_location=map_location,
121+
weights_only=True,
120122
)
121123

122124
try:

projects/implicitron_trainer/impl/optimizer_factory.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def _get_optimizer_state(
241241
map_location = {
242242
"cuda:%d" % 0: "cuda:%d" % accelerator.local_process_index
243243
}
244-
optimizer_state = torch.load(opt_path, map_location)
244+
optimizer_state = torch.load(opt_path, map_location, weights_only=True)
245245
else:
246246
raise FileNotFoundError(f"Optimizer state {opt_path} does not exist.")
247247
return optimizer_state

projects/nerf/nerf/dataset.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,9 @@ def get_nerf_datasets(
8484

8585
if autodownload and any(not os.path.isfile(p) for p in (cameras_path, image_path)):
8686
# Automatically download the data files if missing.
87-
download_data((dataset_name,), data_root=data_root)
87+
download_data([dataset_name], data_root=data_root)
8888

89-
train_data = torch.load(cameras_path)
89+
train_data = torch.load(cameras_path, weights_only=True)
9090
n_cameras = train_data["cameras"]["R"].shape[0]
9191

9292
_image_max_image_pixels = Image.MAX_IMAGE_PIXELS

projects/nerf/test_nerf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def main(cfg: DictConfig):
6363
raise ValueError(f"Model checkpoint {checkpoint_path} does not exist!")
6464

6565
print(f"Loading checkpoint {checkpoint_path}.")
66-
loaded_data = torch.load(checkpoint_path)
66+
loaded_data = torch.load(checkpoint_path, weights_only=True)
6767
# Do not load the cached xy grid.
6868
# - this allows setting an arbitrary evaluation image size.
6969
state_dict = {

projects/nerf/train_nerf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def main(cfg: DictConfig):
7777
# Resume training if requested.
7878
if cfg.resume and os.path.isfile(checkpoint_path):
7979
print(f"Resuming from checkpoint {checkpoint_path}.")
80-
loaded_data = torch.load(checkpoint_path)
80+
loaded_data = torch.load(checkpoint_path, weights_only=True)
8181
model.load_state_dict(loaded_data["model"])
8282
stats = pickle.loads(loaded_data["stats"])
8383
print(f" => resuming from epoch {stats.epoch}.")

pytorch3d/implicitron/models/feature_extractor/resnet_feature_extractor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def __post_init__(self):
106106
self.layers = torch.nn.ModuleList()
107107
self.proj_layers = torch.nn.ModuleList()
108108
for stage in range(self.max_stage):
109-
stage_name = f"layer{stage+1}"
109+
stage_name = f"layer{stage + 1}"
110110
feature_name = self._get_resnet_stage_feature_name(stage)
111111
if (stage + 1) in self.stages:
112112
if (
@@ -139,7 +139,7 @@ def __post_init__(self):
139139
self.stages = set(self.stages) # convert to set for faster "in"
140140

141141
def _get_resnet_stage_feature_name(self, stage) -> str:
142-
return f"res_layer_{stage+1}"
142+
return f"res_layer_{stage + 1}"
143143

144144
def _resnet_normalize_image(self, img: torch.Tensor) -> torch.Tensor:
145145
return (img - self._resnet_mean) / self._resnet_std

pytorch3d/implicitron/tools/model_io.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,10 @@ def load_model(fl, map_location: Optional[dict]):
111111
flstats = get_stats_path(fl)
112112
flmodel = get_model_path(fl)
113113
flopt = get_optimizer_path(fl)
114-
model_state_dict = torch.load(flmodel, map_location=map_location)
114+
model_state_dict = torch.load(flmodel, map_location=map_location, weights_only=True)
115115
stats = load_stats(flstats)
116116
if os.path.isfile(flopt):
117-
optimizer = torch.load(flopt, map_location=map_location)
117+
optimizer = torch.load(flopt, map_location=map_location, weights_only=True)
118118
else:
119119
optimizer = None
120120

pytorch3d/io/experimental_gltf_io.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,8 @@ def _read_chunks(
163163
if binary_data is not None:
164164
binary_data = np.frombuffer(binary_data, dtype=np.uint8)
165165

166-
# pyre-fixme[7]: Expected `Optional[Tuple[Dict[str, typing.Any],
167-
# ndarray[typing.Any, typing.Any]]]` but got `Tuple[typing.Any,
168-
# Optional[ndarray[typing.Any, dtype[typing.Any]]]]`.
166+
assert binary_data is not None
167+
169168
return json_data, binary_data
170169

171170

pytorch3d/io/ply_io.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -1246,13 +1246,10 @@ def _save_ply(
12461246
return
12471247

12481248
color_np_type = np.ubyte if colors_as_uint8 else np.float32
1249-
verts_dtype = [("verts", np.float32, 3)]
1249+
verts_dtype: list = [("verts", np.float32, 3)]
12501250
if verts_normals is not None:
12511251
verts_dtype.append(("normals", np.float32, 3))
12521252
if verts_colors is not None:
1253-
# pyre-fixme[6]: For 1st argument expected `Tuple[str,
1254-
# Type[floating[_32Bit]], int]` but got `Tuple[str,
1255-
# Type[Union[floating[_32Bit], unsignedinteger[typing.Any]]], int]`.
12561253
verts_dtype.append(("colors", color_np_type, 3))
12571254

12581255
vert_data = np.zeros(verts.shape[0], dtype=verts_dtype)

pytorch3d/renderer/mesh/clip.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _get_culled_faces(face_verts: torch.Tensor, frustum: ClipFrustum) -> torch.T
168168
position of the clipping planes.
169169
170170
Returns:
171-
faces_culled: An boolean tensor of size F specifying whether or not each face should be
171+
faces_culled: boolean tensor of size F specifying whether or not each face should be
172172
culled.
173173
"""
174174
clipping_planes = (

pytorch3d/renderer/mesh/textures.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -726,15 +726,17 @@ def __init__(
726726
for each face
727727
verts_uvs: (N, V, 2) tensor giving the uv coordinates per vertex
728728
(a FloatTensor with values between 0 and 1).
729-
maps_ids: Used if there are to be multiple maps per face. This can be either a list of map_ids [(F,)]
729+
maps_ids: Used if there are to be multiple maps per face.
730+
This can be either a list of map_ids [(F,)]
730731
or a long tensor of shape (N, F) giving the id of the texture map
731732
for each face. If maps_ids is present, the maps has an extra dimension M
732733
(so maps_padded is (N, M, H, W, C) and maps_list has elements of
733734
shape (M, H, W, C)).
734735
Specifically, the color
735-
of a vertex V is given by an average of maps_padded[i, maps_ids[i, f], u, v, :]
736+
of a vertex V is given by an average of
737+
maps_padded[i, maps_ids[i, f], u, v, :]
736738
over u and v integers adjacent to
737-
_verts_uvs_padded[i, _faces_uvs_padded[i, f, 0], :] .
739+
_verts_uvs_padded[i, _faces_uvs_padded[i, f, 0], :] .
738740
align_corners: If true, the extreme values 0 and 1 for verts_uvs
739741
indicate the centers of the edge pixels in the maps.
740742
padding_mode: padding mode for outside grid values
@@ -1237,7 +1239,8 @@ def sample_textures(self, fragments, **kwargs) -> torch.Tensor:
12371239
texels = texels.reshape(N, K, C, H_out, W_out).permute(0, 3, 4, 1, 2)
12381240
return texels
12391241
else:
1240-
# We have maps_ids_padded: (N, F), textures_map: (N, M, Hi, Wi, C),fragmenmts.pix_to_face: (N, Ho, Wo, K)
1242+
# We have maps_ids_padded: (N, F), textures_map: (N, M, Hi, Wi, C),
1243+
# fragments.pix_to_face: (N, Ho, Wo, K)
12411244
# Get pixel_to_map_ids: (N, K, Ho, Wo) by indexing pix_to_face into maps_ids
12421245
N, M, H_in, W_in, C = texture_maps.shape # 3 for RGB
12431246

@@ -1827,7 +1830,7 @@ def sample_textures(self, fragments, faces_packed=None) -> torch.Tensor:
18271830
representation) which overlap the pixel.
18281831
18291832
Returns:
1830-
texels: An texture per pixel of shape (N, H, W, K, C).
1833+
texels: A texture per pixel of shape (N, H, W, K, C).
18311834
There will be one C dimensional value for each element in
18321835
fragments.pix_to_face.
18331836
"""

tests/implicitron/test_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def __init__(self, a: Any = 1, b: Any = 2):
246246

247247
enable_get_default_args(Foo)
248248

249-
@dataclass()
249+
@dataclass(frozen=True)
250250
class Bar:
251251
aa: int = 9
252252
bb: int = 9

tests/implicitron/test_extending_orm_types.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ def build(
8787
sequence_annotation: types.SequenceAnnotation,
8888
load_blobs: bool = True,
8989
) -> CanineFrameData:
90-
frame_data = super().build(frame_annotation, sequence_annotation, load_blobs)
90+
frame_data = super().build(
91+
frame_annotation, sequence_annotation, load_blobs=load_blobs
92+
)
9193
frame_data.num_dogs = frame_annotation.num_dogs or 101
9294
frame_data.magnetic_field_average_flux_density = (
9395
frame_annotation.magnetic_field.average_flux_density

tests/pulsar/test_forward.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def test_bg_weight(self):
7676
"test_out",
7777
"test_forward_TestForward_test_bg_weight_hits.png",
7878
),
79-
(hits * 255.0).cpu().to(torch.uint8).numpy(),
79+
(hits * 255.0).cpu().to(torch.uint8).squeeze(2).numpy(),
8080
)
8181
self.assertEqual(hits[500, 500, 0].item(), 1.0)
8282
self.assertTrue(
@@ -139,7 +139,7 @@ def test_basic_3chan(self):
139139
"test_out",
140140
"test_forward_TestForward_test_basic_3chan_hits.png",
141141
),
142-
(hits * 255.0).cpu().to(torch.uint8).numpy(),
142+
(hits * 255.0).cpu().to(torch.uint8).squeeze(2).numpy(),
143143
)
144144
self.assertEqual(hits[500, 500, 0].item(), 1.0)
145145
self.assertTrue(
@@ -194,15 +194,15 @@ def test_basic_1chan(self):
194194
"test_out",
195195
"test_forward_TestForward_test_basic_1chan.png",
196196
),
197-
(result * 255.0).cpu().to(torch.uint8).numpy(),
197+
(result * 255.0).cpu().to(torch.uint8).squeeze(2).numpy(),
198198
)
199199
imageio.imsave(
200200
path.join(
201201
path.dirname(__file__),
202202
"test_out",
203203
"test_forward_TestForward_test_basic_1chan_hits.png",
204204
),
205-
(hits * 255.0).cpu().to(torch.uint8).numpy(),
205+
(hits * 255.0).cpu().to(torch.uint8).squeeze(2).numpy(),
206206
)
207207
self.assertEqual(hits[500, 500, 0].item(), 1.0)
208208
self.assertTrue(
@@ -264,7 +264,7 @@ def test_basic_8chan(self):
264264
"test_out",
265265
"test_forward_TestForward_test_basic_8chan_hits.png",
266266
),
267-
(hits * 255.0).cpu().to(torch.uint8).numpy(),
267+
(hits * 255.0).cpu().to(torch.uint8).squeeze(2).numpy(),
268268
)
269269
self.assertEqual(hits[500, 500, 0].item(), 1.0)
270270
self.assertTrue(

tests/test_build.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def test_valid_ipynbs(self):
4343
tutorials = sorted(tutorials_dir.glob("*.ipynb"))
4444

4545
for tutorial in tutorials:
46-
with open(tutorial) as f:
46+
with open(tutorial, encoding="utf8") as f:
4747
json.load(f)
4848

4949
@unittest.skipIf(in_conda_build or in_re_worker, "In conda build, or RE worker")

tests/test_io_gltf.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def _write(mesh, path, **kwargs) -> None:
5353
io.save_mesh(mesh, path, **kwargs)
5454

5555
with open(path, "rb") as f:
56-
_, stored_length = _read_header(f)
56+
_, stored_length = _read_header(f) # pyre-ignore
5757
assert stored_length == os.path.getsize(path)
5858

5959

@@ -191,14 +191,14 @@ def test_save_cow(self):
191191
mesh = _load(glb, device=device)
192192

193193
# save the mesh to a glb file
194-
glb = DATA_DIR / "cow_write.glb"
195-
_write(mesh, glb)
194+
glb_reload = DATA_DIR / "cow_write.glb"
195+
_write(mesh, glb_reload)
196196

197197
# load again
198-
glb_reload = DATA_DIR / "cow_write.glb"
199198
self.assertTrue(glb_reload.is_file())
200199
device = torch.device("cuda:0")
201200
mesh_reload = _load(glb_reload, device=device)
201+
glb_reload.unlink()
202202

203203
# assertions
204204
self.assertEqual(mesh_reload.faces_packed().shape, (5856, 3))
@@ -232,6 +232,7 @@ def test_save_ico_sphere(self):
232232
# reload the ico_sphere
233233
device = torch.device("cuda:0")
234234
mesh_reload = _load(glb, device=device, include_textures=False)
235+
glb.unlink()
235236

236237
self.assertClose(
237238
ico_sphere_mesh.verts_padded().cpu(),
@@ -299,9 +300,9 @@ def test_load_save_load_cow_texturesvertex(self):
299300
_write(mesh, glb)
300301

301302
# reload the mesh glb file saved in TexturesVertex format
302-
glb = DATA_DIR / "cow_write_texturesvertex.glb"
303303
self.assertTrue(glb.is_file())
304304
mesh_dash = _load(glb, device=device)
305+
glb.unlink()
305306
self.assertEqual(len(mesh_dash), 1)
306307

307308
self.assertEqual(mesh_dash.faces_packed().shape, (5856, 3))
@@ -381,3 +382,4 @@ def test_save_toy(self):
381382

382383
glb = DATA_DIR / "example_write_texturesvertex.glb"
383384
_write(mesh, glb)
385+
glb.unlink()

tests/test_points_to_volumes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ def init_cube_mesh(batch_size: int, device: str):
196196
Generate a batch of `batch_size` cube meshes.
197197
"""
198198

199-
device = torch.device(device)
199+
device_ = torch.device(device)
200200

201201
verts, faces = [], []
202202

@@ -213,7 +213,7 @@ def init_cube_mesh(batch_size: int, device: str):
213213
[0.0, 0.0, 1.0],
214214
],
215215
dtype=torch.float32,
216-
device=device,
216+
device=device_,
217217
)
218218
verts.append(v)
219219
faces.append(
@@ -233,7 +233,7 @@ def init_cube_mesh(batch_size: int, device: str):
233233
[0, 1, 6],
234234
],
235235
dtype=torch.int64,
236-
device=device,
236+
device=device_,
237237
)
238238
)
239239

@@ -316,7 +316,7 @@ def test_from_point_cloud(self, interp_mode="trilinear"):
316316
outfile = (
317317
outdir
318318
+ f"/rgb_{interp_mode}"
319-
+ f"_{str(volume_size).replace(' ','')}"
319+
+ f"_{str(volume_size).replace(' ', '')}"
320320
+ f"_{vidx:003d}_sldim{slice_dim}.png"
321321
)
322322
im.save(outfile)

tests/test_raysampling.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -639,4 +639,4 @@ def test_heterogeneous_sampling(self, batch_size=8):
639639
origin1, origin2, rtol=1e-4, atol=1e-4
640640
) == (id1 == id2), (origin1, origin2, id1, id2)
641641
assert not torch.allclose(dir1, dir2), (dir1, dir2)
642-
self.assertClose(len1, len2), (len1, len2)
642+
self.assertClose(len1, len2)

tests/test_render_volumes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ def test_rotating_cube_volume_render(self):
689689
outfile = (
690690
outdir
691691
+ f"/rgb_{sample_mode}"
692-
+ f"_{str(volume_size).replace(' ','')}"
692+
+ f"_{str(volume_size).replace(' ', '')}"
693693
+ f"_{imidx:003d}"
694694
)
695695
if image_ is image:

0 commit comments

Comments
 (0)