s23dr
hoho22k
research-only
non-commercial
File size: 184,366 Bytes
2c43fda
 
 
 
 
 
 
ac5a5b5
 
 
2c43fda
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
2c43fda
 
ac5a5b5
 
2c43fda
7c4d0d7
2c43fda
ac5a5b5
 
2c43fda
ac5a5b5
2c43fda
ac5a5b5
 
 
 
2c43fda
19a424b
2c43fda
 
 
aa5259b
 
 
 
2c43fda
 
 
aa5259b
ac5a5b5
 
aa5259b
 
 
 
 
 
 
ac5a5b5
4b16925
932f501
dc1fa63
ac5a5b5
2c43fda
 
 
932f501
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230e89c
 
 
 
932f501
 
 
 
230e89c
932f501
 
 
 
230e89c
 
932f501
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
2c43fda
 
 
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
932f501
 
 
 
 
 
 
 
2c43fda
ac5a5b5
2c43fda
 
 
 
 
 
 
932f501
ac5a5b5
 
932f501
2c43fda
 
 
 
 
 
 
932f501
 
 
ac5a5b5
 
 
2c43fda
ac5a5b5
2c43fda
 
 
 
 
 
 
932f501
2c43fda
932f501
 
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
 
 
 
2c43fda
 
 
ac5a5b5
 
 
 
932f501
 
 
 
 
 
 
 
 
 
230e89c
 
 
 
bbfe12c
dc1fa63
9cde5e7
19a424b
 
 
aa5259b
 
 
078e721
ac5a5b5
 
932f501
 
 
 
230e89c
 
 
 
 
 
 
 
bbfe12c
 
d18dd9a
dc1fa63
9cde5e7
0dc1ead
64b54c6
19a424b
 
 
 
 
aa5259b
 
 
 
078e721
ac5a5b5
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
230e89c
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
ab6f32a
 
bbfe12c
dc1fa63
 
 
9cde5e7
19a424b
 
 
 
9cde5e7
19a424b
 
 
 
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
078e721
ab0c4d9
 
 
 
 
 
ac5a5b5
 
 
 
 
 
932f501
 
 
 
 
 
 
 
 
 
 
230e89c
 
932f501
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
 
ac5a5b5
 
bbfe12c
ac5a5b5
 
 
bbfe12c
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
 
19a424b
bbfe12c
 
19a424b
 
 
bbfe12c
 
 
 
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
19a424b
 
 
 
 
 
 
 
 
 
bbfe12c
 
19a424b
bbfe12c
19a424b
bbfe12c
 
 
 
 
 
 
 
 
 
 
 
 
19a424b
 
bbfe12c
 
 
 
 
19a424b
 
bbfe12c
 
 
19a424b
bbfe12c
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
 
 
19a424b
bbfe12c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a424b
bbfe12c
 
 
 
 
 
 
 
 
 
 
4639444
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
4639444
 
 
 
bbfe12c
 
4639444
 
bbfe12c
 
4639444
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
4639444
bbfe12c
 
4639444
bbfe12c
 
 
 
 
 
 
 
 
 
 
 
4639444
bbfe12c
 
19a424b
9cde5e7
bbfe12c
19a424b
 
 
9cde5e7
19a424b
 
9cde5e7
19a424b
9cde5e7
 
 
19a424b
 
 
9cde5e7
19a424b
9cde5e7
 
 
 
 
bbfe12c
 
 
4639444
9cde5e7
bbfe12c
 
 
 
9cde5e7
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
bbfe12c
 
9cde5e7
ab6f32a
9cde5e7
 
 
 
 
 
ab6f32a
 
 
 
 
 
 
 
 
 
 
9cde5e7
ab6f32a
9cde5e7
 
 
 
 
 
 
 
64b54c6
19a424b
 
 
9cde5e7
 
 
 
 
 
 
 
9bb26a8
 
 
 
 
 
9cde5e7
 
 
 
 
 
 
 
 
 
 
19a424b
 
 
9cde5e7
19a424b
 
9cde5e7
 
 
19a424b
9cde5e7
 
19a424b
 
 
 
 
 
 
9cde5e7
19a424b
9cde5e7
19a424b
 
 
 
 
 
 
 
 
 
 
9cde5e7
19a424b
9cde5e7
 
 
19a424b
 
 
 
9cde5e7
 
 
 
 
 
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cde5e7
19a424b
 
 
9cde5e7
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cde5e7
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab6f32a
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
aa5259b
b5c9d64
 
 
aa5259b
b5c9d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
b5c9d64
aa5259b
 
 
b5c9d64
aa5259b
b5c9d64
aa5259b
 
 
b5c9d64
aa5259b
 
b5c9d64
 
 
 
 
 
 
 
 
 
 
aa5259b
 
b5c9d64
aa5259b
 
b5c9d64
 
 
 
aa5259b
b5c9d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
b5c9d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
b5c9d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
 
 
 
 
b5c9d64
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
 
 
aa5259b
b5c9d64
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
 
 
 
b5c9d64
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
b5c9d64
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
932f501
 
bbfe12c
 
932f501
bbfe12c
 
ac5a5b5
 
 
 
 
 
 
230e89c
932f501
 
 
 
bbfe12c
932f501
 
 
 
 
 
230e89c
 
 
 
 
 
 
 
 
ac5a5b5
932f501
 
ac5a5b5
 
 
 
230e89c
932f501
 
 
 
 
 
ac5a5b5
932f501
ac5a5b5
 
 
932f501
bbfe12c
ac5a5b5
dc1fa63
 
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc1fa63
ac5a5b5
 
 
 
dc1fa63
 
ac5a5b5
dc1fa63
 
ac5a5b5
 
 
 
 
bbfe12c
 
 
19a424b
bbfe12c
ac5a5b5
 
 
 
 
bbfe12c
932f501
bbfe12c
19a424b
 
 
bbfe12c
 
 
19a424b
 
 
 
 
b5c9d64
 
 
 
19a424b
 
ac5a5b5
bbfe12c
ab6f32a
19a424b
 
bbfe12c
ac5a5b5
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c9d64
aa5259b
 
 
ac5a5b5
aa5259b
 
 
 
 
 
 
ac5a5b5
aa5259b
 
 
 
078e721
 
aa5259b
ac5a5b5
078e721
 
 
 
 
 
 
 
 
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
 
078e721
aa5259b
 
 
 
 
 
9cde5e7
19a424b
 
 
 
 
bbfe12c
19a424b
ab6f32a
19a424b
 
 
bbfe12c
9cde5e7
 
aa5259b
9cde5e7
aa5259b
19a424b
 
 
 
 
 
 
 
 
 
 
 
9cde5e7
19a424b
9cde5e7
19a424b
 
9cde5e7
 
 
 
19a424b
 
 
 
 
 
 
 
 
bbfe12c
932f501
bbfe12c
 
 
 
 
 
 
 
19a424b
 
bbfe12c
 
19a424b
 
bbfe12c
932f501
 
2c43fda
ac5a5b5
 
2c43fda
 
ac5a5b5
 
 
 
 
2c43fda
ac5a5b5
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b16925
 
 
 
 
 
 
 
 
 
ac5a5b5
 
4b16925
ac5a5b5
4b16925
ac5a5b5
4b16925
 
 
 
 
 
 
ac5a5b5
4b16925
ac5a5b5
4b16925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
ac5a5b5
2c43fda
 
ac5a5b5
 
932f501
2c43fda
ac5a5b5
 
 
2c43fda
 
ac5a5b5
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
ac5a5b5
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a424b
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c4d0d7
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c4d0d7
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230e89c
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
 
 
 
19a424b
 
ac5a5b5
 
 
 
19a424b
ac5a5b5
 
19a424b
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
2c43fda
 
 
 
 
 
230e89c
932f501
230e89c
 
932f501
 
 
 
 
 
 
 
 
19a424b
 
 
 
 
 
230e89c
 
 
 
 
 
 
 
 
 
19a424b
ac5a5b5
 
 
 
932f501
 
 
 
 
 
 
 
 
230e89c
 
932f501
230e89c
 
 
 
 
 
 
 
 
bbfe12c
 
 
dc1fa63
0dc1ead
9cde5e7
19a424b
 
 
 
 
aa5259b
 
 
 
 
 
 
078e721
ab0c4d9
ac5a5b5
 
 
 
 
932f501
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230e89c
 
 
 
 
ab0c4d9
 
 
932f501
230e89c
 
932f501
bbfe12c
9cde5e7
 
19a424b
 
 
 
 
 
dc1fa63
9cde5e7
19a424b
aa5259b
 
932f501
 
 
2c43fda
 
 
 
 
 
dc1fa63
 
230e89c
 
bb6848b
2c43fda
bb6848b
2c43fda
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
932f501
 
 
 
 
c7644c2
 
4639444
 
 
bb6848b
 
932f501
 
 
 
 
 
230e89c
 
19a424b
230e89c
 
19a424b
932f501
 
19a424b
 
 
ab0c4d9
19a424b
230e89c
 
 
 
 
 
 
 
 
 
bbfe12c
dc1fa63
 
 
 
 
 
d18dd9a
0dc1ead
 
 
d18dd9a
dc1fa63
 
 
 
 
 
 
 
 
ab6f32a
 
d18dd9a
ab6f32a
d18dd9a
 
 
 
9cde5e7
0dc1ead
 
 
 
 
 
 
 
19a424b
64b54c6
 
 
 
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
bb6848b
 
 
 
 
 
 
 
 
19a424b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5259b
bb6848b
 
 
 
aa5259b
 
bb6848b
aa5259b
 
 
 
 
 
078e721
 
 
 
 
b5c9d64
aa5259b
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
 
 
ac5a5b5
 
 
2c43fda
4b16925
 
 
2c43fda
 
 
4b16925
 
2c43fda
4b16925
 
 
ac5a5b5
 
19a424b
 
 
 
 
2c43fda
 
 
ac5a5b5
 
2c43fda
 
aa5259b
 
 
 
 
 
ac5a5b5
 
 
 
 
7c4d0d7
 
ac5a5b5
7c4d0d7
 
 
 
 
 
 
ac5a5b5
 
 
 
 
7c4d0d7
 
aa5259b
ac5a5b5
 
 
2c43fda
ac5a5b5
2c43fda
 
 
 
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c43fda
ac5a5b5
 
2c43fda
 
 
 
 
 
 
 
 
 
 
 
ac5a5b5
 
 
 
2c43fda
 
230e89c
 
2c43fda
 
 
 
 
 
 
ac5a5b5
 
2c43fda
932f501
ac5a5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932f501
2c43fda
 
ac5a5b5
 
2c43fda
 
 
 
ac5a5b5
 
2c43fda
 
 
ac5a5b5
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
"""S23DR 2026 — submission script (trained WireframeDiffusion).

HF Competitions entry point: the test runner executes ``python script.py``
in the submission repo's working directory. We therefore:

  * Load ``params.json`` (mirrors ``usm3d/empty_submission_2026``).
  * Resolve the dataset (test server: ``/tmp/data``; local: snapshot_download).
  * Read the samples straight from the webdataset tars (``--loader tar``; or
    through the HF loader script, ``--loader hf``), **load the diffusion model
    exactly once** on CUDA, run inference, and write ``submission.json``.

Online preprocessing
--------------------
Uses V10 online preprocessing by default — ``build_scene_input`` produces
the V10 feature point cloud (COLMAP+camera tokens + depth-unprojected
tokens, per-point RGB, soft top-2 gestalt). Matches the cache layout the
model was trained on.

Efficiency notes
----------------
* Models live only in the main process, which runs one GPU loop over batches
  of ``--batch_samples`` samples (stage 1, then stage 2; fixed batch shape).
* All CPU work (tar read, COLMAP parse, scene build, stage-2 hull crop,
  ensemble selection) runs in ``--n_workers`` spawned worker processes with one
  BLAS thread each; the worker that preprocessed a sample keeps its stage-1
  cache and does that sample's stage-2 build and selection (see run_pipeline).
* A sample whose CPU work raises gets the empty solution and is reported as
  FAILED (counted at the end); a GPU error or a dead / stalled worker stops
  the run.

Specifying the checkpoint
-------------------------
Resolution order (first hit wins):
  1. ``--ckpt PATH``               (CLI, for local testing)
  2. ``S23DR_CKPT`` env var        (set by SLURM / docker entrypoint)
  3. ``params['ckpt']``            (extra field in params.json)
  4. ``./test_checkpoint.pth``     (default — what you'd commit to the
                                    submission repo)

The script auto-resolves model architecture (small vs. large) from the
``args`` dict embedded in the checkpoint, so the same script handles both.

Local sanity check
------------------
Before pushing a submission repo, run::

    python script.py --sanity

This loads the public ``usm3d/hoho22k_2026_trainval`` dataset (which has
GT wireframes), runs the trained model on a few validation samples, and
prints per-sample + mean HSS / F1 / IoU. It writes no submission.json —
its only job is to verify that the checkpoint loads, the V10 online
preprocessing path works end-to-end, and the model produces sane output
before you submit.
"""

from __future__ import annotations

import argparse
import copy
import fcntl
import hashlib
import io
import json
import multiprocessing as mp
import multiprocessing.connection
import os
import signal
import queue
import resource
import shlex
import sys
import threading
import time
import traceback
import zipfile
from collections import Counter, defaultdict, deque
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

import numpy as np
import torch
try:
    from datasets import load_dataset
except ModuleNotFoundError:
    load_dataset = None
from tqdm import tqdm

# --- our project imports ----------------------------------------------------
from data.preprocess import (
    read_colmap_zip,
    _cam_matrix_from_image,
    build_scene_input,
    _image_to_rgb_array,
    gestalt_img_to_ids,
    _camera_for_image,
    _resolve_colmap_image,
    GESTALT_CLASSES,
)
from data.dataset import (_seed_from_order_id, index_tar, read_tar_members, decode_tar_sample,
                          hf_row_images, stream_tar_prefix)
from data.stage2_build import build_stage2_scene
from data.stage2_dataset import stage2_row_to_sample, _pad_init_verts
import models.scene_encoder
from models.scene_encoder import SceneEncoder
from models.denoiser import VertexDenoiser
from models.diffusion import WireframeDiffusion
from models.stage2 import Stage2Diffusion


# ---------------------------------------------------------------------------
# Empty / safe fallback
# ---------------------------------------------------------------------------

def empty_solution() -> Tuple[np.ndarray, List[Tuple[int, int]]]:
    """Minimal valid solution: 2 coincident vertices + 1 edge."""
    return np.zeros((2, 3)), [(0, 1)]


# ---------------------------------------------------------------------------
# Model loading (called once)
# ---------------------------------------------------------------------------

def resolve_ckpt_path(cli_arg: Optional[str], params: Dict[str, Any]) -> Path:
    for candidate, src in [
        (cli_arg,                     "--ckpt"),
        (os.environ.get("S23DR_CKPT"), "$S23DR_CKPT"),
        (params.get("ckpt"),          "params.json[ckpt]"),
        ("./test_checkpoint.pth",     "default ./test_checkpoint.pth"),
    ]:
        if candidate:
            print(f"[ckpt] using {candidate}  (from {src})", flush=True)
            return Path(candidate)
    raise SystemExit("[ckpt] no checkpoint specified")


def resolve_stage2_ckpt_path(cli_arg: Optional[str], params: Dict[str, Any]) -> Path:
    """Stage-2 checkpoint resolution. The two-stage architecture is mandatory;
    if no stage-2 ckpt is configured the script aborts. Resolution mirrors
    ``resolve_ckpt_path``: CLI → env → params.json → committed default."""
    for candidate, src in [
        (cli_arg,                                "--stage2_ckpt"),
        (os.environ.get("S23DR_STAGE2_CKPT"),    "$S23DR_STAGE2_CKPT"),
        (params.get("stage2_ckpt"),              "params.json[stage2_ckpt]"),
        ("./test_checkpoint_stage2.pth",         "default ./test_checkpoint_stage2.pth"),
    ]:
        if candidate:
            print(f"[stage2/ckpt] using {candidate}  (from {src})", flush=True)
            return Path(candidate)
    raise SystemExit("[stage2/ckpt] no stage-2 checkpoint specified — "
                     "two-stage pipeline is mandatory.")


def _load_state_strict(model: torch.nn.Module, ckpt: Dict[str, Any], ckpt_path: Path) -> None:
    """Load the checkpoint weights with strict key AND shape matching (every checkpoint tensor
    consumed, every model parameter loaded; raises otherwise) and switch to eval mode."""
    state = ckpt.get("model") or ckpt.get("state_dict")
    if state is None:
        raise RuntimeError(f"checkpoint {ckpt_path} has no 'model' or 'state_dict' key")
    # Strip DDP prefix if present.
    if any(k.startswith("module.") for k in state):
        state = {k[len("module."):]: v for k, v in state.items()}
    model.load_state_dict(state, strict=True)
    n_params = sum(1 for _ in model.state_dict())
    if n_params != len(state):
        raise RuntimeError(f"{ckpt_path}: {len(state)} checkpoint tensors vs {n_params} model tensors")
    model.eval()


def load_model(ckpt_path: Path, device: torch.device):
    """Return (model, ckpt_args) — model is .eval() on `device`.

    Architecture hyperparameters (d_model, n_heads, n_layers, d_ff,
    n_pool, encoder layer counts, ...) are read from the ``args`` dict
    embedded in the checkpoint. Same loader handles small and large
    configs transparently.
    """
    print(f"[model] loading {ckpt_path} on {device}", flush=True)
    t0 = time.perf_counter()
    ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
    ckpt_args = ckpt.get("args", {}) or {}

    # RGB branch is present in v10+ caches and was used when training models
    # on those shards. Older sem_v7 checkpoints disable the RGB MLP.
    cache_version = str(ckpt_args.get("cache_version", "sem_v10")).lower()
    use_rgb = cache_version not in {"v7", "sem_v7"}

    enc = SceneEncoder(
        d_model=ckpt_args.get("d_model", 256),
        n_heads=ckpt_args.get("n_heads", 8),
        d_ff=ckpt_args.get("d_ff", 1024),
        n_full_layers=ckpt_args.get("n_encoder_full_layers", 2),
        n_pool=ckpt_args.get("n_pool", 1024),
        n_pool_cross_layers=ckpt_args.get("n_encoder_pool_cross_layers", 1),
        n_pool_layers=ckpt_args.get("n_encoder_pool_layers", 2),
        use_rgb=use_rgb,
    )
    den = VertexDenoiser(
        d_model=ckpt_args.get("d_model", 256),
        n_heads=ckpt_args.get("n_heads", 8),
        n_layers=ckpt_args.get("n_layers", 8),
        d_ff=ckpt_args.get("d_ff", 1024),
        k_verts=ckpt_args.get("k_verts", 64),
    )
    model = WireframeDiffusion(
        enc, den,
        noise_sigma_xyz=ckpt_args.get("noise_sigma_xyz", 1.0),
        init_from_scene=ckpt_args.get("init_from_scene", False),
        scene_init_jitter=ckpt_args.get("scene_init_jitter", 0.05),
    ).to(device)

    _load_state_strict(model, ckpt, ckpt_path)

    print(f"[model] loaded in {time.perf_counter() - t0:.1f}s  "
          f"d_model={ckpt_args.get('d_model')} n_layers={ckpt_args.get('n_layers')} "
          f"use_rgb={use_rgb}  step={ckpt.get('step')}  best_hss={ckpt.get('best_hss')}",
          flush=True)
    return model, ckpt_args


def load_stage2_model(ckpt_path: Path, device: torch.device):
    """Build a Stage2Diffusion model from its checkpoint. Architecture is read
    from the embedded ``args`` dict so the same loader handles small / large
    variants. Returns (model, ckpt_args).
    """
    print(f"[stage2/model] loading {ckpt_path} on {device}", flush=True)
    t0 = time.perf_counter()
    ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
    a = ckpt.get("args", {}) or {}
    if not isinstance(a, dict):
        a = vars(a)

    enc = SceneEncoder(
        d_model=a.get("d_model", 256),
        n_heads=a.get("n_heads", 8),
        d_ff=a.get("d_ff", 1024),
        n_full_layers=a.get("n_encoder_full_layers", 2),
        n_pool=a.get("n_pool", 1024),
        n_pool_cross_layers=a.get("n_encoder_pool_cross_layers", 1),
        n_pool_layers=a.get("n_encoder_pool_layers", 2),
        use_rgb=True,  # stage-2 cache always carries RGB
    )
    den = VertexDenoiser(
        d_model=a.get("d_model", 256),
        n_heads=a.get("n_heads", 8),
        n_layers=a.get("n_layers", 8),
        d_ff=a.get("d_ff", 1024),
        k_verts=a.get("k_verts", 64),
    )
    model = Stage2Diffusion(
        enc, den,
        noise_sigma_xyz=a.get("noise_sigma_xyz", 0.5),
        init_from_scene=a.get("init_from_scene", True),
        scene_init_jitter=a.get("scene_init_jitter", 0.05),
    ).to(device)

    _load_state_strict(model, ckpt, ckpt_path)

    print(f"[stage2/model] loaded in {time.perf_counter() - t0:.1f}s  "
          f"d_model={a.get('d_model')} n_layers={a.get('n_layers')}  "
          f"step={ckpt.get('step')}  best_hss={ckpt.get('best_hss')}",
          flush=True)
    return model, a


# ---------------------------------------------------------------------------
# Per-sample preprocessing (CPU, runs in the pipeline worker processes)
# ---------------------------------------------------------------------------

def preprocess_sample(
    sample: Dict[str, Any],
    n_pts: int,
    use_depth: bool,
    voxel_size_m: float = 0.1,
    keep_raw: bool = False,
    *,
    colmap_order: str,
) -> Dict[str, Any]:
    """Heavy CPU work: COLMAP parse + V10 scene input build. No torch / GPU here.

    Mirrors `data.dataset.process_sample` exactly: same `voxel_size_m`
    (configs set this to 0.1; build_scene_input's bare default is 0.0
    which would skip voxel downsampling and produce a different point
    set) and same per-order_id deterministic RNG seed (so the same
    points are sampled as were cached at training time).

    With ``keep_raw=True`` the return value is ``{"scene": ..., "raw_sample":
    ..., "colmap_rec": ...}`` so the stage-2 builder can reuse the already-
    decoded COLMAP record instead of parsing the zip twice. ``colmap_order``:
    point / image order of the COLMAP record (``read_colmap_zip``; "pycolmap" =
    the released preprocessing bit for bit).
    """
    colmap_rec = read_colmap_zip(sample["colmap"], order=colmap_order)
    order_id = sample.get("order_id", "")
    rng = np.random.default_rng(_seed_from_order_id(order_id))
    scene = build_scene_input(
        {**sample, "colmap": colmap_rec},
        n_pts=n_pts, use_depth=use_depth,
        voxel_size_m=voxel_size_m,
        rng=rng,
        return_cache=keep_raw,
    )
    if not keep_raw:
        return scene
    cache = scene.pop("_cache", None)
    return {
        "scene":      scene,
        "raw_sample": sample,
        "colmap_rec": colmap_rec,
        "cache":      cache,
    }


_SCENE_KEYS = ("scene_xyz", "scene_type_ids", "scene_gestalt_ids", "scene_gestalt_id2",
               "scene_gestalt_w1", "scene_ade_ids", "scene_geom_conf", "scene_sem_conf", "scene_rgb")


def scenes_to_batch(scenes: Sequence[Dict[str, np.ndarray]], device: torch.device) -> Dict[str, torch.Tensor]:
    """Stack S stage-1 scenes (``build_scene_input`` dicts, equal point counts) into one device
    batch with leading dim S (one host->device copy per field)."""
    batch = {k: torch.from_numpy(np.stack([s[k] for s in scenes])).to(device)
             for k in _SCENE_KEYS + ("bbox_center", "bbox_R")}
    batch["bbox_scale"] = torch.tensor([s["bbox_scale"] for s in scenes], dtype=torch.float32, device=device)
    return batch


def scene_to_batch(scene: Dict[str, np.ndarray], device: torch.device) -> Dict[str, torch.Tensor]:
    return scenes_to_batch([scene], device)


# ---------------------------------------------------------------------------
# Stage-2 inference helpers
# ---------------------------------------------------------------------------

class Stage2Config:
    """Frozen knobs for the stage-2 refinement path. Built once in `main`."""

    __slots__ = ("model", "n_pts", "k_verts", "n_sample_steps", "validity_thresh",
                 "above_m", "below_m", "side_m",
                 "n_col_oversample", "n_dep_oversample",
                 "n_depth_per_image_cap", "sampling",
                 "density_voxel_size_m", "density_kernel_radius",
                 "density_kernel_axis", "density_response_power",
                 "density_planarity_suppression", "density_planarity_radius",
                 "density_planarity_min_points", "density_min_per_voxel",
                 "ensemble_n", "ensemble_merge_m", "ensemble_mode",
                 "ensemble_strategy", "ensemble_refine_positions",
                 "ensemble_refine_agg", "ensemble_top_k",
                 "ensemble_edge_vote", "ensemble_edge_vote_frac",
                 "ensemble_vertex_vote_frac",
                 "ensemble_stage2_last_k", "ensemble_selector",
                 "ensemble_ranker_path", "ensemble_ranker",
                 "ensemble_fixed_candidate",
                 "ensemble_topk_fuse",
                 "fps_max_exact_iters",
                 "seed", "encoder_bf16", "denoiser_bf16", "cuda_graph", "compile")

    def __init__(self, model, n_pts: int, k_verts: int, n_sample_steps: int,
                 validity_thresh: float, above_m: float, below_m: float, side_m: float,
                 n_col_oversample: int, n_dep_oversample: int,
                 n_depth_per_image_cap: int, sampling: str = "random",
                 density_voxel_size_m: float = 0.25,
                 density_kernel_radius: int = 3,
                 density_kernel_axis: str = "cube",
                 density_response_power: float = 1.0,
                 density_planarity_suppression: float = 1.0,
                 density_planarity_radius: int = 1,
                 density_planarity_min_points: int = 12,
                 density_min_per_voxel: int = 0,
                 ensemble_n: int = 1,
                 ensemble_merge_m: float = 0.5,
                 ensemble_mode: str = "medoid",
                 ensemble_strategy: str = "union_hull",
                 ensemble_refine_positions: bool = True,
                 ensemble_refine_agg: str = "mean",
                 ensemble_top_k: int = 0,
                 ensemble_edge_vote: bool = True,
                 ensemble_edge_vote_frac: float = 0.5,
                 ensemble_vertex_vote_frac: float = 0.0,
                 ensemble_stage2_last_k: int = 1,
                 ensemble_selector: str = "legacy",
                 ensemble_ranker_path: Optional[str] = None,
                 ensemble_ranker: Optional[Dict[str, np.ndarray]] = None,
                 ensemble_fixed_candidate: str = "confidence_mean_add",
                 ensemble_topk_fuse: int = 1,
                 fps_max_exact_iters: Optional[int] = None,
                 seed: int = 0,
                 encoder_bf16: bool = False,
                 denoiser_bf16: bool = False,
                 cuda_graph: bool = False,
                 compile: bool = False):
        self.model = model
        self.n_pts = int(n_pts)
        self.k_verts = int(k_verts)
        self.n_sample_steps = int(n_sample_steps)
        self.validity_thresh = float(validity_thresh)
        self.above_m = float(above_m); self.below_m = float(below_m); self.side_m = float(side_m)
        self.n_col_oversample = int(n_col_oversample)
        self.n_dep_oversample = int(n_dep_oversample)
        self.n_depth_per_image_cap = int(n_depth_per_image_cap)
        if sampling not in ("random", "fps", "voxel"):
            raise ValueError(f"sampling must be 'random', 'fps', or 'voxel', got {sampling!r}")
        self.sampling = sampling
        self.density_voxel_size_m = float(density_voxel_size_m)
        self.density_kernel_radius = int(density_kernel_radius)
        self.density_kernel_axis = str(density_kernel_axis)
        self.density_response_power = float(density_response_power)
        self.density_planarity_suppression = float(density_planarity_suppression)
        self.density_planarity_radius = int(density_planarity_radius)
        self.density_planarity_min_points = int(density_planarity_min_points)
        self.density_min_per_voxel = int(density_min_per_voxel)
        self.ensemble_n = max(1, int(ensemble_n))
        self.ensemble_merge_m = float(ensemble_merge_m)
        if ensemble_mode not in ("medoid", "consensus", "confidence"):
            raise ValueError(f"ensemble_mode must be 'medoid', 'consensus', or 'confidence', got {ensemble_mode!r}")
        self.ensemble_mode = str(ensemble_mode)
        if ensemble_strategy not in ("union_hull", "per_seed"):
            raise ValueError(f"ensemble_strategy must be 'union_hull' or 'per_seed', got {ensemble_strategy!r}")
        self.ensemble_strategy = str(ensemble_strategy)
        self.ensemble_refine_positions = bool(ensemble_refine_positions)
        if ensemble_refine_agg not in ("median", "mean", "wmean"):
            raise ValueError(
                f"ensemble_refine_agg must be 'median', 'mean', or 'wmean', "
                f"got {ensemble_refine_agg!r}")
        self.ensemble_refine_agg = str(ensemble_refine_agg)
        self.ensemble_top_k = max(0, int(ensemble_top_k))
        self.ensemble_edge_vote = bool(ensemble_edge_vote)
        if not (0.0 < float(ensemble_edge_vote_frac) <= 1.0):
            raise ValueError(
                f"ensemble_edge_vote_frac must be in (0, 1], got {ensemble_edge_vote_frac!r}")
        self.ensemble_edge_vote_frac = float(ensemble_edge_vote_frac)
        if not (0.0 <= float(ensemble_vertex_vote_frac) <= 1.0):
            raise ValueError(
                f"ensemble_vertex_vote_frac must be in [0, 1], "
                f"got {ensemble_vertex_vote_frac!r}")
        self.ensemble_vertex_vote_frac = float(ensemble_vertex_vote_frac)
        self.ensemble_stage2_last_k = max(1, int(ensemble_stage2_last_k))
        if ensemble_selector not in ("legacy", "ranker", "fixed"):
            raise ValueError(
                f"ensemble_selector must be 'legacy', 'ranker', or 'fixed', got {ensemble_selector!r}")
        self.ensemble_selector = str(ensemble_selector)
        self.ensemble_ranker_path = ensemble_ranker_path
        self.ensemble_ranker = ensemble_ranker
        self.ensemble_fixed_candidate = str(ensemble_fixed_candidate)
        self.ensemble_topk_fuse = max(1, int(ensemble_topk_fuse))
        # None => full exact FPS. Set to the value the model trained with so
        # the per-provenance anchor count matches; otherwise the encoder sees
        # a markedly different point distribution at inference (all exact
        # anchors vs. exact prefix + deterministic random fill).
        self.fps_max_exact_iters = (None if fps_max_exact_iters is None
                                    else int(fps_max_exact_iters))
        # GPU numerics + paired seeding (see stage1_predict_batch / stage2_predict_batch).
        self.seed = int(seed)
        self.encoder_bf16 = bool(encoder_bf16)
        self.denoiser_bf16 = bool(denoiser_bf16)
        self.cuda_graph = bool(cuda_graph)
        self.compile = bool(compile)


def _stage2_sample_to_batch(sample: Dict[str, Any], device: torch.device) -> Dict[str, torch.Tensor]:
    """Same shape as ``scene_to_batch`` but for the stage-2 sample dict produced
    by ``stage2_row_to_sample`` (includes ``init_verts`` + valid mask)."""
    keys = (
        "scene_xyz", "scene_type_ids",
        "scene_gestalt_ids", "scene_gestalt_id2", "scene_gestalt_w1",
        "scene_ade_ids", "scene_geom_conf", "scene_sem_conf",
        "scene_rgb", "init_verts", "init_verts_valid",
        "bbox_center", "bbox_scale", "bbox_R",
        # FPS-mode extras (only present when pre_subsample=False):
        "scene_valid_mask", "init_verts_world", "verts_gt_world",
    )
    return {k: sample[k].unsqueeze(0).to(device) for k in keys if k in sample}


def _stage2_samples_to_batch(samples: Sequence[Dict[str, Any]], device: torch.device) -> Dict[str, torch.Tensor]:
    """Stack S built stage-2 samples (equal point counts and member counts M) into one device batch:
    scene fields (S, ...), ``init_verts`` (S*M, K, 3) and ``init_verts_valid`` (S*M, K)."""
    batch = {k: torch.stack([s[k] for s in samples]).to(device) for k in _SCENE_KEYS}
    for k in ("init_verts", "init_verts_valid"):
        batch[k] = torch.cat([s[k] for s in samples]).to(device)
    return batch


def _torch_seed(order_id: str, seed: int, stage: str, n: int) -> int:
    """Per-sample torch seed sha1(f"{order_id}/{seed}/{stage}/{n}")[:8] (big endian) & (2**63 - 1),
    the formula of tools/infer_bench.py:stable_seed. ``stage`` is "s1" or "s2"; ``n`` counts that
    stage's scene encodes within the sample (0 except in the per-seed stage-2 path)."""
    h = hashlib.sha1(f"{order_id}/{seed}/{stage}/{n}".encode()).digest()
    return int.from_bytes(h[:8], "big") & ((1 << 63) - 1)


@contextmanager
def _phase(timings: Optional[Dict[str, float]], key: str, device: torch.device):
    """Add the CUDA-synchronised wall seconds of the block to timings[key]; no-op when None."""
    if timings is None:
        yield
        return
    if device.type == "cuda":
        torch.cuda.synchronize(device)
    t0 = time.perf_counter()
    yield
    if device.type == "cuda":
        torch.cuda.synchronize(device)
    timings[key] = timings.setdefault(key, 0.0) + time.perf_counter() - t0


def _init_members(model: WireframeDiffusion, batch: Dict[str, torch.Tensor], M: int,
                  order_ids: Sequence[str], seed: int, stage: str, enc_idx: Sequence[int]) -> torch.Tensor:
    """x0 (S*M, K, 3) for the M members of each of the S scenes in ``batch`` (sample-major rows).
    Sample s reseeds the torch RNG with _torch_seed(order_ids[s], seed, stage, enc_idx[s]) and then
    makes exactly the draws of the released per-sample path (``model._init_x0`` on its scene
    replicated to M rows), so each sample is paired with the seeded phase-0 baseline."""
    S = batch["scene_xyz"].shape[0]
    x0 = []
    for s in range(S):
        sub = {k: batch[k][s:s + 1].expand(M, *batch[k].shape[1:]) for k in _SCENE_KEYS}
        if "init_verts" in batch:
            sub["init_verts"] = batch["init_verts"][s * M:(s + 1) * M]
            sub["init_verts_valid"] = batch["init_verts_valid"][s * M:(s + 1) * M]
        torch.manual_seed(_torch_seed(order_ids[s], seed, stage, enc_idx[s]))
        x0.append(model._init_x0(sub, model.denoiser.k_verts, batch["scene_xyz"].device, M))
    return torch.cat(x0)


def _decode_members(x: torch.Tensor, valid_logit: torch.Tensor, edge_logit: torch.Tensor,
                    frames: Sequence[Tuple[Any, Any, Any]], M: int, validity_thresh: float,
                    xyz_clip: Optional[float]) -> List[List[Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
    """World-space members from the final ODE outputs with ONE device->host copy.

    x (S*M, K, 3), valid_logit (S*M, K), edge_logit (S*M, K, K) on the device; ``frames`` holds S
    host tuples (bbox_center (3,), bbox_scale, bbox_R (3, 3)). ``xyz_clip`` (stage 1) sanitises and
    clamps the normalised state first; None (stage 2) uses it as is. Returns S lists of M host tuples
    (verts_world (m, 3) float32, edges (e, 2) int64 pairs i < j into verts, valid_logits (m,) float32):
    a slot is kept iff its validity logit > validity_thresh, an edge iff its logit > 0."""
    B, K, _ = x.shape
    if xyz_clip is not None:
        x = torch.nan_to_num(x, nan=0.0, posinf=xyz_clip, neginf=-xyz_clip).clamp(-xyz_clip, xyz_clip)
    host = torch.cat([x.reshape(B, 3 * K), valid_logit,
                      (edge_logit > 0.0).reshape(B, K * K).float()], dim=1).cpu().numpy()
    xs, logits = host[:, :3 * K].reshape(B, K, 3), host[:, 3 * K:4 * K]
    edge_pos = host[:, 4 * K:].reshape(B, K, K) > 0.5
    out = []
    for s, (center, scale, R) in enumerate(frames):
        center, R, scale = np.asarray(center, np.float32), np.asarray(R, np.float32), np.float32(scale)
        members = []
        for b in range(s * M, (s + 1) * M):
            idx = np.flatnonzero(logits[b] > validity_thresh)
            verts = ((xs[b, idx] * scale) @ R + center).astype(np.float32)
            edges = np.argwhere(np.triu(edge_pos[b][np.ix_(idx, idx)], 1)).astype(np.int64)
            members.append((verts, edges, logits[b, idx]))
        out.append(members)
    return out


@torch.inference_mode()
def stage1_predict_batch(
    model: WireframeDiffusion,
    scenes: Sequence[Dict[str, np.ndarray]],
    order_ids: Sequence[str],
    cfg: "Stage2Config",
    n_steps: int,
    validity_thresh: float,
    device: torch.device,
    timings: Optional[Dict[str, float]] = None,
) -> List[List[Tuple[np.ndarray, np.ndarray, np.ndarray]]]:
    """Stage 1 on the GPU for S samples at once: one scene encode per sample, cfg.ensemble_n
    members per sample integrated together (B = S * ensemble_n).

    Inputs (host): ``scenes`` = S ``preprocess_sample(...)["scene"]`` dicts with equal point counts,
    ``order_ids`` = their S order_id strings. Sample s reseeds the torch RNG with
    _torch_seed(order_ids[s], cfg.seed, "s1", 0) right before its x0 draws, so results do not depend
    on S or on the batch composition beyond float rounding. Precision: cfg.encoder_bf16 /
    cfg.denoiser_bf16 / the global TF32 setting.
    Returns S lists of cfg.ensemble_n host tuples (verts_world (m, 3) float32, edges (e, 2) int64,
    valid_logits (m,) float32); nothing returned references device memory. ``timings`` (optional)
    accumulates CUDA-synchronised seconds under s1_enc / s1_den / s1_post."""
    M = cfg.ensemble_n
    if cfg.compile and model.denoiser._compiled is None:
        model.denoiser.compile_step()
    with _phase(timings, "s1_enc", device):
        batch = scenes_to_batch(scenes, device)
        feats, sxyz = model.encode(batch, cfg.encoder_bf16)
    with _phase(timings, "s1_den", device):
        x0 = _init_members(model, batch, M, order_ids, cfg.seed, "s1", [0] * len(scenes))
        x, logit, edge = model.integrate(feats, sxyz, x0, n_steps, 1, cfg.denoiser_bf16, cfg.cuda_graph)
    with _phase(timings, "s1_post", device):
        return _decode_members(x, logit, edge,
                               [(s["bbox_center"], s["bbox_scale"], s["bbox_R"]) for s in scenes],
                               M, validity_thresh, model.xyz_clip)


def _fuse_wireframes(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    n_total: int,
    merge_tau_m: float,
    vertex_vote_frac: float = 0.5,
    edge_vote_frac: float = 0.5,
    aggregator: str = "mean",
) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
    """Vertex-merge consensus fusion.

    1. Greedy single-link cluster all run vertices in world coords (threshold
       ``merge_tau_m`` metres). Each cluster centroid is the running mean of
       its members (or a logit-weighted mean when ``aggregator="wmean"``).
    2. Keep clusters supported by at least
       ``ceil(n_total * vertex_vote_frac)`` distinct runs.
    3. For each pair of kept clusters, vote an edge if it appears in at least
       ``ceil(n_total * edge_vote_frac)`` runs.

    Falls back to the single run with the most predicted vertices when no
    cluster meets the support bar — we never collapse to empty when individual
    runs were non-empty. ``runs`` entries are ``(verts, edges, logits)``;
    ``logits`` is only consulted under ``aggregator="wmean"``."""
    if aggregator not in ("mean", "median", "wmean"):
        raise ValueError(
            f"aggregator must be 'mean', 'median', or 'wmean', got {aggregator!r}")
    valid: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]] = []
    for r in runs:
        v_raw = r[0]
        if v_raw is None or len(v_raw) == 0:
            continue
        v = np.asarray(v_raw, dtype=np.float64).reshape(-1, 3)
        e = list(r[1]) if len(r) > 1 and r[1] is not None else []
        lg_raw = r[2] if len(r) > 2 else None
        lg = (np.asarray(lg_raw, dtype=np.float64).reshape(-1)
              if lg_raw is not None else np.zeros(v.shape[0], dtype=np.float64))
        if lg.shape[0] != v.shape[0]:
            lg = np.zeros(v.shape[0], dtype=np.float64)
        valid.append((v, e, lg))
    if not valid:
        return np.zeros((0, 3), dtype=np.float64), []

    v_support = max(1, int(np.ceil(n_total * float(vertex_vote_frac))))
    e_support = max(1, int(np.ceil(n_total * float(edge_vote_frac))))

    # Per-cluster bookkeeping: member positions, member logits, and the set
    # of run indices contributing. Centroid is computed once at the end so
    # 'median' / 'wmean' can use all members (running-mean only worked for
    # the plain 'mean' aggregator).
    cluster_members: List[List[np.ndarray]] = []
    cluster_member_lg: List[List[float]] = []
    cluster_centroids: List[np.ndarray] = []  # running mean — used for matching
    cluster_count: List[int] = []
    cluster_runs: List[set] = []
    vertex_to_cluster: List[List[int]] = []

    for r, (verts, _edges, lg) in enumerate(valid):
        local_map: List[int] = []
        for vi in range(verts.shape[0]):
            v = verts[vi]
            best_c, best_d = -1, float("inf")
            for ci, cc in enumerate(cluster_centroids):
                d = float(np.linalg.norm(v - cc))
                if d < best_d:
                    best_d, best_c = d, ci
            if best_c >= 0 and best_d <= merge_tau_m:
                n = cluster_count[best_c]
                cluster_centroids[best_c] = (cluster_centroids[best_c] * n + v) / (n + 1)
                cluster_count[best_c] = n + 1
                cluster_runs[best_c].add(r)
                cluster_members[best_c].append(v)
                cluster_member_lg[best_c].append(float(lg[vi]))
                local_map.append(best_c)
            else:
                cluster_centroids.append(v.copy())
                cluster_count.append(1)
                cluster_runs.append({r})
                cluster_members.append([v])
                cluster_member_lg.append([float(lg[vi])])
                local_map.append(len(cluster_centroids) - 1)
        vertex_to_cluster.append(local_map)

    kept = [ci for ci, rs in enumerate(cluster_runs) if len(rs) >= v_support]
    if not kept:
        best = max(range(len(valid)), key=lambda r: valid[r][0].shape[0])
        return valid[best][0].astype(np.float64), list(valid[best][1])

    # Final centroids per kept cluster, per aggregator.
    fused_verts = np.empty((len(kept), 3), dtype=np.float64)
    for new_i, ci in enumerate(kept):
        stack = np.stack(cluster_members[ci], axis=0)
        if aggregator == "median":
            fused_verts[new_i] = np.median(stack, axis=0)
        elif aggregator == "wmean":
            lg = np.asarray(cluster_member_lg[ci], dtype=np.float64)
            lg = lg - lg.max()
            w = np.exp(lg)
            ws = float(w.sum())
            if ws <= 1e-12 or not np.isfinite(ws):
                fused_verts[new_i] = stack.mean(axis=0)
            else:
                fused_verts[new_i] = (stack * (w / ws)[:, None]).sum(axis=0)
        else:  # "mean"
            fused_verts[new_i] = stack.mean(axis=0)

    old_to_new = {old: new for new, old in enumerate(kept)}
    n_kept = len(kept)
    edge_votes = np.zeros((n_kept, n_kept), dtype=np.int32)
    for r, (_verts, edges, _lg) in enumerate(valid):
        seen_pairs: set = set()
        for (a, b) in edges:
            if a < 0 or b < 0 or a == b:
                continue
            if a >= len(vertex_to_cluster[r]) or b >= len(vertex_to_cluster[r]):
                continue
            ca = vertex_to_cluster[r][a]
            cb = vertex_to_cluster[r][b]
            if ca == cb or ca not in old_to_new or cb not in old_to_new:
                continue
            i, j = old_to_new[ca], old_to_new[cb]
            if i > j:
                i, j = j, i
            if (i, j) in seen_pairs:
                continue
            seen_pairs.add((i, j))
            edge_votes[i, j] += 1
    ii, jj = np.where(edge_votes >= e_support)
    fused_edges = [(int(a), int(b)) for a, b in zip(ii.tolist(), jj.tolist())]
    return fused_verts, fused_edges


def _wireframe_pair_distance(
    va: np.ndarray, ea: List[Tuple[int, int]],
    vb: np.ndarray, eb: List[Tuple[int, int]],
    match_tau_m: float = 0.4,
) -> float:
    """Symmetric distance between two wireframes for medoid selection.

    Uses Hungarian (optimal 1-1) vertex assignment, which is naturally
    symmetric and aligned with how the HSS metric matches predictions to GT.

    Components:
      * **Vertex term** (metres, capped at ``match_tau_m``): solve the
        rectangular linear-sum-assignment on the pairwise distance matrix
        capped at ``match_tau_m``. Matched pair cost = capped distance;
        unmatched leftover vertices (size mismatch) cost ``match_tau_m`` each.
        Mean over ``max(|Va|, |Vb|)`` slots so the term lives in
        ``[0, match_tau_m]``.
      * **Edge term** (Jaccard, in ``[0, 1]``): the Hungarian assignment
        gives a 1-1 vertex map; use it to relabel B's edges into A's index
        space (only for matches actually within ``match_tau_m``) and compute
        ``1 - IoU`` over the two edge sets.

    Returns a single scalar; lower = more similar. Degenerate empty inputs
    return ``+inf`` so they cannot be picked as the medoid.
    """
    from scipy.optimize import linear_sum_assignment

    va = np.asarray(va, dtype=np.float64).reshape(-1, 3)
    vb = np.asarray(vb, dtype=np.float64).reshape(-1, 3)
    Na, Nb = va.shape[0], vb.shape[0]
    if Na == 0 or Nb == 0:
        return float("inf")

    D = np.linalg.norm(va[:, None, :] - vb[None, :, :], axis=-1)
    D_capped = np.minimum(D, match_tau_m)

    row_ind, col_ind = linear_sum_assignment(D_capped)
    matched_cost = float(D_capped[row_ind, col_ind].sum())
    n_unmatched = abs(Na - Nb)  # leftover on the larger side
    vertex_dist = (matched_cost + n_unmatched * match_tau_m) / max(Na, Nb)

    # Map B → A via the Hungarian assignment, but only when the match is
    # actually within tau (capped matches at exactly tau are unreliable).
    b_to_a = -np.ones(Nb, dtype=np.int64)
    for r, c in zip(row_ind, col_ind):
        if D[r, c] <= match_tau_m:
            b_to_a[c] = r

    ea_norm = set((min(int(i), int(j)), max(int(i), int(j)))
                  for i, j in ea if i != j)
    eb_mapped = set()
    for (i, j) in eb:
        if i == j or i < 0 or j < 0 or i >= Nb or j >= Nb:
            continue
        ai, aj = int(b_to_a[i]), int(b_to_a[j])
        if ai < 0 or aj < 0 or ai == aj:
            continue
        eb_mapped.add((min(ai, aj), max(ai, aj)))

    if not ea_norm and not eb_mapped:
        edge_dist = 0.0
    elif not ea_norm or not eb_mapped:
        edge_dist = 1.0
    else:
        inter = len(ea_norm & eb_mapped)
        union = len(ea_norm | eb_mapped)
        edge_dist = 1.0 - (inter / union)

    return vertex_dist + edge_dist


def _medoid_rank(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    match_tau_m: float = 0.4,
) -> List[int]:
    """Return indices into ``runs`` sorted by centrality (lowest pairwise
    Hungarian distance first → most-central run is index ``[0]``). Empty /
    edgeless runs are excluded from the pairwise computation; if none qualify
    the singleton list ``[longest_run_index]`` is returned. Always returns
    at least one valid index when ``runs`` is non-empty."""
    if not runs:
        return []
    candidates_idx = [r for r, (v, e, *_) in enumerate(runs)
                      if len(v) > 0 and len(e) > 0]
    if not candidates_idx:
        return [max(range(len(runs)),
                    key=lambda r: (len(runs[r][0]) if runs[r][0] is not None else -1,
                                   len(runs[r][1]) if runs[r][1] is not None else -1))]
    if len(candidates_idx) == 1:
        return [candidates_idx[0]]

    n = len(candidates_idx)
    verts = [np.asarray(runs[idx][0], dtype=np.float64).reshape(-1, 3)
             for idx in candidates_idx]
    edges = [list(runs[idx][1]) for idx in candidates_idx]
    dist = np.zeros((n, n), dtype=np.float64)
    for i in range(n):
        for j in range(i + 1, n):
            d = _wireframe_pair_distance(
                verts[i], edges[i], verts[j], edges[j],
                match_tau_m=match_tau_m,
            )
            dist[i, j] = d
            dist[j, i] = d
    centrality = dist.sum(axis=1)
    order = np.argsort(centrality, kind="stable")
    return [candidates_idx[int(k)] for k in order]


def _medoid_select_idx(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    match_tau_m: float = 0.4,
) -> int:
    """Return the index into ``runs`` of the medoid — the run whose wireframe
    is most similar to the others by Hungarian-matched distance. Thin wrapper
    around ``_medoid_rank`` that returns just the most-central index."""
    ranking = _medoid_rank(runs, match_tau_m=match_tau_m)
    return ranking[0] if ranking else 0


def _confidence_select_idx(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
) -> int:
    """Return the index into ``runs`` of the highest mean-validity-logit run.
    Skips empty / all-NaN runs in the scoring; falls back to the longest run
    when no run has meaningful confidence."""
    if not runs:
        return 0
    scored: List[Tuple[float, int]] = []
    for i, (v, _e, logits) in enumerate(runs):
        if v is None or len(v) == 0 or logits is None or len(logits) == 0:
            continue
        arr = np.asarray(logits, dtype=np.float64)
        if not np.all(np.isfinite(arr)):
            arr = arr[np.isfinite(arr)]
            if arr.size == 0:
                continue
        scored.append((float(arr.mean()), i))
    if not scored:
        return max(range(len(runs)),
                   key=lambda r: (len(runs[r][0]) if runs[r][0] is not None else -1,
                                  len(runs[r][1]) if runs[r][1] is not None else -1))
    return max(scored, key=lambda t: t[0])[1]


def _refine_positions(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    picked_idx: int,
    match_tau_m: float,
    aggregator: str = "mean",
    member_indices: Optional[Sequence[int]] = None,
    vertex_vote_frac: float = 0.0,
) -> Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]:
    """Position refinement on top of a single picked run.

    Keep the picked run's vertices and edges (topology unchanged). For each
    vertex ``v`` of the picked run, find its Hungarian-matched correspondent
    in every other run (only matches within ``match_tau_m`` count), then
    replace ``v`` with the per-axis ``aggregator`` of ``{v}`` ∪
    correspondents.

    ``aggregator`` ∈ {"mean", "median", "wmean"}:
      * ``"mean"`` (default) — simple average; lower variance under iid noise
        but sensitive to outliers.
      * ``"median"`` — per-axis median. Robust to a single bad correspondent
        (e.g., an off-by-one Hungarian match at the Ï„ boundary).
      * ``"wmean"`` — softmax-of-validity-logit weighted mean.

    Rationale: vertex prediction is the dominant noise source (F1 hits HSS
    harder than IoU). Selectors (medoid / confidence) pick a *vertex set*
    that's already good; this step denoises each vertex's *position* by
    aggregating with consensus detections from the other N−1 runs. Topology
    (edges) is untouched so we never lose recall on edges.

    Returns ``(verts_refined, edges_picked)``. Falls back to the picked
    run's verts/edges verbatim when no refinement signal is available."""
    from scipy.optimize import linear_sum_assignment

    if aggregator not in ("median", "mean", "wmean"):
        raise ValueError(
            f"aggregator must be 'median', 'mean', or 'wmean', got {aggregator!r}")
    if not runs:
        return np.zeros((0, 3), dtype=np.float64), [], np.zeros((0,), dtype=np.int64)
    picked_v_raw, picked_e_raw, picked_logits = runs[picked_idx]
    picked_v = np.asarray(picked_v_raw, dtype=np.float64).reshape(-1, 3)
    picked_e = list(picked_e_raw)
    if picked_v.shape[0] == 0:
        return picked_v, picked_e, np.zeros((0,), dtype=np.int64)

    M = picked_v.shape[0]
    picked_lg = (np.asarray(picked_logits, dtype=np.float64).reshape(-1)
                 if picked_logits is not None else np.zeros(M, dtype=np.float64))
    if picked_lg.shape[0] != M:
        picked_lg = np.zeros(M, dtype=np.float64)

    # Per-picked-vertex correspondent positions and per-correspondent logits
    # (used for 'wmean' aggregation). Picked run is always the first entry.
    correspondents: List[List[np.ndarray]] = [[picked_v[i]] for i in range(M)]
    corr_logits: List[List[float]] = [[float(picked_lg[i])] for i in range(M)]

    if member_indices is None:
        contributor_iter: List[int] = list(range(len(runs)))
    else:
        contributor_iter = list(member_indices)
        if picked_idx not in contributor_iter:
            contributor_iter.append(picked_idx)
    # Voter set includes picked (self-vote on each vertex).
    M_voters = max(1, len(set(contributor_iter)))

    for j in contributor_iter:
        if j == picked_idx or j < 0 or j >= len(runs):
            continue
        vj_raw, _ej, lj_raw = runs[j]
        vj = np.asarray(vj_raw, dtype=np.float64).reshape(-1, 3)
        if vj.shape[0] == 0:
            continue
        lj = (np.asarray(lj_raw, dtype=np.float64).reshape(-1)
              if lj_raw is not None else np.zeros(vj.shape[0], dtype=np.float64))
        if lj.shape[0] != vj.shape[0]:
            lj = np.zeros(vj.shape[0], dtype=np.float64)
        D = np.linalg.norm(picked_v[:, None, :] - vj[None, :, :], axis=-1)
        D_capped = np.minimum(D, match_tau_m)
        row_ind, col_ind = linear_sum_assignment(D_capped)
        for r, c in zip(row_ind, col_ind):
            if D[r, c] <= match_tau_m:
                correspondents[r].append(vj[c])
                corr_logits[r].append(float(lj[c]))

    # Vertex consensus drop. A picked vertex survives iff at least
    # ceil(M_voters * vertex_vote_frac) voters support it (including the
    # picked run's self-vote).
    if vertex_vote_frac > 0.0:
        threshold = int(np.ceil(M_voters * float(vertex_vote_frac)))
        keep_mask = np.array(
            [len(correspondents[i]) >= threshold for i in range(M)],
            dtype=bool,
        )
        if not keep_mask.any():
            # Don't collapse to empty — fall back to keeping all picked verts.
            keep_mask[:] = True
    else:
        keep_mask = np.ones(M, dtype=bool)

    keep_idx = np.flatnonzero(keep_mask).astype(np.int64)

    refined = np.empty((keep_idx.size, 3), dtype=np.float64)
    for new_i, old_i in enumerate(keep_idx):
        stack = np.stack(correspondents[int(old_i)], axis=0)
        if aggregator == "median":
            refined[new_i] = np.median(stack, axis=0)
        elif aggregator == "mean":
            refined[new_i] = stack.mean(axis=0)
        else:  # "wmean"
            lg = np.asarray(corr_logits[int(old_i)], dtype=np.float64)
            # Softmax over logits for stable positive weights; falls back to
            # uniform when logits are all-equal / missing.
            lg = lg - lg.max()
            w = np.exp(lg)
            w_sum = float(w.sum())
            if w_sum <= 1e-12 or not np.isfinite(w_sum):
                refined[new_i] = stack.mean(axis=0)
            else:
                w = w / w_sum
                refined[new_i] = (stack * w[:, None]).sum(axis=0)

    # Remap picked-run edges into the kept-vertex index space; drop edges
    # whose endpoints didn't survive the vertex vote.
    old_to_new = -np.ones(M, dtype=np.int64)
    for new_i, old_i in enumerate(keep_idx):
        old_to_new[int(old_i)] = new_i
    edges_remapped: List[Tuple[int, int]] = []
    for (a, b) in picked_e:
        ia, ib = int(a), int(b)
        if ia < 0 or ib < 0 or ia >= M or ib >= M or ia == ib:
            continue
        na, nb = int(old_to_new[ia]), int(old_to_new[ib])
        if na < 0 or nb < 0 or na == nb:
            continue
        edges_remapped.append((na, nb))

    return refined, edges_remapped, keep_idx


def _vote_edges(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    picked_idx: int,
    match_tau_m: float,
    vote_frac: float = 0.5,
    member_indices: Optional[Sequence[int]] = None,
    keep_idx: Optional[np.ndarray] = None,
) -> List[Tuple[int, int]]:
    """Majority-vote edge refinement.

    For each voter run, Hungarian-match its vertices to the picked run's
    vertices (matches outside ``match_tau_m`` ignored), relabel its edges
    into picked-vertex index space, and tally votes per ``(i, j)`` pair.
    An edge survives if at least ``ceil(M * vote_frac)`` voters (out of
    ``M`` = ``len(member_indices)`` or ``len(runs)``) vote for it. The
    picked run itself is always a voter — its own edges therefore enter
    with one self-vote.

    Returns the filtered edge list in picked-vertex index space.
    """
    from scipy.optimize import linear_sum_assignment

    if not runs:
        return []
    picked_v = np.asarray(runs[picked_idx][0], dtype=np.float64).reshape(-1, 3)
    if picked_v.shape[0] == 0:
        return list(runs[picked_idx][1])

    if member_indices is None:
        voters: List[int] = list(range(len(runs)))
    else:
        voters = [int(j) for j in member_indices if 0 <= int(j) < len(runs)]
        if picked_idx not in voters:
            voters.append(int(picked_idx))
    M = max(1, len(voters))
    threshold = int(np.ceil(M * float(vote_frac)))

    votes: Dict[Tuple[int, int], int] = {}
    Mp = picked_v.shape[0]
    for j in voters:
        vj_raw, ej_raw, _lj = runs[j]
        vj = np.asarray(vj_raw, dtype=np.float64).reshape(-1, 3)
        if j == picked_idx:
            j_to_p = np.arange(Mp, dtype=np.int64)
        else:
            if vj.shape[0] == 0:
                continue
            D = np.linalg.norm(picked_v[:, None, :] - vj[None, :, :], axis=-1)
            D_capped = np.minimum(D, match_tau_m)
            row_ind, col_ind = linear_sum_assignment(D_capped)
            j_to_p = -np.ones(vj.shape[0], dtype=np.int64)
            for r, c in zip(row_ind, col_ind):
                if D[r, c] <= match_tau_m:
                    j_to_p[c] = r

        for (a, b) in ej_raw:
            ia, ib = int(a), int(b)
            if ia == ib or ia < 0 or ib < 0 or ia >= len(j_to_p) or ib >= len(j_to_p):
                continue
            pa, pb = int(j_to_p[ia]), int(j_to_p[ib])
            if pa < 0 or pb < 0 or pa == pb:
                continue
            key = (min(pa, pb), max(pa, pb))
            votes[key] = votes.get(key, 0) + 1

    kept_old = [(int(i), int(j)) for (i, j), c in votes.items() if c >= threshold]
    if not kept_old:
        # Degenerate vote tally (e.g. only the picked run voted on edges with
        # vote_frac > 1/M). Fall back to picked edges so we never lose all
        # edges — F1 would zero out HSS.
        kept_old = [(int(a), int(b)) for (a, b) in runs[picked_idx][1]
                    if int(a) != int(b)]

    if keep_idx is None:
        return kept_old

    # Remap from picked-vertex index space → kept-vertex index space (the
    # output of _refine_positions when vertex_vote_frac > 0 drops some
    # picked vertices). Edges referencing dropped vertices are filtered out.
    old_to_new = -np.ones(Mp, dtype=np.int64)
    for new_i, old_i in enumerate(np.asarray(keep_idx).reshape(-1)):
        oi = int(old_i)
        if 0 <= oi < Mp:
            old_to_new[oi] = new_i
    out: List[Tuple[int, int]] = []
    for (a, b) in kept_old:
        na, nb = int(old_to_new[a]), int(old_to_new[b])
        if na < 0 or nb < 0 or na == nb:
            continue
        out.append((min(na, nb), max(na, nb)))
    return out


# ------------------------------------------------------------------
# 2D gestalt-mask reprojection features
# ------------------------------------------------------------------
# Pixels of these gestalt classes mark wireframe edges (lines).
_GESTALT_EDGE_NAMES = (
    "ridge", "eave", "rake", "hip", "valley",
    "fascia", "transition_line", "flashing", "step_flashing",
    "ground_line", "soffit",
)
# Pixels of these classes mark wireframe vertices (line endpoints).
_GESTALT_VERT_NAMES = (
    "apex", "eave_end_point", "flashing_end_point",
)


def _ids_from_class_names(names: Tuple[str, ...]) -> np.ndarray:
    return np.array(
        sorted(GESTALT_CLASSES.index(n) for n in names if n in GESTALT_CLASSES),
        dtype=np.int64,
    )


_EDGE_GESTALT_IDS = _ids_from_class_names(_GESTALT_EDGE_NAMES)
_VERT_GESTALT_IDS = _ids_from_class_names(_GESTALT_VERT_NAMES)


def _build_reprojection_views(
    raw_sample: Dict[str, Any],
    colmap_rec,
    edge_dilate: int = 2,
    vert_dilate: int = 4,
) -> List[Dict[str, Any]]:
    """Pre-compute per-view camera + dilated gestalt masks for reprojection.

    Returns a list of dicts with keys
      ``R`` (3,3), ``t`` (3,), ``fx``, ``fy``, ``cx``, ``cy``, ``W``, ``H``,
      ``edge_mask`` and ``vert_mask`` (both uint8 HxW).

    The masks are 1 where pixels belong to wireframe edge / vertex gestalt
    classes (dilated by ``edge_dilate`` / ``vert_dilate`` 3x3 iterations to
    tolerate small projection error and label boundary noise).
    """
    try:
        from scipy.ndimage import binary_dilation
    except Exception:
        binary_dilation = None  # type: ignore

    image_ids = raw_sample.get("image_ids", []) or []
    gestalt_imgs = raw_sample.get("gestalt", []) or []
    if not image_ids or not gestalt_imgs:
        return []

    colmap_by_name = {
        col_img.name: col_img for col_img in colmap_rec.images.values()
    }
    structure = np.ones((3, 3), dtype=bool)

    out: List[Dict[str, Any]] = []
    for i, img_id in enumerate(image_ids):
        if i >= len(gestalt_imgs) or gestalt_imgs[i] is None:
            continue
        col_img = _resolve_colmap_image(colmap_by_name, img_id)
        if col_img is None:
            continue
        cam = _camera_for_image(colmap_rec, col_img)
        cam_w = int(getattr(cam, "width", 0) or 0)
        cam_h = int(getattr(cam, "height", 0) or 0)
        if cam_w <= 0 or cam_h <= 0:
            continue
        try:
            R, t = _cam_matrix_from_image(col_img)
            R = np.asarray(R, dtype=np.float64).reshape(3, 3)
            t = np.asarray(t, dtype=np.float64).reshape(3)
            K = cam.calibration_matrix()
        except Exception:
            continue
        try:
            gest_np = _image_to_rgb_array(gestalt_imgs[i])
        except Exception:
            continue
        ids = gestalt_img_to_ids(gest_np)
        edge_tight = np.isin(ids, _EDGE_GESTALT_IDS)
        vert_tight = np.isin(ids, _VERT_GESTALT_IDS)
        edge_mask = edge_tight.copy()
        vert_mask = vert_tight.copy()
        if binary_dilation is not None:
            if edge_dilate > 0 and edge_mask.any():
                edge_mask = binary_dilation(
                    edge_mask, structure=structure, iterations=int(edge_dilate))
            if vert_dilate > 0 and vert_mask.any():
                vert_mask = binary_dilation(
                    vert_mask, structure=structure, iterations=int(vert_dilate))
        H, W = ids.shape[:2]
        out.append({
            "R": R, "t": t,
            "fx": float(K[0, 0]), "fy": float(K[1, 1]),
            "cx": float(K[0, 2]), "cy": float(K[1, 2]),
            "cam_w": float(cam_w), "cam_h": float(cam_h),
            "W": int(W), "H": int(H),
            "edge_mask": np.ascontiguousarray(edge_mask, dtype=bool),
            "vert_mask": np.ascontiguousarray(vert_mask, dtype=bool),
            "edge_mask_tight": np.ascontiguousarray(edge_tight, dtype=bool),
            "vert_mask_tight": np.ascontiguousarray(vert_tight, dtype=bool),
            "ids": np.ascontiguousarray(ids, dtype=np.int32),
        })
    return out


def _project_to_mask(
    pts: np.ndarray,
    view: Dict[str, Any],
    which: str,
) -> Tuple[np.ndarray, np.ndarray]:
    """Project (N,3) world points into one view's mask.

    Returns (in_view, hit) bool arrays of length N. ``in_view`` is True when
    the point is in front of the camera and lands inside the image; ``hit``
    is True when in_view AND the mask is set at the corresponding pixel.
    """
    R = view["R"]; t = view["t"]
    p_cam = pts @ R.T + t
    z = p_cam[:, 2]
    valid = z > 1e-6
    u = np.empty_like(z); v = np.empty_like(z)
    zsafe = np.where(valid, z, 1.0)
    u_proj = p_cam[:, 0] / zsafe * view["fx"] + view["cx"]
    v_proj = p_cam[:, 1] / zsafe * view["fy"] + view["cy"]
    sx = view["W"] / view["cam_w"]; sy = view["H"] / view["cam_h"]
    ui = np.rint(u_proj * sx).astype(np.int64)
    vi = np.rint(v_proj * sy).astype(np.int64)
    in_view = valid & (ui >= 0) & (ui < view["W"]) & (vi >= 0) & (vi < view["H"])
    mask = view[which]
    hit = np.zeros(pts.shape[0], dtype=bool)
    if in_view.any():
        idx = np.where(in_view)[0]
        hit[idx] = mask[vi[idx], ui[idx]]
    return in_view, hit


def _reprojection_features(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    views: List[Dict[str, Any]],
    n_edge_samples: int = 8,
) -> Tuple[float, float, float, float]:
    """Return ``(vert_mean, vert_min, edge_mean, edge_min)`` — legacy stub.

    Mostly kept for backwards-compatibility; new code should call
    :func:`_reprojection_features_extended` for the richer per-vertex /
    per-edge breakdown.
    """
    res = _reprojection_features_extended(verts, edges, views, n_edge_samples)
    return res["vert_mean"], res["vert_min"], res["edge_mean"], res["edge_min"]


def _reprojection_features_extended(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    views: List[Dict[str, Any]],
    n_edge_samples: int = 8,
) -> Dict[str, Any]:
    """Full reprojection scoring with per-vertex / per-edge arrays.

    Returns a dict with scalar fields:
      vert_mean, vert_min, vert_worst3_mean, vert_bad_frac,
      vert_soft_mean,
      edge_mean, edge_min, edge_worst3_mean, edge_bad_frac,
      edge_soft_mean,
      endpoint_corner_mean, endpoint_corner_min,
    plus arrays:
      per_v (Nv,), per_e (Ne,)
    All scalars in [0, 1]. "soft" uses the non-dilated (tight) masks;
    "bad" thresholds at 0.1; "worst3" averages the 3 lowest scores.
    """
    out = {
        "vert_mean": 0.0, "vert_min": 0.0,
        "vert_worst3_mean": 0.0, "vert_bad_frac": 0.0,
        "vert_soft_mean": 0.0,
        "edge_mean": 0.0, "edge_min": 0.0,
        "edge_worst3_mean": 0.0, "edge_bad_frac": 0.0,
        "edge_soft_mean": 0.0,
        "endpoint_corner_mean": 0.0, "endpoint_corner_min": 0.0,
        "per_v": np.zeros((0,), dtype=np.float64),
        "per_e": np.zeros((0,), dtype=np.float64),
    }
    if not views or verts.size == 0:
        return out
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    Nv = v.shape[0]

    # --- vertices: dilated + tight masks ---
    vert_hits = np.zeros(Nv, dtype=np.float64)
    vert_soft = np.zeros(Nv, dtype=np.float64)
    vert_views = np.zeros(Nv, dtype=np.float64)
    for view in views:
        in_view, hit = _project_to_mask(v, view, "vert_mask")
        _, hit_soft = _project_to_mask(v, view, "vert_mask_tight")
        vert_views += in_view.astype(np.float64)
        vert_hits += hit.astype(np.float64)
        vert_soft += hit_soft.astype(np.float64)
    denom = np.maximum(vert_views, 1.0)
    per_v = np.where(vert_views > 0, vert_hits / denom, 0.0)
    per_v_soft = np.where(vert_views > 0, vert_soft / denom, 0.0)
    out["per_v"] = per_v
    out["vert_mean"] = float(per_v.mean())
    out["vert_min"] = float(per_v.min())
    k3 = min(3, Nv)
    out["vert_worst3_mean"] = float(np.sort(per_v)[:k3].mean()) if k3 else 0.0
    out["vert_bad_frac"] = float(np.mean(per_v < 0.1))
    out["vert_soft_mean"] = float(per_v_soft.mean())

    if not edges:
        return out
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    Ne = e_arr.shape[0]

    # --- edges: sample interior, dilated + tight masks ---
    ts = np.linspace(0.0, 1.0, n_edge_samples + 2)[1:-1]
    a = v[e_arr[:, 0]]; b = v[e_arr[:, 1]]
    samples = a[:, None, :] + (b - a)[:, None, :] * ts[None, :, None]
    sflat = samples.reshape(-1, 3)
    eh = np.zeros(Ne * n_edge_samples, dtype=np.float64)
    eh_soft = np.zeros_like(eh)
    ev = np.zeros_like(eh)
    for view in views:
        in_view, hit = _project_to_mask(sflat, view, "edge_mask")
        _, hit_soft = _project_to_mask(sflat, view, "edge_mask_tight")
        ev += in_view.astype(np.float64)
        eh += hit.astype(np.float64)
        eh_soft += hit_soft.astype(np.float64)
    edenom = np.maximum(ev, 1.0)
    per_sample = np.where(ev > 0, eh / edenom, 0.0)
    per_sample_soft = np.where(ev > 0, eh_soft / edenom, 0.0)
    per_e = per_sample.reshape(Ne, n_edge_samples).mean(axis=1)
    per_e_soft = per_sample_soft.reshape(Ne, n_edge_samples).mean(axis=1)
    out["per_e"] = per_e
    out["edge_mean"] = float(per_e.mean())
    out["edge_min"] = float(per_e.min())
    k3e = min(3, Ne)
    out["edge_worst3_mean"] = float(np.sort(per_e)[:k3e].mean()) if k3e else 0.0
    out["edge_bad_frac"] = float(np.mean(per_e < 0.1))
    out["edge_soft_mean"] = float(per_e_soft.mean())

    # --- endpoint-on-corner: per-edge min(endpoint vertex scores) ---
    if Nv > 0:
        e_endpoint_min = np.minimum(per_v[e_arr[:, 0]], per_v[e_arr[:, 1]])
        out["endpoint_corner_mean"] = float(e_endpoint_min.mean())
        out["endpoint_corner_min"] = float(e_endpoint_min.min())
    return out


def _stage1_displacement_features(
    verts: np.ndarray,
    s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]],
) -> Tuple[float, float, float]:
    """Distance from candidate vertices to nearest stage-1 prediction.

    Returns ``(disp_mean, disp_max, disp_far_frac)``, where ``disp_far_frac``
    is the fraction of candidate vertices > 0.5 m from any stage-1 vertex.
    """
    if not s1_runs or verts.size == 0:
        return 0.0, 0.0, 0.0
    cv = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    if cv.shape[0] == 0:
        return 0.0, 0.0, 0.0
    s1_v: List[np.ndarray] = []
    for entry in s1_runs:
        rv = entry[0] if isinstance(entry, (tuple, list)) else entry
        rv = np.asarray(rv, dtype=np.float64).reshape(-1, 3)
        if rv.shape[0] > 0:
            s1_v.append(rv)
    if not s1_v:
        return 0.0, 0.0, 0.0
    pool = np.concatenate(s1_v, axis=0)
    D = np.linalg.norm(cv[:, None, :] - pool[None, :, :], axis=-1)
    d_min = D.min(axis=1)
    return (float(d_min.mean()), float(d_min.max()),
            float(np.mean(d_min > 0.5)))


def _connectivity_features(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
) -> Tuple[float, float, float]:
    """``(n_components_norm, cycle_rank_norm, degree_entropy)``.

    * ``n_components_norm`` = (n_components - 1) / max(1, Nv) — 0 when fully
      connected, grows with disconnected fragments.
    * ``cycle_rank_norm``  = (Ne - Nv + n_components) / max(1, Nv) — Betti-1
      density; very low (tree-like) or very high (over-connected) are both
      suspicious.
    * ``degree_entropy``  = Shannon entropy of the degree distribution in nats.
    """
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    Nv = v.shape[0]
    if Nv == 0 or not edges:
        return 0.0, 0.0, 0.0
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    Ne = e_arr.shape[0]
    adj: List[List[int]] = [[] for _ in range(Nv)]
    for a, b in e_arr:
        if 0 <= a < Nv and 0 <= b < Nv and a != b:
            adj[a].append(b); adj[b].append(a)
    visited = [False] * Nv
    n_components = 0
    for s in range(Nv):
        if visited[s]:
            continue
        n_components += 1
        stack = [s]
        while stack:
            u = stack.pop()
            if visited[u]: continue
            visited[u] = True
            for w in adj[u]:
                if not visited[w]:
                    stack.append(w)
    cycle_rank = Ne - Nv + n_components
    deg = np.array([len(a) for a in adj], dtype=np.float64)
    p = np.bincount(deg.astype(np.int64))
    p = p / p.sum() if p.sum() > 0 else p
    p = p[p > 0]
    deg_entropy = float(-(p * np.log(p)).sum()) if p.size > 0 else 0.0
    return (
        float((n_components - 1) / max(1, Nv)),
        float(cycle_rank / max(1, Nv)),
        deg_entropy,
    )


def _symmetry_residual(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
) -> float:
    """Best reflection-plane residual normalised by mean edge length.

    Computes PCA on the candidate vertices, tries reflecting across each of
    the three principal planes (normal = each eigenvector through the
    centroid), Hungarian-matches reflected vs. original verts, and returns
    the minimum mean matched distance / mean edge length. Lower = more
    symmetric. 0 when the wireframe has fewer than 4 vertices or any edge.
    """
    from scipy.optimize import linear_sum_assignment
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    Nv = v.shape[0]
    if Nv < 4 or not edges:
        return 0.0
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    lengths = np.linalg.norm(v[e_arr[:, 0]] - v[e_arr[:, 1]], axis=1)
    mean_len = float(lengths.mean()) if lengths.size > 0 else 0.0
    if mean_len < 1e-6:
        return 0.0
    centroid = v.mean(axis=0)
    Q = v - centroid
    try:
        _, S, Vt = np.linalg.svd(Q, full_matrices=False)
    except np.linalg.LinAlgError:
        return 0.0
    axes = Vt  # rows are unit principal directions
    best = float("inf")
    for k in range(min(3, axes.shape[0])):
        n = axes[k]
        # Reflect Q across plane through centroid with normal n.
        ref = Q - 2.0 * (Q @ n)[:, None] * n[None, :]
        D = np.linalg.norm(Q[:, None, :] - ref[None, :, :], axis=-1)
        row, col = linear_sum_assignment(D)
        matched_d = D[row, col]
        cost = float(matched_d.mean())
        if cost < best:
            best = cost
    if not np.isfinite(best):
        return 0.0
    return float(best / mean_len)


def _per_edge_class_consistency(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    views: List[Dict[str, Any]],
    n_edge_samples: int = 8,
) -> Tuple[float, float]:
    """Gestalt-class purity per edge, aggregated to candidate-level stats.

    For each edge we sample interior points, project to each view, and look
    up the gestalt-class id at the pixel. Across all (sample × view) hits we
    take the modal class and define edge-purity as the fraction of hits
    belonging to that mode. Returns ``(mean_purity, high_purity_frac)``
    where ``high_purity_frac = mean(purity > 0.5)``. Both are 0 with no
    views or edges.
    """
    if not views or not edges or verts.size == 0:
        return 0.0, 0.0
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    Ne = e_arr.shape[0]
    ts = np.linspace(0.0, 1.0, n_edge_samples + 2)[1:-1]
    a = v[e_arr[:, 0]]; b = v[e_arr[:, 1]]
    samples = a[:, None, :] + (b - a)[:, None, :] * ts[None, :, None]
    sflat = samples.reshape(-1, 3)
    # (Ne*S, V) classes; -1 = no hit
    cls_per_view: List[np.ndarray] = []
    for view in views:
        R = view["R"]; t = view["t"]
        p_cam = sflat @ R.T + t
        z = p_cam[:, 2]
        valid = z > 1e-6
        zsafe = np.where(valid, z, 1.0)
        u_proj = p_cam[:, 0] / zsafe * view["fx"] + view["cx"]
        v_proj = p_cam[:, 1] / zsafe * view["fy"] + view["cy"]
        sx = view["W"] / view["cam_w"]; sy = view["H"] / view["cam_h"]
        ui = np.rint(u_proj * sx).astype(np.int64)
        vi = np.rint(v_proj * sy).astype(np.int64)
        in_view = (valid & (ui >= 0) & (ui < view["W"])
                   & (vi >= 0) & (vi < view["H"]))
        cls = -np.ones(sflat.shape[0], dtype=np.int64)
        if in_view.any():
            idx = np.where(in_view)[0]
            cls[idx] = view["ids"][vi[idx], ui[idx]]
        # Only keep edge-class hits (other classes are background-ish noise)
        is_edge_cls = np.isin(cls, _EDGE_GESTALT_IDS)
        cls = np.where(is_edge_cls, cls, -1)
        cls_per_view.append(cls)
    if not cls_per_view:
        return 0.0, 0.0
    cls_stack = np.stack(cls_per_view, axis=0).reshape(
        len(views), Ne, n_edge_samples)
    # For each edge: flatten (V*S) hits, drop -1, compute mode purity.
    purities = np.zeros(Ne, dtype=np.float64)
    for e_i in range(Ne):
        hits = cls_stack[:, e_i, :].reshape(-1)
        hits = hits[hits >= 0]
        if hits.size == 0:
            purities[e_i] = 0.0
            continue
        counts = np.bincount(hits.astype(np.int64))
        purities[e_i] = float(counts.max()) / float(hits.size)
    return float(purities.mean()), float(np.mean(purities > 0.5))


def _structural_features(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
) -> Tuple[float, float]:
    """Cheap structural priors: degree-1 vertex fraction + edge-length CV."""
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    Nv = v.shape[0]
    if Nv == 0 or not edges:
        return 0.0, 0.0
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    deg = np.zeros(Nv, dtype=np.int64)
    for a, b in e_arr:
        if 0 <= a < Nv: deg[a] += 1
        if 0 <= b < Nv: deg[b] += 1
    degree1_frac = float(np.mean(deg == 1))
    lengths = np.linalg.norm(v[e_arr[:, 0]] - v[e_arr[:, 1]], axis=1)
    mean_len = float(lengths.mean()) if lengths.size > 0 else 0.0
    cv = float(lengths.std() / mean_len) if mean_len > 1e-6 else 0.0
    return degree1_frac, cv


def _coplanarity_score(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    max_cycles: int = 64,
) -> float:
    """Median plane-fit residual of 4-cycles, mapped to [0, 1] (higher = flatter).

    Buildings are mostly composed of planar quads (roof faces, wall panels).
    For every length-4 cycle in the wireframe we compute the third singular
    value of the centred (4,3) vertex matrix — the out-of-plane spread —
    normalised by the cycle's average edge length. The median residual is
    then mapped to ``exp(-5*r)`` so the feature is in [0, 1] with 1 = perfectly
    planar. Returns 0 when no cycles exist.
    """
    Nv = verts.shape[0]
    if Nv < 4 or not edges:
        return 0.0
    adj = [set() for _ in range(Nv)]
    for a, b in edges:
        a, b = int(a), int(b)
        if 0 <= a < Nv and 0 <= b < Nv and a != b:
            adj[a].add(b); adj[b].add(a)
    cycles: List[Tuple[int, int, int, int]] = []
    for u in range(Nv):
        for v_idx in range(u + 1, Nv):
            common = adj[u] & adj[v_idx]
            if len(common) < 2:
                continue
            comm = sorted(c for c in common if c != u and c != v_idx)
            for i in range(len(comm)):
                for j in range(i + 1, len(comm)):
                    cycles.append((u, comm[i], v_idx, comm[j]))
                    if len(cycles) >= max_cycles:
                        break
                if len(cycles) >= max_cycles: break
            if len(cycles) >= max_cycles: break
        if len(cycles) >= max_cycles: break
    if not cycles:
        return 0.0
    vals = []
    for cyc in cycles:
        pts = verts[list(cyc)]
        centroid = pts.mean(axis=0)
        Q = pts - centroid
        try:
            S = np.linalg.svd(Q, compute_uv=False)
        except np.linalg.LinAlgError:
            continue
        if S.size < 3:
            continue
        dev = float(S[-1])
        perim = 0.0
        for k in range(4):
            a, b = cyc[k], cyc[(k + 1) % 4]
            perim += float(np.linalg.norm(verts[a] - verts[b]))
        mean_len = perim / 4.0
        if mean_len < 1e-6:
            continue
        vals.append(dev / mean_len)
    if not vals:
        return 0.0
    return float(np.exp(-5.0 * float(np.median(vals))))


def _junction_angle_dev(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
) -> float:
    """Mean angular deviation of edge-pair junctions from {90°, 180°} in radians.

    At each vertex with degree >= 2, we compute the angle between every pair
    of incident edges and take the smaller deviation to 90° or 180° (the two
    angles that dominate roof/wall geometry). Lower is better; 0 means every
    junction sits exactly at a right or straight angle.
    """
    Nv = verts.shape[0]
    if Nv == 0 or not edges:
        return 0.0
    nbrs: List[List[int]] = [[] for _ in range(Nv)]
    for a, b in edges:
        a, b = int(a), int(b)
        if 0 <= a < Nv and 0 <= b < Nv and a != b:
            nbrs[a].append(b); nbrs[b].append(a)
    devs: List[float] = []
    for u in range(Nv):
        if len(nbrs[u]) < 2:
            continue
        dirs: List[np.ndarray] = []
        for v_idx in nbrs[u]:
            d = verts[v_idx] - verts[u]
            n = float(np.linalg.norm(d))
            if n > 1e-6:
                dirs.append(d / n)
        for i in range(len(dirs)):
            for j in range(i + 1, len(dirs)):
                c = float(np.clip(np.dot(dirs[i], dirs[j]), -1.0, 1.0))
                ang = float(np.arccos(c))
                devs.append(min(abs(ang - np.pi / 2), abs(ang - np.pi)))
    if not devs:
        return 0.0
    return float(np.mean(devs))


def _principal_axis_features(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    cos_thresh: float = 0.9659,  # cos(15°)
) -> Tuple[float, float]:
    """Manhattan structure features from per-edge direction PCA.

    Returns ``(manhattan_frac, top1_frac)``:
      * ``manhattan_frac`` — fraction of edges within 15° of any of the top-3
        eigenvectors of the symmetric second-moment matrix ``sum_i d_i d_i^T``
        (antipodal-symmetric: signs don't matter).
      * ``top1_frac`` — same, but only against the *dominant* eigenvector;
        a proxy for "fraction of edges aligned with the building's principal
        axis" (often vertical in COLMAP world).
    """
    if not edges or verts.shape[0] == 0:
        return 0.0, 0.0
    e_arr = np.asarray(edges, dtype=np.int64).reshape(-1, 2)
    if e_arr.shape[0] == 0:
        return 0.0, 0.0
    d = verts[e_arr[:, 1]] - verts[e_arr[:, 0]]
    nrm = np.linalg.norm(d, axis=1)
    valid = nrm > 1e-6
    if not valid.any():
        return 0.0, 0.0
    u = d[valid] / nrm[valid, None]
    M = u.T @ u
    try:
        eigvals, eigvecs = np.linalg.eigh(M)
    except np.linalg.LinAlgError:
        return 0.0, 0.0
    order = np.argsort(-eigvals)
    eigvecs = eigvecs[:, order]
    dots = np.abs(u @ eigvecs)
    max_any = dots.max(axis=1)
    max_top1 = dots[:, 0]
    return (float(np.mean(max_any >= cos_thresh)),
            float(np.mean(max_top1 >= cos_thresh)))


_RANKER_FEATURE_NAMES = [
    "n_v",
    "n_e",
    "edge_density",
    "logit_mean",
    "logit_std",
    "logit_min",
    "logit_max",
    "vertex_support_mean",
    "vertex_support_std",
    "vertex_support_min",
    "edge_support_mean",
    "edge_support_max",
    "centrality_mean",
    "centrality_min",
    "centrality_rank",
    "is_raw_member",
    "is_medoid_source",
    "is_conf_source",
    "is_refined",
    "uses_edge_vote",
    "uses_add_edges",
    "uses_topk",
    "source_idx",
    # --- 2D reprojection + structural priors (added) ---
    "vert_reproj_mean",
    "vert_reproj_min",
    "edge_reproj_mean",
    "edge_reproj_min",
    "degree1_frac",
    "edge_length_cv",
    # --- geometric priors (added) ---
    "coplanarity_score",
    "junction_angle_dev",
    "manhattan_frac",
    "principal_axis_align",
    # --- v5 features (selected from v4 ablation: only those that survived
    # 5-fold CV with positive lift in addition to v3) ---
    "s1_disp_far_frac",
    "degree_entropy",
    "symmetry_residual",
]


def _edge_key_set(edges: List[Tuple[int, int]]) -> set:
    out = set()
    for a, b in edges:
        ia, ib = int(a), int(b)
        if ia == ib:
            continue
        out.add((min(ia, ib), max(ia, ib)))
    return out


def _candidate_logits_from_source(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    source_idx: int,
    keep_idx: Optional[np.ndarray],
    n_verts: int,
) -> np.ndarray:
    if source_idx < 0 or source_idx >= len(runs):
        return np.zeros((n_verts,), dtype=np.float64)
    lg = np.asarray(runs[source_idx][2], dtype=np.float64).reshape(-1)
    if keep_idx is not None and lg.size > 0:
        ki = np.asarray(keep_idx, dtype=np.int64).reshape(-1)
        valid = (ki >= 0) & (ki < lg.size)
        if valid.all() and ki.size == n_verts:
            return lg[ki]
    if lg.size == n_verts:
        return lg
    if lg.size == 0:
        return np.zeros((n_verts,), dtype=np.float64)
    return np.full((n_verts,), float(np.nanmean(lg)), dtype=np.float64)


def _candidate_support_features(
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    match_tau_m: float,
) -> Tuple[float, float, float, float, float]:
    """Agreement features for one candidate against the ensemble members."""
    from scipy.optimize import linear_sum_assignment

    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    Nv = v.shape[0]
    if Nv == 0 or not runs:
        return 0.0, 0.0, 0.0, 0.0, 0.0

    v_support = np.zeros((Nv,), dtype=np.float64)
    e_keys = _edge_key_set(edges)
    e_votes: Dict[Tuple[int, int], int] = {k: 0 for k in e_keys}

    for rv_raw, re_raw, _rlg in runs:
        rv = np.asarray(rv_raw, dtype=np.float64).reshape(-1, 3)
        if rv.shape[0] == 0:
            continue
        D = np.linalg.norm(v[:, None, :] - rv[None, :, :], axis=-1)
        D_capped = np.minimum(D, match_tau_m)
        row_ind, col_ind = linear_sum_assignment(D_capped)
        r_to_c = -np.ones(rv.shape[0], dtype=np.int64)
        for r, c in zip(row_ind, col_ind):
            if D[r, c] <= match_tau_m:
                v_support[r] += 1.0
                r_to_c[c] = r
        if e_keys:
            seen = set()
            for a, b in re_raw:
                ia, ib = int(a), int(b)
                if (ia == ib or ia < 0 or ib < 0
                        or ia >= r_to_c.size or ib >= r_to_c.size):
                    continue
                ca, cb = int(r_to_c[ia]), int(r_to_c[ib])
                if ca < 0 or cb < 0 or ca == cb:
                    continue
                key = (min(ca, cb), max(ca, cb))
                if key in e_votes:
                    seen.add(key)
            for key in seen:
                e_votes[key] += 1

    denom = float(max(1, len(runs)))
    v_frac = v_support / denom
    if e_votes:
        e_frac = np.asarray(list(e_votes.values()), dtype=np.float64) / denom
        e_mean = float(e_frac.mean())
        e_max = float(e_frac.max())
    else:
        e_mean = 0.0
        e_max = 0.0
    return (
        float(v_frac.mean()),
        float(v_frac.std()),
        float(v_frac.min()),
        e_mean,
        e_max,
    )


def _candidate_feature_vector(
    name: str,
    verts: np.ndarray,
    edges: List[Tuple[int, int]],
    logits: np.ndarray,
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    match_tau_m: float,
    source_idx: int,
    medoid_idx: int,
    confidence_idx: int,
    ranking: List[int],
    is_raw_member: bool,
    is_refined: bool,
    uses_edge_vote: bool,
    uses_add_edges: bool,
    uses_topk: bool,
    reproj_views: Optional[List[Dict[str, Any]]] = None,
    s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]] = None,
) -> np.ndarray:
    v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
    e = list(edges)
    lg = np.asarray(logits, dtype=np.float64).reshape(-1)
    lg = lg[np.isfinite(lg)]
    if lg.size == 0:
        lg = np.zeros((1,), dtype=np.float64)

    n_v = float(v.shape[0])
    n_e = float(len(e))
    max_edges = max(1.0, n_v * max(0.0, n_v - 1.0) / 2.0)
    v_sup_mean, v_sup_std, v_sup_min, e_sup_mean, e_sup_max = (
        _candidate_support_features(v, e, runs, match_tau_m)
    )

    dists = []
    for rv, re, _rl in runs:
        try:
            dists.append(_wireframe_pair_distance(
                v, e, np.asarray(rv, dtype=np.float64), list(re),
                match_tau_m=match_tau_m,
            ))
        except Exception:
            continue
    d_arr = np.asarray([d for d in dists if np.isfinite(d)], dtype=np.float64)
    if d_arr.size == 0:
        centrality_mean = 10.0
        centrality_min = 10.0
    else:
        centrality_mean = float(d_arr.mean())
        centrality_min = float(d_arr.min())

    rank_pos = float(len(ranking))
    if source_idx in ranking:
        rank_pos = float(ranking.index(source_idx))

    if reproj_views:
        vr_mean, vr_min, er_mean, er_min = _reprojection_features(
            v, e, reproj_views,
        )
    else:
        vr_mean = vr_min = er_mean = er_min = 0.0
    deg1_frac, edge_len_cv = _structural_features(v, e)
    coplanarity = _coplanarity_score(v, e)
    junction_dev = _junction_angle_dev(v, e)
    manhattan_frac, princ_axis_align = _principal_axis_features(v, e)

    _, _, s1_disp_far = _stage1_displacement_features(v, s1_runs)
    _, _, deg_ent = _connectivity_features(v, e)
    sym_res = _symmetry_residual(v, e)

    feats = np.asarray([
        n_v / 64.0,
        n_e / 128.0,
        n_e / max_edges,
        float(lg.mean()),
        float(lg.std()),
        float(lg.min()),
        float(lg.max()),
        v_sup_mean,
        v_sup_std,
        v_sup_min,
        e_sup_mean,
        e_sup_max,
        centrality_mean,
        centrality_min,
        rank_pos / float(max(1, len(ranking))),
        1.0 if is_raw_member else 0.0,
        1.0 if source_idx == medoid_idx else 0.0,
        1.0 if source_idx == confidence_idx else 0.0,
        1.0 if is_refined else 0.0,
        1.0 if uses_edge_vote else 0.0,
        1.0 if uses_add_edges else 0.0,
        1.0 if uses_topk else 0.0,
        float(source_idx) / float(max(1, len(runs) - 1)),
        vr_mean,
        vr_min,
        er_mean,
        er_min,
        deg1_frac,
        edge_len_cv,
        coplanarity,
        junction_dev,
        manhattan_frac,
        princ_axis_align,
        # --- v5 features ---
        s1_disp_far,
        deg_ent,
        sym_res,
    ], dtype=np.float64)
    if feats.shape[0] != len(_RANKER_FEATURE_NAMES):
        raise RuntimeError(f"ranker feature mismatch for {name}")
    return feats


def _ensemble_heuristic_score(features: np.ndarray) -> float:
    f = {k: float(v) for k, v in zip(_RANKER_FEATURE_NAMES, features)}
    return (
        1.20 * f["vertex_support_mean"]
        + 0.55 * f["edge_support_mean"]
        + 0.08 * f["logit_mean"]
        - 0.30 * f["centrality_mean"]
        - 0.08 * abs(f["n_v"] - 0.33)
        - 0.04 * abs(f["n_e"] - 0.18)
        + 0.04 * f["is_refined"]
        + 0.02 * f["is_medoid_source"]
        - 0.03 * f["uses_edge_vote"]
    )


def _score_ranker_candidate(
    features: np.ndarray,
    ranker: Optional[Dict[str, np.ndarray]],
) -> float:
    if ranker is None:
        return _ensemble_heuristic_score(features)
    mean = np.asarray(ranker["mean"], dtype=np.float64)
    scale = np.asarray(ranker["scale"], dtype=np.float64)
    weights = np.asarray(ranker["weights"], dtype=np.float64)
    x = (features - mean) / np.maximum(scale, 1e-8)
    return float(np.dot(x, weights[1:]) + weights[0])


def _fuse_topk_candidates(
    candidates: List[Dict[str, Any]],
    scores: np.ndarray,
    k: int,
    match_tau_m: float,
    edge_vote_frac: float,
) -> Tuple[np.ndarray, List[Tuple[int, int]], int]:
    """Fuse the top-K ranker-scored candidates into one wireframe.

    Strategy mirrors ``medoid_mean_add`` but applies it to the top-K
    *ranker-quality-filtered* candidates rather than all ensemble members:

      1. Sort candidates by ``scores`` descending; keep ``top_k = min(k, len)``.
      2. Pivot = top-1 candidate. For each pivot vertex, Hungarian-match to
         each of the other top-K candidates' vertices (cap Ï„ = ``match_tau_m``)
         and average the positions of matched correspondents.
      3. Union pivot's edges with edges voted by at least
         ``edge_vote_frac`` of the top-K (counted on matched vertex pairs).

    Returns ``(verts, edges, best_idx)`` where ``best_idx`` is the position
    of the top-1 candidate in the input list (for diagnostics).
    """
    scores_arr = np.asarray(scores, dtype=np.float64).reshape(-1)
    n = scores_arr.size
    if n == 0:
        return np.zeros((0, 3), dtype=np.float64), [], 0
    k_eff = max(1, min(int(k), n))
    order = np.argsort(-scores_arr)[:k_eff].astype(np.int64)
    best_idx = int(order[0])
    if k_eff == 1:
        c = candidates[best_idx]
        return (np.asarray(c["verts"], dtype=np.float64),
                list(c["edges"]), best_idx)

    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]] = []
    for j in order:
        c = candidates[int(j)]
        v = np.asarray(c["verts"], dtype=np.float64).reshape(-1, 3)
        e = list(c["edges"])
        lg_src = c.get("logits", None)
        lg = (np.asarray(lg_src, dtype=np.float64).reshape(-1)
              if lg_src is not None and len(np.asarray(lg_src).ravel()) == v.shape[0]
              else np.zeros((v.shape[0],), dtype=np.float64))
        runs.append((v, e, lg))

    refined_v, refined_e, keep_idx = _refine_positions(
        runs, picked_idx=0, match_tau_m=match_tau_m,
        aggregator="mean", member_indices=None, vertex_vote_frac=0.0,
    )
    voted = _vote_edges(
        runs, picked_idx=0, match_tau_m=match_tau_m,
        vote_frac=edge_vote_frac, member_indices=None,
        keep_idx=keep_idx,
    )
    edge_set = set()
    for (a, b) in refined_e:
        ia, ib = int(a), int(b)
        if ia == ib: continue
        edge_set.add((min(ia, ib), max(ia, ib)))
    for (a, b) in voted:
        ia, ib = int(a), int(b)
        if ia == ib: continue
        edge_set.add((min(ia, ib), max(ia, ib)))
    return refined_v, sorted(edge_set), best_idx


def _load_ensemble_ranker(path: Optional[str]) -> Optional[Dict[str, np.ndarray]]:
    if not path:
        return None
    p = Path(path)
    if not p.exists():
        print(f"[ranker] {p} not found; using built-in heuristic scorer", flush=True)
        return None
    data = np.load(p, allow_pickle=False)
    names = [str(x) for x in data["feature_names"].tolist()]
    if names != _RANKER_FEATURE_NAMES:
        print(
            f"[ranker] feature-name mismatch in {p} "
            f"(have {len(names)}-d, expected {len(_RANKER_FEATURE_NAMES)}-d); "
            f"falling back to built-in heuristic scorer", flush=True)
        return None
    ranker = {
        "mean": np.asarray(data["mean"], dtype=np.float64),
        "scale": np.asarray(data["scale"], dtype=np.float64),
        "weights": np.asarray(data["weights"], dtype=np.float64),
    }
    print(f"[ranker] loaded {p}", flush=True)
    return ranker


def _build_ranker_candidates(
    runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    match_tau_m: float,
    edge_vote_frac: float,
    ranking: Optional[List[int]] = None,
    medoid_idx: Optional[int] = None,
    confidence_idx: Optional[int] = None,
    reproj_views: Optional[List[Dict[str, Any]]] = None,
    s1_runs: Optional[List[Tuple[np.ndarray, Any, Any]]] = None,
) -> List[Dict[str, Any]]:
    """Produce candidate wireframes for learned/heuristic ensemble selection."""
    if not runs:
        return []
    if ranking is None:
        ranking = _medoid_rank(runs, match_tau_m=match_tau_m)
    medoid_idx = int(medoid_idx if medoid_idx is not None
                     else (ranking[0] if ranking else 0))
    confidence_idx = int(confidence_idx if confidence_idx is not None
                         else _confidence_select_idx(runs))

    candidates: List[Dict[str, Any]] = []

    def add_candidate(
        name: str,
        verts: np.ndarray,
        edges: List[Tuple[int, int]],
        source_idx: int,
        keep_idx: Optional[np.ndarray],
        is_raw_member: bool,
        is_refined: bool,
        uses_edge_vote: bool,
        uses_add_edges: bool,
        uses_topk: bool,
    ) -> None:
        v = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
        e = [(int(a), int(b)) for a, b in edges if int(a) != int(b)]
        if v.shape[0] == 0 or len(e) == 0:
            return
        logits = _candidate_logits_from_source(runs, source_idx, keep_idx, v.shape[0])
        features = _candidate_feature_vector(
            name=name, verts=v, edges=e, logits=logits, runs=runs,
            match_tau_m=match_tau_m, source_idx=source_idx,
            medoid_idx=medoid_idx, confidence_idx=confidence_idx,
            ranking=ranking, is_raw_member=is_raw_member,
            is_refined=is_refined, uses_edge_vote=uses_edge_vote,
            uses_add_edges=uses_add_edges, uses_topk=uses_topk,
            reproj_views=reproj_views,
            s1_runs=s1_runs,
        )
        candidates.append({
            "name": name,
            "verts": v,
            "edges": e,
            "logits": logits,
            "features": features,
            "source_idx": int(source_idx),
        })

    for i, (v, e, _lg) in enumerate(runs):
        add_candidate(
            name=f"member_{i:02d}", verts=v, edges=list(e), source_idx=i,
            keep_idx=None, is_raw_member=True, is_refined=False,
            uses_edge_vote=False, uses_add_edges=False, uses_topk=False,
        )

    def refined_candidates(source_idx: int, label: str, member_indices: Optional[List[int]]) -> None:
        uses_topk = member_indices is not None
        rv, re, keep_idx = _refine_positions(
            runs, source_idx, match_tau_m=match_tau_m,
            aggregator="mean", member_indices=member_indices,
            vertex_vote_frac=0.0,
        )
        add_candidate(
            name=f"{label}_mean_picked" + ("_topk" if uses_topk else ""),
            verts=rv, edges=re, source_idx=source_idx, keep_idx=keep_idx,
            is_raw_member=False, is_refined=True,
            uses_edge_vote=False, uses_add_edges=False, uses_topk=uses_topk,
        )
        voted = _vote_edges(
            runs, source_idx, match_tau_m=match_tau_m,
            vote_frac=edge_vote_frac, member_indices=member_indices,
            keep_idx=keep_idx,
        )
        add_candidate(
            name=f"{label}_mean_voted" + ("_topk" if uses_topk else ""),
            verts=rv, edges=voted, source_idx=source_idx, keep_idx=keep_idx,
            is_raw_member=False, is_refined=True,
            uses_edge_vote=True, uses_add_edges=False, uses_topk=uses_topk,
        )
        add_edges = sorted(_edge_key_set(re) | _edge_key_set(voted))
        add_candidate(
            name=f"{label}_mean_add" + ("_topk" if uses_topk else ""),
            verts=rv, edges=add_edges, source_idx=source_idx, keep_idx=keep_idx,
            is_raw_member=False, is_refined=True,
            uses_edge_vote=True, uses_add_edges=True, uses_topk=uses_topk,
        )

    refined_candidates(medoid_idx, "medoid", None)
    if confidence_idx != medoid_idx:
        refined_candidates(confidence_idx, "confidence", None)

    for k in (5, 8):
        if ranking and len(ranking) >= k:
            members = list(ranking[:k])
            if medoid_idx not in members:
                members.append(medoid_idx)
            refined_candidates(medoid_idx, f"medoid_top{k}", members)

    return candidates


def train_ensemble_ranker_jsonl(jsonl_path: str, out_path: str, l2: float = 1e-2) -> None:
    """Fit a tiny ridge ranker from within-sample candidate comparisons.

    Absolute HSS is dominated by sample difficulty ("easy building" vs.
    "hard building"), but inference only needs to choose among candidates for
    the same sample. Training on pairwise feature differences cancels that
    nuisance and directly optimizes the ordering we care about.
    """
    rows_by_sample: Dict[str, List[Tuple[np.ndarray, float]]] = {}
    with open(jsonl_path, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            row = json.loads(line)
            feats = np.asarray(row.get("features", []), dtype=np.float64)
            if feats.shape[0] != len(_RANKER_FEATURE_NAMES):
                continue
            y = float(row.get("hss", 0.0))
            if not np.isfinite(y) or not np.all(np.isfinite(feats)):
                continue
            sid = str(row.get("order_id", row.get("sample_index", "")))
            rows_by_sample.setdefault(sid, []).append((feats, y))

    xs = [feat for rows in rows_by_sample.values() for feat, _y in rows]
    if len(xs) < 10 or len(rows_by_sample) < 2:
        raise SystemExit(
            f"[ranker/train] need >=10 rows and >=2 samples, got "
            f"{len(xs)} rows / {len(rows_by_sample)} samples")

    X = np.stack(xs, axis=0)
    mean = X.mean(axis=0)
    scale = X.std(axis=0)
    scale[scale < 1e-8] = 1.0

    pair_x: List[np.ndarray] = []
    pair_y: List[float] = []
    for rows in rows_by_sample.values():
        if len(rows) < 2:
            continue
        feats = [(feat - mean) / scale for feat, _y in rows]
        ys = [float(y) for _feat, y in rows]
        for i in range(len(rows)):
            for j in range(i + 1, len(rows)):
                dy = ys[i] - ys[j]
                if abs(dy) < 1e-9:
                    continue
                pair_x.append(feats[i] - feats[j])
                pair_y.append(dy)
    if len(pair_x) < 10:
        raise SystemExit(f"[ranker/train] need >=10 informative pairs, got {len(pair_x)}")

    DX = np.stack(pair_x, axis=0)
    dy = np.asarray(pair_y, dtype=np.float64)
    reg = np.eye(DX.shape[1], dtype=np.float64) * float(l2)
    w = np.linalg.solve(DX.T @ DX + reg, DX.T @ dy)
    weights = np.concatenate([[0.0], w], axis=0)
    pred = DX @ w
    mse = float(np.mean((pred - dy) ** 2))
    corr = float(np.corrcoef(pred, dy)[0, 1]) if pred.std() > 0 and dy.std() > 0 else 0.0

    # Grouped oracle estimate: how good would this ranker be on the same dump?
    # This is optimistic when train==eval, but useful as a smoke test.
    picked = []
    oracle = []
    for rows in rows_by_sample.values():
        scored = []
        for feat, y in rows:
            x = np.concatenate([[1.0], (feat - mean) / scale])
            scored.append((float(np.dot(x, weights)), float(y)))
        picked.append(max(scored, key=lambda t: t[0])[1])
        oracle.append(max(scored, key=lambda t: t[1])[1])

    np.savez(
        out_path,
        feature_names=np.asarray(_RANKER_FEATURE_NAMES, dtype="<U64"),
        mean=mean,
        scale=scale,
        weights=weights,
    )
    print(f"[ranker/train] rows={len(xs)} samples={len(rows_by_sample)} "
          f"pairs={len(pair_x)} pair_mse={mse:.6f} pair_corr={corr:.4f}",
          flush=True)
    if picked:
        print(f"[ranker/train] train-picked mean={float(np.mean(picked)):.4f}  "
              f"candidate-oracle mean={float(np.mean(oracle)):.4f}", flush=True)
    print(f"[ranker/train] wrote {out_path}", flush=True)


def _build_stage2_sample(
    raw_sample: Dict[str, Any],
    colmap_rec,
    pred_verts: np.ndarray,
    pred_edges: np.ndarray,
    stage2_cfg: Stage2Config,
    preprocess_cache: Optional[Dict[str, Any]],
    order_id: str,
    timings: Optional[Dict[str, float]],
) -> Optional[Dict[str, Any]]:
    """Host: stage-2 scene around one set of stage-1 vertices/edges (``build_stage2_scene`` +
    ``stage2_row_to_sample``). Returns the model-ready sample (host tensors, ``init_verts`` (K, 3)
    from ``pred_verts``) or None when the hull is invalid."""
    if stage2_cfg.sampling == "fps":
        raise NotImplementedError("stage-2 'fps' sampling is not supported by the inference path")
    t0 = time.perf_counter()
    s2_row = build_stage2_scene(
        raw_sample=raw_sample,
        colmap_rec=colmap_rec,
        pred_verts=pred_verts,
        pred_edges=pred_edges,
        above_m=stage2_cfg.above_m,
        below_m=stage2_cfg.below_m,
        side_m=stage2_cfg.side_m,
        n_col_oversample=stage2_cfg.n_col_oversample,
        n_dep_oversample=stage2_cfg.n_dep_oversample,
        n_depth_per_image_cap=stage2_cfg.n_depth_per_image_cap,
        sampling_mode=("voxel" if stage2_cfg.sampling == "voxel" else "random"),
        density_voxel_size_m=stage2_cfg.density_voxel_size_m,
        density_kernel_radius=stage2_cfg.density_kernel_radius,
        density_kernel_axis=stage2_cfg.density_kernel_axis,
        density_response_power=stage2_cfg.density_response_power,
        density_planarity_suppression=stage2_cfg.density_planarity_suppression,
        density_planarity_radius=stage2_cfg.density_planarity_radius,
        density_planarity_min_points=stage2_cfg.density_planarity_min_points,
        density_min_per_voxel=stage2_cfg.density_min_per_voxel,
        rng=np.random.default_rng(_seed_from_order_id(order_id)),
        cache=preprocess_cache,
    )
    if timings is not None:
        timings["s2_build"] = timings.setdefault("s2_build", 0.0) + time.perf_counter() - t0
    if not s2_row["hull_valid"]:
        return None
    t0 = time.perf_counter()
    s2_sample = stage2_row_to_sample(
        s2_row,
        n_pts=stage2_cfg.n_pts,
        k_verts=stage2_cfg.k_verts,
        augment=False,
        flip=False, yaw=False, jitter_sigma=0.0,
        pre_subsample=True,
    )
    if timings is not None:
        timings["s2_transform"] = timings.setdefault("s2_transform", 0.0) + time.perf_counter() - t0
    return s2_sample


def build_stage2_union_sample(
    raw_sample: Dict[str, Any],
    colmap_rec,
    s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
    stage2_cfg: Stage2Config,
    preprocess_cache: Optional[Dict[str, Any]],
    timings: Optional[Dict[str, float]] = None,
) -> Optional[Dict[str, Any]]:
    """Host only (safe in a CPU worker): the union-hull stage-2 input of one sample.

    ONE stage-2 scene (hull, point cloud, bbox) is built from the union of the N = len(s1_runs)
    stage-1 members' vertices and edges; ``init_verts`` (N, K, 3) / ``init_verts_valid`` (N, K) hold
    each member's vertices normalised into that shared bbox, so every member starts its stage-2
    trajectory from its own stage-1 hypothesis. Returns the sample (host tensors, the input of
    ``stage2_predict_batch``) or None when all members are empty or the hull is invalid."""
    order_id = str(raw_sample["order_id"])
    parts = [(np.asarray(v, dtype=np.float32).reshape(-1, 3), np.asarray(e, dtype=np.int64).reshape(-1, 2))
             for v, e, _l in s1_runs if len(v) > 0]
    if not parts:
        return None
    offsets = np.cumsum([0] + [len(v) for v, _e in parts[:-1]])
    union_verts = np.concatenate([v for v, _e in parts])
    union_edges = np.concatenate([e + o for (_v, e), o in zip(parts, offsets)])
    s2_sample = _build_stage2_sample(raw_sample, colmap_rec, union_verts, union_edges, stage2_cfg,
                                     preprocess_cache, order_id, timings)
    if s2_sample is None:
        return None
    K, N = stage2_cfg.k_verts, len(s1_runs)
    center = s2_sample["bbox_center"].numpy().astype(np.float32)
    scale = max(float(s2_sample["bbox_scale"]), 1e-6)
    init = np.zeros((N, K, 3), dtype=np.float32)
    valid = np.zeros((N, K), dtype=bool)
    for i, (v, _e, _l) in enumerate(s1_runs):
        if len(v) > 0:
            norm = ((np.asarray(v, dtype=np.float32).reshape(-1, 3) - center) / scale).astype(np.float32)
            init[i], valid[i] = _pad_init_verts(norm, K)
    s2_sample["init_verts"] = torch.from_numpy(init)
    s2_sample["init_verts_valid"] = torch.from_numpy(valid)
    return s2_sample


def build_stage2_seed_sample(
    raw_sample: Dict[str, Any],
    colmap_rec,
    pred_verts: np.ndarray,
    pred_edges: np.ndarray,
    stage2_cfg: Stage2Config,
    preprocess_cache: Optional[Dict[str, Any]],
    timings: Optional[Dict[str, float]] = None,
) -> Optional[Dict[str, Any]]:
    """Host only: per-seed stage-2 input around ONE stage-1 member (M = 1: ``init_verts`` (1, K, 3)).
    None when its hull is invalid."""
    s2_sample = _build_stage2_sample(raw_sample, colmap_rec, pred_verts, pred_edges, stage2_cfg,
                                     preprocess_cache, str(raw_sample["order_id"]), timings)
    if s2_sample is not None:
        s2_sample["init_verts"] = s2_sample["init_verts"][None]
        s2_sample["init_verts_valid"] = s2_sample["init_verts_valid"][None]
    return s2_sample


@torch.inference_mode()
def stage2_predict_batch(
    stage2_cfg: Stage2Config,
    samples: Sequence[Dict[str, Any]],
    order_ids: Sequence[str],
    enc_idx: Sequence[int],
    device: torch.device,
    timings: Optional[Dict[str, float]] = None,
) -> List[List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]]]:
    """Stage 2 on the GPU for S built samples at once (one scene encode each, all members integrated
    together). ``samples``: S outputs of ``build_stage2_union_sample`` / ``build_stage2_seed_sample``
    (host tensors; equal point counts and equal member counts M = init_verts.shape[0]);
    ``order_ids`` / ``enc_idx``: per sample its order_id and the index n of this stage-2 encode within
    the sample (0 for the union hull; enc_base + member index on the per-seed path). Sample s reseeds
    the torch RNG with _torch_seed(order_ids[s], cfg.seed, "s2", enc_idx[s]) before its x0 draws.
    Returns S lists of M host tuples (verts_world (m, 3) float32, edges [(i, j)] with i < j,
    valid_logits (m,) float32), WITHOUT the stage-1 fallback (see ``merge_stage_members``).
    ``timings`` (optional) accumulates CUDA-synchronised seconds under s2_enc / s2_den / s2_post."""
    M = samples[0]["init_verts"].shape[0]
    if any(s["init_verts"].shape[0] != M for s in samples):
        raise ValueError("stage2_predict_batch needs the same member count in every sample")
    model = stage2_cfg.model
    if stage2_cfg.compile and model.denoiser._compiled is None:
        model.denoiser.compile_step()
    with _phase(timings, "s2_enc", device):
        batch = _stage2_samples_to_batch(samples, device)
        feats, sxyz = model.encode(batch, stage2_cfg.encoder_bf16)
    with _phase(timings, "s2_den", device):
        x0 = _init_members(model, batch, M, order_ids, stage2_cfg.seed, "s2", enc_idx)
        x, logit, edge = model.integrate(feats, sxyz, x0, stage2_cfg.n_sample_steps,
                                         stage2_cfg.ensemble_stage2_last_k, stage2_cfg.denoiser_bf16,
                                         stage2_cfg.cuda_graph)
    with _phase(timings, "s2_post", device):
        out = _decode_members(x, logit, edge,
                              [(s["bbox_center"].numpy(), float(s["bbox_scale"]), s["bbox_R"].numpy())
                               for s in samples], M, stage2_cfg.validity_thresh, None)
    return [[(v, [(int(a), int(b)) for a, b in e], l) for v, e, l in members] for members in out]


def merge_stage_members(
    s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
    s2_runs: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
) -> List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]]:
    """Member i keeps its stage-2 result when that has vertices and edges, else its stage-1
    prediction when that has both, else it is dropped. Returns the ensemble ``seed_results``
    [(verts (m, 3) float64, edges [(i, j)], valid_logits (m,) float32)] for ``select_ensemble``."""
    out = []
    for (v1, e1, l1), (v2, e2, l2) in zip(s1_runs, s2_runs, strict=True):
        if len(v2) > 0 and len(e2) > 0:
            out.append((np.asarray(v2, dtype=float), list(e2), np.asarray(l2, dtype=np.float32)))
            continue
        e1 = [(int(a), int(b)) for a, b in np.asarray(e1).tolist()]
        if len(v1) > 0 and len(e1) > 0:
            out.append((np.asarray(v1, dtype=float), e1, np.asarray(l1, dtype=np.float32)))
    return out


_NO_MEMBER = (np.zeros((0, 3), dtype=np.float32), [], np.zeros(0, dtype=np.float32))


def select_ensemble(
    seed_results: List[Tuple[np.ndarray, List[Tuple[int, int]], np.ndarray]],
    s1_runs: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
    n_hull_valid: int,
    stage2_cfg: Stage2Config,
    raw_sample: Dict[str, Any],
    colmap_rec,
    stats: Optional[Dict[str, int]] = None,
    diagnostics: Optional[Dict[str, Any]] = None,
) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
    """Host only (safe in a CPU worker): fuse / select the final wireframe of one sample from its
    ensemble ``seed_results`` (``merge_stage_members`` output, see ``_Worker``). Reads only
    the ensemble_* fields of ``stage2_cfg`` (never ``stage2_cfg.model``); ``raw_sample`` /
    ``colmap_rec`` are used by the ranker selector only. Returns (verts (V, 3) float64, edges)."""
    n_ensemble = stage2_cfg.ensemble_n
    if not seed_results:
        if stats is not None:
            stats["empty_fallback"] = stats.get("empty_fallback", 0) + 1
        if diagnostics is not None:
            diagnostics["members"] = []
            diagnostics["final"] = empty_solution()
        ev, ee = empty_solution()
        return np.asarray(ev, dtype=float), [(int(a), int(b)) for a, b in ee]

    if diagnostics is not None:
        diagnostics["members"] = [
            (np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
            for v, e, l in seed_results
        ]
        diagnostics["s1_runs"] = [
            (np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
            for v, e, l in s1_runs
        ]
        diagnostics["n_hull_valid"] = int(n_hull_valid)

    # When n_ensemble=1 the single run is returned verbatim.
    if n_ensemble == 1:
        fused_v, fused_e = seed_results[0][0], seed_results[0][1]
        if diagnostics is not None:
            diagnostics["single"] = (np.asarray(fused_v, dtype=float), list(fused_e))
    else:
        selector = stage2_cfg.ensemble_selector
        mode = stage2_cfg.ensemble_mode
        tau = stage2_cfg.ensemble_merge_m
        refine = stage2_cfg.ensemble_refine_positions
        top_k = stage2_cfg.ensemble_top_k
        edge_vote = stage2_cfg.ensemble_edge_vote
        edge_vote_frac = stage2_cfg.ensemble_edge_vote_frac
        vertex_vote_frac = stage2_cfg.ensemble_vertex_vote_frac
        agg = stage2_cfg.ensemble_refine_agg
        ranking: Optional[List[int]] = None
        if mode == "medoid" or top_k > 0 or selector == "ranker":
            ranking = _medoid_rank(seed_results, match_tau_m=tau)
        medoid_pick = (ranking[0] if ranking else
                       _medoid_select_idx(seed_results, match_tau_m=tau))
        conf_pick = _confidence_select_idx(seed_results)

        if diagnostics is not None:
            diagnostics["single"] = (
                np.asarray(seed_results[0][0], dtype=float),
                list(seed_results[0][1]),
            )
            diagnostics["medoid_pick"] = (
                np.asarray(seed_results[medoid_pick][0], dtype=float),
                list(seed_results[medoid_pick][1]),
            )
            diagnostics["confidence_pick"] = (
                np.asarray(seed_results[conf_pick][0], dtype=float),
                list(seed_results[conf_pick][1]),
            )
            diagnostics["medoid_idx"] = int(medoid_pick)
            diagnostics["confidence_idx"] = int(conf_pick)

        if selector in ("ranker", "fixed"):
            reproj_views_cached = _build_reprojection_views(
                raw_sample, colmap_rec,
            ) if selector == "ranker" else None
            candidates = _build_ranker_candidates(
                seed_results, match_tau_m=tau, edge_vote_frac=edge_vote_frac,
                ranking=ranking, medoid_idx=medoid_pick,
                confidence_idx=conf_pick,
                reproj_views=reproj_views_cached,
                s1_runs=s1_runs,
            )
            if candidates:
                if selector == "fixed":
                    wanted = str(stage2_cfg.ensemble_fixed_candidate)
                    fallback = "medoid_mean_add"
                    scores = [
                        (2.0 if c["name"] == wanted else
                         1.0 if c["name"] == fallback else 0.0)
                        for c in candidates
                    ]
                else:
                    ranker = stage2_cfg.ensemble_ranker
                    scores = [
                        _score_ranker_candidate(c["features"], ranker)
                        for c in candidates
                    ]
                scores_arr = np.asarray(scores, dtype=np.float64)
                best_c = int(np.argmax(scores_arr))
                chosen = candidates[best_c]
                topk_k = stage2_cfg.ensemble_topk_fuse
                if (selector == "ranker" and topk_k > 1
                        and len(candidates) > 1):
                    fused_v, fused_e, _ = _fuse_topk_candidates(
                        candidates, scores_arr, topk_k,
                        match_tau_m=tau, edge_vote_frac=edge_vote_frac,
                    )
                else:
                    fused_v = np.asarray(chosen["verts"], dtype=np.float64)
                    fused_e = list(chosen["edges"])
                if diagnostics is not None:
                    diagnostics["candidates"] = [
                        {
                            "name": str(c["name"]),
                            "features": np.asarray(c["features"], dtype=np.float64),
                            "score": float(scores[j]),
                            "verts": np.asarray(c["verts"], dtype=float),
                            "edges": list(c["edges"]),
                        }
                        for j, c in enumerate(candidates)
                    ]
                    diagnostics["selected_candidate"] = str(chosen["name"])
                    diagnostics["selected_candidate_score"] = float(scores[best_c])
                    diagnostics["pick_idx"] = int(chosen.get("source_idx", -1))
                    diagnostics["topk_fuse_k"] = int(topk_k)
            else:
                fused_v = np.asarray(seed_results[medoid_pick][0], dtype=np.float64)
                fused_e = list(seed_results[medoid_pick][1])
                if diagnostics is not None:
                    diagnostics["pick_idx"] = int(medoid_pick)
        elif mode == "consensus":
            # Consensus already aggregates across runs — refinement is
            # logically subsumed. Vertex / edge vote fractions come straight
            # from the same flags (vertex frac defaults to 0.5 here since
            # consensus needs *some* support bar, not 0).
            v_frac_consensus = vertex_vote_frac if vertex_vote_frac > 0.0 else 0.5
            e_frac_consensus = edge_vote_frac if edge_vote else 0.5
            fused_v, fused_e = _fuse_wireframes(
                list(seed_results),
                n_total=n_ensemble, merge_tau_m=tau,
                vertex_vote_frac=v_frac_consensus,
                edge_vote_frac=e_frac_consensus,
                aggregator=agg,
            )
        else:
            if mode == "confidence":
                pick = conf_pick
            else:  # "medoid"
                pick = medoid_pick

            if diagnostics is not None:
                diagnostics["pick_idx"] = int(pick)

            if top_k > 0 and ranking:
                members: Optional[List[int]] = list(ranking[:max(1, top_k)])
                if pick not in members:
                    members.append(pick)
            else:
                members = None  # use all runs

            keep_idx: Optional[np.ndarray] = None
            if refine:
                fused_v, fused_e, keep_idx = _refine_positions(
                    seed_results, pick, match_tau_m=tau,
                    aggregator=agg, member_indices=members,
                    vertex_vote_frac=vertex_vote_frac,
                )
            else:
                fused_v = np.asarray(seed_results[pick][0], dtype=np.float64).reshape(-1, 3)
                fused_e = list(seed_results[pick][1])
                keep_idx = np.arange(fused_v.shape[0], dtype=np.int64)

            if edge_vote:
                fused_e = _vote_edges(
                    seed_results, pick, match_tau_m=tau,
                    vote_frac=edge_vote_frac,
                    member_indices=members,
                    keep_idx=keep_idx,
                )

    if stats is not None:
        if n_hull_valid == 0:
            stats["stage1_fallback"] = stats.get("stage1_fallback", 0) + 1
        else:
            stats["stage2_used"] = stats.get("stage2_used", 0) + 1

    if len(fused_v) == 0 or len(fused_e) == 0:
        if stats is not None:
            stats["empty_fallback"] = stats.get("empty_fallback", 0) + 1
        if diagnostics is not None:
            diagnostics["final"] = empty_solution()
        ev, ee = empty_solution()
        return np.asarray(ev, dtype=float), [(int(a), int(b)) for a, b in ee]
    if diagnostics is not None:
        diagnostics["final"] = (np.asarray(fused_v, dtype=float), list(fused_e))
    return np.asarray(fused_v, dtype=float), fused_e


# ---------------------------------------------------------------------------
# Data sources: the test-server tars, read directly (--loader tar) or through
# the HF loader script (--loader hf)
# ---------------------------------------------------------------------------

def resolve_data_dir(data_dir: str, params: Dict[str, Any]) -> Path:
    """The test-server data dir; downloaded with snapshot_download(params['dataset']) when missing."""
    path = Path(data_dir)
    if path.exists():
        print(f"[data] test environment detected ({path} exists)", flush=True)
    else:
        print(f"[data] local run — snapshot_download '{params['dataset']}' → {path}", flush=True)
        from huggingface_hub import snapshot_download
        snapshot_download(repo_id=params["dataset"], local_dir=str(path), repo_type="dataset")
    return path


def split_tars(data_path: Path) -> Dict[str, List[str]]:
    """Split -> tars as the released script hands them to the loader script (validation =
    *public*/**/*.tar, test = *private*/**/*.tar, rglob order); splits without tars are left out."""
    files = {"validation": [str(p) for p in data_path.rglob("*public*/**/*.tar")],
             "test": [str(p) for p in data_path.rglob("*private*/**/*.tar")]}
    print(f"[data] resolved data_files: { {k: len(v) for k, v in files.items()} } shards", flush=True)
    return {k: v for k, v in files.items() if v}


def tar_items(files: Dict[str, List[str]], limit: int) -> List[Tuple[str, tuple]]:
    """[(order_id, worker reference)] of every sample in the loader script's order (splits, their tars,
    tar order), at most ``limit`` (> 0) per split; built from the tar headers only (``index_tar``). Members
    the loader script does not read are skipped as it skips them; one line reports them."""
    items: List[Tuple[str, tuple]] = []
    skipped: Counter = Counter()
    for paths in files.values():
        rows = []
        for p in paths:
            samples, skip = index_tar(p)
            skipped += skip
            rows += [(key.replace("order_", ""), ("tar", p, key, members)) for key, members in samples]
        items += rows[:limit] if limit > 0 else rows
    if skipped:
        print(f"[data] skipped tar members the loader script does not read (suffix: count): {dict(skipped)}",
              flush=True)
    return items


def hf_items(data_path: Path, files: Dict[str, List[str]], limit: int):
    """--loader hf: the released ``load_dataset`` call on the loader script. Returns the items (worker
    references (split, row)) and the split datasets, which the workers read rows from undecoded."""
    if load_dataset is None:
        raise SystemExit("[data] --loader hf needs the Python package 'datasets'")
    dataset = load_dataset(str(data_path / "hoho22k_2026_test_x_anon.py"), data_files=files,
                           trust_remote_code=True, writer_batch_size=100)
    print(dataset, flush=True)
    items: List[Tuple[str, tuple]] = []
    splits = {}
    for name in dataset:
        ds = dataset[name]
        splits[name] = ds.select(range(min(limit, len(ds)))) if limit > 0 else ds
        items += [(str(o), ("hf", name, i)) for i, o in enumerate(splits[name]["order_id"])]
    return items, splits


def sanity_items(args) -> List[Tuple[str, tuple]]:
    """--sanity: the first --sanity_n samples of --sanity_split (all with --sanity_n 0) as tar items, from
      - --sanity_data_dir: all *.tar below it;
      - else, with --sanity_n 0: the split's shards of --sanity_dataset, downloaded into --sanity_cache_dir;
      - else: those full shards when a --sanity_n 0 run downloaded them, otherwise streamed prefixes of the
        shards (``_streamed_prefix_tars``): only the first --sanity_n samples are fetched.
    Shards are taken in sorted order, as the HF loader script lists them, so every route picks the same
    samples in the same order."""
    split = args.sanity_split
    local = Path(args.sanity_cache_dir) / args.sanity_dataset.replace("/", "--")
    full, done = local / "data" / split, local / "data" / split / ".complete"
    if args.sanity_data_dir:
        tars = sorted(str(p) for p in Path(args.sanity_data_dir).rglob("*.tar"))
    elif args.sanity_n <= 0:
        from huggingface_hub import snapshot_download
        print(f"[sanity] downloading {args.sanity_dataset} data/{split}/*.tar → {local}", flush=True)
        snapshot_download(repo_id=args.sanity_dataset, repo_type="dataset",
                          allow_patterns=[f"data/{split}/*.tar"], local_dir=str(local))
        done.write_text("")  # the full split is here (a later --sanity_n > 0 run uses it)
        tars = sorted(str(p) for p in full.glob("*.tar"))
    elif done.exists():
        tars = sorted(str(p) for p in full.glob("*.tar"))
    else:
        tars = _streamed_prefix_tars(args.sanity_dataset, split, args.sanity_n, local / "stream" / split)
    if not tars:
        raise SystemExit(f"[sanity] no tars for split {split!r}")
    print(f"[sanity] {len(tars)} tars: {tars}", flush=True)
    return tar_items({split: tars}, args.sanity_n)


def _streamed_prefix_tars(repo: str, split: str, n: int, cache: Path) -> List[str]:
    """Local tars that hold the first ``n`` samples of the split. Per shard (sorted names; the list is
    cached in ``shards.json``) a cached ``<shard>.first<k>.tar`` with k >= the samples still needed, or a
    cached ``<shard>.all<k>.tar`` (the whole shard), is used; otherwise the shard is read from the Hub as one
    sequential stream until enough samples are complete (``stream_tar_prefix``: a byte-identical prefix of
    the shard). Files are written under a temporary name and renamed when complete. Hub errors (gated
    dataset, missing login) are raised as huggingface_hub raises them."""
    from huggingface_hub import HfFileSystem
    cache.mkdir(parents=True, exist_ok=True)
    listing = cache / "shards.json"
    if not listing.exists():
        names = sorted(p.rsplit("/", 1)[1] for p in HfFileSystem().ls(f"datasets/{repo}/data/{split}", detail=False)
                       if p.endswith(".tar"))
        (cache / ".shards.json.partial").write_text(json.dumps(names))
        (cache / ".shards.json.partial").rename(listing)
    tars, need = [], n
    for name in json.loads(listing.read_text()):
        if need <= 0:
            break
        cached = []  # (samples, whole shard, path) of <name>.first<k>.tar / <name>.all<k>.tar
        for p in cache.glob(f"{name}.*.tar"):
            tag = p.name[len(name) + 1:-len(".tar")]
            kind = tag.rstrip("0123456789")
            if kind in ("first", "all") and tag != kind:
                cached.append((int(tag[len(kind):]), kind == "all", p))
        cached.sort()
        hit = next(((k, p) for k, whole, p in cached if whole or k >= need), None)
        if hit is None:
            tmp = cache / f".{name}.partial"
            t0 = time.perf_counter()
            with HfFileSystem().open(f"datasets/{repo}/data/{split}/{name}", "rb", block_size=0) as src, \
                    open(tmp, "w+b") as dst:
                k, whole, n_read = stream_tar_prefix(src, dst, need)
            path = cache / f"{name}.{'all' if whole else 'first'}{k}.tar"
            tmp.rename(path)
            print(f"[sanity] streamed {repo} data/{split}/{name}: "
                  f"{'whole shard,' if whole else 'first'} {k} samples, {n_read / 1e6:.1f} MB read in "
                  f"{time.perf_counter() - t0:.1f} s → {path}", flush=True)
            hit = (k, path)
        tars.append(str(hit[1]))
        need -= hit[0]
    return tars


# ---------------------------------------------------------------------------
# Pipeline: CPU worker processes + one GPU loop in the main process
# ---------------------------------------------------------------------------

_THREAD_ENV = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS")
_S2_KEYS = _SCENE_KEYS + ("init_verts", "init_verts_valid", "bbox_center", "bbox_scale", "bbox_R")


def _host_s2(sample: Dict[str, Any]) -> Dict[str, np.ndarray]:
    """A built stage-2 input as plain arrays for the queue (torch CPU tensors would be moved to shared memory)."""
    return {k: sample[k].numpy() for k in _S2_KEYS}


def _torch_s2(arrays: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]:
    return {k: torch.from_numpy(v) for k, v in arrays.items()}


def _warmup_colmap(order: str) -> None:
    """The first read_colmap_zip of a process pays pyarrow's compute warm-up (and, for "pycolmap", the
    libstdc++ lookup); do it on a one-point reconstruction."""
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as zf:
        zf.writestr("cameras.txt", "1 SIMPLE_PINHOLE 4 4 1 2 2\n")
        zf.writestr("images.txt", "1 1 0 0 0 0 0 0 1 a.png\n\n")
        zf.writestr("points3D.txt", "1 0 0 0 0 0 0 0.5 1 0\n")
    read_colmap_zip(buf.getvalue(), order)


def _sanity_score(sample, colmap_rec, verts, edges, diag, cfg, dump: bool, idx: int) -> Dict[str, Any]:
    """--sanity, in the worker that owns the sample: HSS / F1 / IoU of the final wireframe against the GT
    (hoho2025.metric_helper.hss, failures scored 0 as before), plus the ensemble diagnostics (``diag`` from
    select_ensemble) and the ranker-candidate JSONL rows (``dump``)."""
    from hoho2025.metric_helper import hss as hss_fn, HSSReturnType
    gt_v, gt_e = np.asarray(sample["wf_vertices"]), np.asarray(sample["wf_edges"])
    out: Dict[str, Any] = {"gt_nv": len(gt_v), "gt_ne": len(gt_e), "notes": [], "diag_line": "", "cand_rows": [],
                           "diag_hss": defaultdict(list), "diag_counts": defaultdict(list)}

    def variant(name: str, vv, ee) -> float:
        try:
            val = float(hss_fn(np.asarray(vv, dtype=float), list(ee), gt_v, gt_e).hss)
        except Exception:
            val = 0.0
        out["diag_hss"][name].append(val)
        out["diag_counts"][f"{name}_v"].append(len(vv))
        out["diag_counts"][f"{name}_e"].append(len(ee))
        return val

    if diag:
        scored = {name: variant(name, *diag[name]) for name in ("single", "medoid_pick", "confidence_pick", "final")
                  if name in diag}
        member_scores = [variant("member", vv, ee) for vv, ee, _ll in diag["members"]]
        if member_scores:
            oracle = max(member_scores)
            out["diag_hss"]["oracle"].append(oracle)
            best, final_h = int(np.argmax(member_scores)), scored["final"]
            out["diag_line"] = (f"  | diag single={scored.get('single', 0.0):.3f} "
                                f"medoid={scored.get('medoid_pick', 0.0):.3f} "
                                f"conf={scored.get('confidence_pick', 0.0):.3f} final={final_h:.3f} "
                                f"oracle={oracle:.3f}@{best} gap={oracle - final_h:+.3f}")
        if dump and diag["members"]:
            candidates = diag.get("candidates")
            if not candidates:
                candidates = _build_ranker_candidates(
                    [(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32)) for v, e, l in diag["members"]],
                    match_tau_m=cfg.ensemble_merge_m, edge_vote_frac=cfg.ensemble_edge_vote_frac,
                    medoid_idx=diag.get("medoid_idx"), confidence_idx=diag.get("confidence_idx"),
                    reproj_views=_build_reprojection_views(sample, colmap_rec),
                    s1_runs=[(np.asarray(v, dtype=float), list(e), np.asarray(l, dtype=np.float32))
                             for v, e, l in diag["s1_runs"]])
            selected = str(diag.get("selected_candidate", ""))
            for cand in candidates:
                cv, ce = np.asarray(cand["verts"], dtype=float), list(cand["edges"])
                try:
                    cr = hss_fn(cv, ce, gt_v, gt_e)
                    chss, cf1, ciou = float(cr.hss), float(cr.f1), float(cr.iou)
                except Exception:
                    chss, cf1, ciou = 0.0, 0.0, 0.0
                out["cand_rows"].append({
                    "order_id": sample["order_id"], "sample_index": int(idx), "name": str(cand["name"]),
                    "selected": str(cand["name"]) == selected, "hss": chss, "f1": cf1, "iou": ciou,
                    "n_v": int(len(cv)), "n_e": int(len(ce)),
                    "features": np.asarray(cand["features"], dtype=np.float64).tolist()})
    try:
        r = hss_fn(np.asarray(verts, dtype=float), list(edges), gt_v, gt_e)
    except Exception as exc:
        out["notes"].append(f"HSS FAILED ({type(exc).__name__}: {exc})")
        r = HSSReturnType(hss=0.0, f1=0.0, iou=0.0)
    out.update(hss=float(r.hss), f1=float(r.f1), iou=float(r.iou),
               diag_hss=dict(out["diag_hss"]), diag_counts=dict(out["diag_counts"]))
    return out


class _Worker:
    """The CPU side of every sample, in a worker process (see run_pipeline). Messages (name, idx, ...):
    "pre" read + decode + stage-1 preprocess; "s2" stage-2 input build (union hull, else per seed);
    "union" / "seed" merge with the stage-2 GPU result (per-seed fallback when the union hull yields no
    member) and ensemble selection. Raw sample, COLMAP record and stage-1 cache stay here between the
    steps; only scenes, stage-2 inputs and member wireframes cross the queues."""

    def __init__(self, wid: int, out: "_Outbox", o: Dict[str, Any]):
        self.wid, self.out, self.o, self.cfg = wid, out, o, o["cfg"]
        self.hf = {k: ds.with_format("arrow") for k, ds in o["hf_splits"].items()}
        self.st: Dict[int, Dict[str, Any]] = {}
        _warmup_colmap(o["colmap_order"])

    def handle(self, m) -> None:
        try:
            getattr(self, m[0])(*m[1:])
        except Exception as exc:  # per-sample CPU failure: the main process gives the sample the empty solution
            s = self.st.pop(m[1], None)
            extra = None
            if self.o["sanity"] and s is not None:
                ev, ee = empty_solution()
                extra = _sanity_score(s["sample"], None, ev, ee, None, self.cfg, False, m[1])
            self.out.put(("failed", m[1], m[0], f"{type(exc).__name__}: {exc}", traceback.format_exc(),
                            None if s is None else s["t"], extra))

    def pre(self, idx: int, ref: tuple) -> None:
        t0 = time.perf_counter()
        if ref[0] == "tar":
            files = read_tar_members(ref[1], ref[3])
            t1 = time.perf_counter()
            sample = decode_tar_sample(ref[2], files)
        else:
            row = self.hf[ref[1]][ref[2]].to_pylist()[0]
            t1 = time.perf_counter()
            sample = hf_row_images(row)
        t2 = time.perf_counter()
        s = self.st[idx] = {"sample": sample, "t": {"read": t1 - t0, "decode": t2 - t1, "s2_build": 0.0}}
        pre = preprocess_sample(sample, self.o["n_pts"], self.o["use_depth"], 0.1, True,
                                colmap_order=self.o["colmap_order"])
        s.update(rec=pre["colmap_rec"], cache=pre["cache"])
        s["t"]["pre"] = time.perf_counter() - t2
        self.out.put(("s1", idx, self.wid, pre["scene"]))

    def s2(self, idx: int, s1_runs) -> None:
        s = self.st[idx]
        s["s1"] = s1_runs
        t0 = time.perf_counter()
        built = None
        if self.cfg.ensemble_strategy == "union_hull" and self.cfg.ensemble_n > 1:
            built = build_stage2_union_sample(s["sample"], s["rec"], s1_runs, self.cfg, s["cache"])
        if built is None:  # per-seed strategy, ensemble_n == 1, or no valid union hull
            return self._per_seed(idx, 0, t0)
        s["t"]["s2_build"] += time.perf_counter() - t0
        self.out.put(("s2u", idx, _host_s2(built)))

    def _per_seed(self, idx: int, enc_base: int, t0: float) -> None:
        """Released per-seed stage 2: one hull per stage-1 member; members with a valid hull go to the GPU
        (stage-2 encode index enc_base + member), the others keep their stage-1 prediction."""
        s = self.st[idx]
        built = [build_stage2_seed_sample(s["sample"], s["rec"], v, e, self.cfg, s["cache"]) for v, e, _l in s["s1"]]
        items = [(j, _host_s2(b)) for j, b in enumerate(built) if b is not None]
        s["t"]["s2_build"] += time.perf_counter() - t0
        if items:
            self.out.put(("s2s", idx, enc_base, items))
        else:
            self.seed(idx, enc_base, {})

    def union(self, idx: int, s2_runs) -> None:
        t0 = time.perf_counter()
        seed_results = merge_stage_members(self.st[idx]["s1"], s2_runs)
        if seed_results:
            self._finish(idx, seed_results, self.cfg.ensemble_n, t0)
        else:  # no usable union-hull member: released per-seed fallback
            self._per_seed(idx, 1, t0)

    def seed(self, idx: int, enc_base: int, runs: Dict[int, tuple]) -> None:
        t0 = time.perf_counter()
        s1 = self.st[idx]["s1"]
        seed_results = merge_stage_members(s1, [runs[j] if j in runs else _NO_MEMBER for j in range(len(s1))])
        self._finish(idx, seed_results, (self.cfg.ensemble_n if enc_base else 0) + len(runs), t0)

    def _finish(self, idx: int, seed_results, n_hull_valid: int, t0: float) -> None:
        s = self.st.pop(idx)
        stats: Dict[str, int] = {}
        diag = {} if self.o["diagnostics"] else None
        verts, edges = select_ensemble(seed_results, s["s1"], n_hull_valid, self.cfg, s["sample"], s["rec"],
                                       stats, diag)
        edges = [(int(a), int(b)) for a, b in edges]
        s["t"]["select"] = time.perf_counter() - t0
        extra: Dict[str, Any] = {"stats": stats}
        if self.o["sanity"]:
            extra.update(_sanity_score(s["sample"], s["rec"], verts, edges, diag, self.cfg, self.o["dump"], idx))
        self.out.put(("done", idx, np.asarray(verts, dtype=float).tolist(), edges, s["t"], extra))


class _Outbox:
    """Worker -> main messages, sent in order by a thread over this worker's own pipe: the worker does not
    wait while the GPU loop is busy, and as only this process holds the write end, a worker that dies in
    the middle of a message gives the main process EOF instead of a read that never completes."""

    def __init__(self, conn):
        self.q: queue.SimpleQueue = queue.SimpleQueue()
        self.thread = threading.Thread(target=self._send_all, args=(conn,), daemon=True)
        self.thread.start()

    def _send_all(self, conn) -> None:
        try:
            for m in iter(self.q.get, None):
                conn.send(m)
        except BaseException:  # a lost message would stall the run: die, the main process reports the dead worker
            traceback.print_exc()
            os._exit(1)

    def put(self, m) -> None:
        self.q.put(m)

    def close(self) -> None:
        self.q.put(None)
        self.thread.join()


def _worker_main(wid: int, conn, out_conn) -> None:
    """Worker process: one "init" message, then sample messages until "stop"; stage-2 and selection
    messages are served before queued preprocessing (they unblock the GPU loop)."""
    signal.signal(signal.SIGINT, signal.SIG_IGN)  # Ctrl-C reaches the whole process group; the main process stops us
    torch.set_num_threads(1)
    out = _Outbox(out_conn)
    m = conn.recv()
    if m[0] != "init":
        raise RuntimeError(f"worker {wid}: expected 'init', got {m[0]!r}")
    w = _Worker(wid, out, m[1])
    hi: deque = deque()
    lo: deque = deque()
    busy = 0.0
    while True:
        if not hi and not lo:
            m = conn.recv()
            (lo if m[0] == "pre" else hi).append(m)
        while conn.poll():
            m = conn.recv()
            (lo if m[0] == "pre" else hi).append(m)
        m = hi.popleft() if hi else lo.popleft()
        if m[0] == "stop":
            out.put(("exit", wid, resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, busy))
            out.close()
            return
        t = time.perf_counter()
        w.handle(m)
        busy += time.perf_counter() - t


def start_workers(n: int):
    """n worker processes (spawn start method: safe with CUDA initialised in this process), each limited to
    one OpenMP / BLAS thread. Returns [(process, input pipe, output pipe)], one pipe pair per worker.
    The input pipes are written by the GPU loop's thread itself (an mp.Queue would add a feeder thread per
    worker to this process, competing with the GPU loop for the GIL); their buffers are raised to 1 MB so
    a send does not wait for a busy worker. This process closes its copies of the pipe ends the worker uses,
    so a dead worker shows up as a broken pipe / EOF."""
    ctx = mp.get_context("spawn")
    saved = {k: os.environ.get(k) for k in _THREAD_ENV}
    os.environ.update(dict.fromkeys(_THREAD_ENV, "1"))
    try:
        workers = []
        for w in range(n):
            rx, tx = ctx.Pipe(duplex=False)
            out_rx, out_tx = ctx.Pipe(duplex=False)
            fcntl.fcntl(tx.fileno(), fcntl.F_SETPIPE_SZ, 1 << 20)
            p = ctx.Process(target=_worker_main, args=(w, rx, out_tx), name=f"s23dr-worker-{w}", daemon=True)
            p.start()
            rx.close()
            out_tx.close()
            workers.append((p, tx, out_rx))
    finally:
        for k, v in saved.items():
            if v is None:
                del os.environ[k]
            else:
                os.environ[k] = v
    return workers


def check_workers(workers) -> None:
    """Raise if any worker process has exited."""
    dead = [(w, p.exitcode) for w, (p, _tx, _rx) in enumerate(workers) if p.exitcode is not None]
    if dead:
        raise RuntimeError(f"pipeline worker(s) died (worker, exit code; -9 = SIGKILL, e.g. the OOM killer): "
                           f"{dead}; see the worker traceback above, if any")


def kill_workers(workers) -> None:
    """Error-path shutdown: SIGKILL (SIGTERM would make every worker print a native stack dump)."""
    for p, _tx, _rx in workers:  # kill before closing the pipes: a live worker would report the closed pipe
        if p.is_alive():
            p.kill()
    for p, tx, rx in workers:
        tx.close()
        rx.close()
        p.join(timeout=30)


def run_pipeline(workers, items, model, cfg: Stage2Config, device: torch.device, n_steps: int,
                 validity_thresh: float, args, report) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
    """All ``items`` (order_id, worker reference) through the workers and one GPU loop (this thread);
    returns (predictions in item order, timing summary). Stops the workers at the end.

    Per sample: worker "pre" -> GPU stage 1 -> worker "s2" -> GPU stage 2 (union hull: one item with
    ensemble_n members; per seed: one item per member with a valid hull) -> worker merge + selection.
    Seeding is per sample (order_id, --seed, stage), so outputs do not depend on batching or timing.
    GPU batches hold S = --batch_samples samples (per-seed: S items); stage 2 runs before stage 1. A
    batch of fewer than S runs only when no further input for that stage can arrive (--partial_batch
    wait) or whenever the GPU would otherwise idle (pad). On CUDA it is padded to S by repeating its last
    entry (results dropped), so every stage keeps one batch shape (one CUDA graph; bf16 results depend on
    the shape, so an unpadded last batch would make them depend on arrival timing). At most
    3*S + 2*n_workers samples are in flight (>= 3S - 2 makes a stall of the three GPU queues impossible),
    each worker with at most 2 queued preprocessing tasks. ``report(i, order_id, verts, edges, times,
    extra)`` runs once per finished sample (extra: worker extras, None if the sample failed unread)."""
    pc = time.perf_counter
    S, W, n = args.batch_samples, len(workers), len(items)
    pad = device.type == "cuda"
    readers = {rx: w for w, (_p, _tx, rx) in enumerate(workers)}
    cap = 3 * S + 2 * W
    oids = [o for o, _r in items]
    ready: Dict[str, deque] = {"s1": deque(), "s2u": deque(), "s2s": deque()}
    where: Dict[int, str] = {}  # in-flight sample -> pre / s1 / build / s2u / s2s / post
    count: Counter = Counter()
    owner: Dict[int, int] = {}
    npre = [0] * W
    seeds: Dict[int, list] = {}  # per-seed sample -> [enc_base, items left, {member: run}]
    rec = [{"s1_gpu": 0.0, "s2_gpu": 0.0, "wait_s1": 0.0, "wait_s2": 0.0} for _ in range(n)]
    results: List[Optional[Dict[str, Any]]] = [None] * n
    wall: Counter = Counter()
    batches: Counter = Counter()
    padded: Counter = Counter()
    stats: Counter = Counter()
    failed: List[str] = []
    nxt = n_done = 0
    t_first = None
    t_done: List[float] = []
    bar = tqdm(total=n, desc="predict", unit="sample")

    def send(w, m):
        try:
            workers[w][1].send(m)
        except (BrokenPipeError, ConnectionResetError):  # the worker is gone: say so
            workers[w][0].join(timeout=5)
            check_workers(workers)
            raise

    def recv(timeout: float) -> list:
        """The next message of every worker pipe readable within ``timeout`` (0: poll)."""
        msgs = []
        for rx in mp.connection.wait(list(readers), timeout):
            try:
                msgs.append(rx.recv())
            except (EOFError, OSError):  # a worker exited (possibly mid-message)
                workers[readers[rx]][0].join(timeout=5)
                check_workers(workers)
                raise
        return msgs

    def stage(i, s):
        if i in where:
            count[where[i]] -= 1
        where[i] = s
        count[s] += 1

    def admit():
        nonlocal nxt
        while nxt < n and len(where) < cap:
            w = min(range(W), key=npre.__getitem__)
            if npre[w] >= 2:
                return
            i, nxt = nxt, nxt + 1
            owner[i] = w
            npre[w] += 1
            stage(i, "pre")
            rec[i]["t_admit"] = pc()
            send(w, ("pre", i, items[i][1]))

    def finish(i, verts, edges, times, extra):
        nonlocal n_done, t_first
        count[where.pop(i)] -= 1
        n_done += 1
        t = pc()
        t_first = t if t_first is None else t_first
        t_done.append(t)
        if times is not None:
            rec[i].update(times)
        rec[i]["latency"] = t - rec[i]["t_admit"]
        rec[i]["done_s"] = t - t0
        results[i] = {"order_id": oids[i], "wf_vertices": verts, "wf_edges": edges}
        bar.update(1)
        report(i, oids[i], verts, edges, rec[i], extra)

    def on(m):
        kind, i = m[0], m[1]
        if kind == "s1":
            npre[m[2]] -= 1
            stage(i, "s1")
            rec[i]["t_ready"] = pc()
            ready["s1"].append((i, m[3]))
        elif kind == "s2u":
            stage(i, "s2u")
            rec[i]["t_ready"] = pc()
            ready["s2u"].append((i, _torch_s2(m[2])))
        elif kind == "s2s":
            stage(i, "s2s")
            rec[i]["t_ready"] = pc()
            seeds[i] = [m[2], len(m[3]), {}]
            ready["s2s"].extend((i, j, m[2], _torch_s2(x)) for j, x in m[3])
        elif kind == "done":
            stats.update(m[5]["stats"])
            finish(i, m[2], m[3], m[4], m[5])
        elif kind == "failed":
            if m[2] == "pre":
                npre[owner[i]] -= 1
            print(f"[predict] {oids[i]}: FAILED in '{m[2]}' ({m[3]}) — empty_solution\n{m[4]}", flush=True)
            failed.append(oids[i])
            ev, ee = empty_solution()
            finish(i, np.asarray(ev, dtype=float).tolist(), [(int(a), int(b)) for a, b in ee], m[5], m[6])
        else:
            raise RuntimeError(f"unexpected worker message {kind!r}")

    def runnable() -> Optional[str]:
        more_s1 = nxt < n or count["pre"] > 0
        more = {"s1": more_s1, "s2u": more_s1 or count["s1"] + count["build"] > 0}
        more["s2s"] = more["s2u"] or count["s2u"] + count["post"] > 0
        for s in ("s2u", "s2s", "s1"):
            if len(ready[s]) >= S or (ready[s] and not more[s]):
                return s
        if args.partial_batch == "pad":
            return next((s for s in ("s2u", "s2s", "s1") if ready[s]), None)
        return None

    def run(s):
        q = ready[s]
        take = [q.popleft() for _ in range(min(S, len(q)))]
        full = take + [take[-1]] * (S - len(take)) if pad else take
        batches[s] += 1
        padded[s] += len(full) - len(take)
        ids = [oids[x[0]] for x in full]
        t0 = pc()
        if s == "s1":
            out = stage1_predict_batch(model, [x[1] for x in full], ids, cfg, n_steps, validity_thresh, device)
        elif s == "s2u":
            out = stage2_predict_batch(cfg, [x[1] for x in full], ids, [0] * len(full), device)
        else:
            out = stage2_predict_batch(cfg, [x[3] for x in full], ids, [x[2] + x[1] for x in full], device)
        dt = pc() - t0
        wall["gpu_" + s] += dt
        for x, r in zip(take, out):
            i = x[0]
            rec[i]["s1_gpu" if s == "s1" else "s2_gpu"] += dt / len(take)
            if s == "s1":
                rec[i]["wait_s1"] = t0 - rec[i]["t_ready"]
                stage(i, "build")
                send(owner[i], ("s2", i, r))
            elif s == "s2u":
                rec[i]["wait_s2"] += t0 - rec[i]["t_ready"]
                stage(i, "post")
                send(owner[i], ("union", i, r))
            else:
                sd = seeds[i]
                sd[2][x[1]] = r[0]
                sd[1] -= 1
                if sd[1] == 0:
                    del seeds[i]
                    rec[i]["wait_s2"] += t0 - rec[i]["t_ready"]
                    stage(i, "post")
                    send(owner[i], ("seed", i, sd[0], sd[2]))

    t0, t0_wall = pc(), time.time()
    last_msg = next_check = t0
    while n_done < n:
        if pc() >= next_check:
            check_workers(workers)
            next_check = pc() + 2.0
        admit()
        while msgs := recv(0):
            for m in msgs:
                on(m)
            last_msg = pc()
        s = runnable()
        if s is not None:
            run(s)
            continue
        tb = pc()
        msgs = recv(1.0)  # nothing to run: the GPU waits for the workers
        wall["blocked"] += pc() - tb
        for m in msgs:
            on(m)
        if msgs:
            last_msg = pc()
        elif pc() - last_msg > args.stall_timeout:
            raise RuntimeError(f"pipeline stalled: no worker message for {args.stall_timeout:.0f} s with samples in "
                               f"flight {dict(count)}")
    t1, t1_wall = pc(), time.time()
    bar.close()

    for w in range(W):
        send(w, ("stop",))
    exits: Dict[int, tuple] = {}
    t_stop = pc()
    while readers:
        msgs = recv(1.0)
        for m in msgs:
            if m[0] != "exit":
                raise RuntimeError(f"unexpected worker message after the last sample: {m[0]!r}")
            exits[m[1]] = m[2:]
            readers.pop(workers[m[1]][2])
        if not msgs and pc() - t_stop > 60:
            raise RuntimeError(f"workers {sorted(set(range(W)) - set(exits))} did not stop")
    for p, _tx, _rx in workers:
        p.join(timeout=60)

    loop = t1 - t0
    gpu = sum(v for k, v in wall.items() if k.startswith("gpu_"))
    keys = ("read", "decode", "pre", "s2_build", "select", "s1_gpu", "s2_gpu", "wait_s1", "wait_s2", "latency")
    summary = {
        "n": n, "n_failed": len(failed), "failed": failed, "n_workers": W, "batch_samples": S,
        "partial_batch": args.partial_batch, "padded_batches": pad, "max_in_flight": cap,
        "t_loop": loop, "t_loop0": t0, "t_first_result": t_first, "loop_wall": (t0_wall, t1_wall),
        "samples_per_s": n / loop,
        # completions between 25 % and 75 % of the samples: no start-up (graph captures, JIT) and no drain
        "samples_per_s_steady": (3 * n // 4 - n // 4) / (t_done[3 * n // 4] - t_done[n // 4]) if n >= 40 else None,
        "per_sample_ms": {k: 1e3 * float(np.mean([r[k] for r in rec if k in r])) for k in keys},
        "gpu_busy_frac": gpu / loop, "blocked_frac": wall["blocked"] / loop,
        "main_overhead_frac": 1.0 - (gpu + wall["blocked"]) / loop,
        "worker_busy_frac": sum(e[1] for e in exits.values()) / (W * loop),
        "gpu_wall_s": {k: v for k, v in wall.items() if k.startswith("gpu_")},
        "batches": dict(batches), "padded_slots": dict(padded), "selection_stats": dict(stats),
        "peak_rss_main_mb": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024,
        "peak_rss_workers_mb": [exits[w][0] / 1024 for w in range(W)],
        "per_sample": [{"order_id": oids[i], **{k: v for k, v in rec[i].items() if not k.startswith("t_")}}
                       for i in range(n)],
    }
    if device.type == "cuda":
        summary["gpu_mem_peak_mb"] = {"allocated": torch.cuda.max_memory_allocated(device) / 2 ** 20,
                                      "reserved": torch.cuda.max_memory_reserved(device) / 2 ** 20}
    print_pipeline_summary(summary)
    return results, summary


def print_pipeline_summary(s: Dict[str, Any]) -> None:
    """Per-phase means and the loop split; what bounds the run."""
    p = s["per_sample_ms"]
    bound = ("CPU workers (more cores / --n_workers)" if s["worker_busy_frac"] > 0.85 else
             "GPU" if s["gpu_busy_frac"] > 0.85 else
             "main-process Python" if s["main_overhead_frac"] > 0.15 else
             "neither saturated (batch latency)")
    w_rss = s["peak_rss_workers_mb"]
    steady = "" if s["samples_per_s_steady"] is None else f", middle half {s['samples_per_s_steady']:.2f}"
    print(f"[pipeline] {s['n']} samples in {s['t_loop']:.1f} s = {s['samples_per_s']:.2f} samples/s{steady}  "
          f"(FAILED {s['n_failed']}; {s['n_workers']} workers, S={s['batch_samples']}, {s['partial_batch']})", flush=True)
    print(f"[pipeline] per sample [ms], workers: read {p['read']:.1f}  decode {p['decode']:.1f}  "
          f"stage-1 preprocess {p['pre']:.1f}  stage-2 build {p['s2_build']:.1f}  selection {p['select']:.1f}", flush=True)
    print(f"[pipeline] per sample [ms], GPU loop: stage-1 GPU {p['s1_gpu']:.1f}  stage-2 GPU {p['s2_gpu']:.1f}  "
          f"queue wait s1 {p['wait_s1']:.0f}  s2 {p['wait_s2']:.0f}  latency {p['latency']:.0f}", flush=True)
    print(f"[pipeline] loop: GPU calls {100 * s['gpu_busy_frac']:.0f}%  waiting for workers (GPU idle) "
          f"{100 * s['blocked_frac']:.0f}%  main-thread overhead {100 * s['main_overhead_frac']:.0f}%  |  workers busy "
          f"{100 * s['worker_busy_frac']:.0f}%  |  batches {s['batches']} padded slots {s['padded_slots']}", flush=True)
    print(f"[pipeline] peak RSS main {s['peak_rss_main_mb']:.0f} MB, workers {sum(w_rss):.0f} MB "
          f"(max {max(w_rss):.0f})" + (f", GPU peak allocated {s['gpu_mem_peak_mb']['allocated']:.0f} MB reserved "
                                       f"{s['gpu_mem_peak_mb']['reserved']:.0f} MB" if "gpu_mem_peak_mb" in s else "")
          + f"  |  selection {s['selection_stats']}  |  bound by: {bound}", flush=True)


def _print_prediction(i, order_id, verts, edges, times, extra) -> None:
    print(f"[predict/stage2] {order_id}: {len(verts)}v {len(edges)}e  (latency {times['latency']:.2f}s)", flush=True)


# ---------------------------------------------------------------------------
# Local sanity check (--sanity): val split, scored against GT
# ---------------------------------------------------------------------------

def run_sanity_check(workers, items, model, stage2_cfg: Stage2Config, device: torch.device,
                     n_steps: int, validity_thresh: float, args) -> Dict[str, Any]:
    """The inference pipeline on --sanity_split samples with GT; the workers score each prediction
    (hoho2025.metric_helper.hss) and, with --sanity_ensemble_diagnostics / --ensemble_candidate_dump,
    the ensemble alternatives. Prints per-sample and mean HSS / F1 / IoU; returns the pipeline summary
    with the means."""
    print(f"[sanity] dataset={args.sanity_data_dir or args.sanity_dataset}  split={args.sanity_split}  "
          f"n={len(items)}  n_sample_steps={n_steps}  validity_thresh={validity_thresh}", flush=True)
    print(f"[sanity] STAGE 2 enabled  n_pts={stage2_cfg.n_pts}  n_sample_steps={stage2_cfg.n_sample_steps}  "
          f"hull=(+{stage2_cfg.above_m:.2f}/-{stage2_cfg.below_m:.2f}/±{stage2_cfg.side_m:.2f})", flush=True)
    diagnostics = args.sanity_ensemble_diagnostics or args.ensemble_candidate_dump is not None
    if diagnostics and stage2_cfg.ensemble_n > 1:
        print("[diag] enabled: scoring single/member0, medoid pick, confidence pick, final fused, and oracle-best "
              "member", flush=True)
    scores: Dict[str, List[float]] = {"hss": [], "f1": [], "iou": []}
    diag_hss: Dict[str, List[float]] = defaultdict(list)
    diag_counts: Dict[str, List[int]] = defaultdict(list)
    cand_rows: Dict[int, List[dict]] = {}

    def report(i, order_id, verts, edges, times, extra):
        if extra is None:  # failed before its GT was read
            extra = {"hss": 0.0, "f1": 0.0, "iou": 0.0, "gt_nv": -1, "gt_ne": -1, "notes": ["no GT read"],
                     "diag_line": "", "cand_rows": [], "diag_hss": {}, "diag_counts": {}}
        for note in extra["notes"]:
            print(f"[sanity] {order_id}: {note}", flush=True)
        for k in scores:
            scores[k].append(extra[k])
        for k, v in extra["diag_hss"].items():
            diag_hss[k].extend(v)
        for k, v in extra["diag_counts"].items():
            diag_counts[k].extend(v)
        cand_rows[i] = extra["cand_rows"]
        g = lambda k: times[k] if k in times else float("nan")
        print(f"[sanity] [{i:03d}] {order_id}  pred={len(verts)}v/{len(edges)}e  gt={extra['gt_nv']}v/{extra['gt_ne']}e  "
              f"HSS={extra['hss']:.3f}  F1={extra['f1']:.3f}  IoU={extra['iou']:.3f}  | pre={g('pre'):.2f}s  "
              f"s1={g('s1_gpu'):.3f}s  s2build={g('s2_build'):.3f}s  s2={g('s2_gpu'):.3f}s  sel={g('select'):.3f}s  "
              f"latency={times['latency']:.2f}s{extra['diag_line']}", flush=True)

    _results, summary = run_pipeline(workers, items, model, stage2_cfg, device, n_steps, validity_thresh,
                                     args, report)

    def mean_std(xs):
        arr = np.asarray(xs, dtype=np.float64)
        return (float(arr.mean()), float(arr.std())) if arr.size else (0.0, 0.0)
    print("=" * 60, flush=True)
    print(f"[sanity] samples={len(scores['hss'])}", flush=True)
    for k, name in (("hss", "HSS "), ("f1", "F1  "), ("iou", "IoU ")):
        m, sd = mean_std(scores[k])
        summary[f"sanity_{k}"] = m
        print(f"[sanity] {name} mean={m:.4f}  std={sd:.4f}", flush=True)
    if diag_hss:
        print("[diag] HSS means:", flush=True)
        for name in ("single", "member", "medoid_pick", "confidence_pick", "final", "oracle"):
            if name in diag_hss:
                m, sd = mean_std(diag_hss[name])
                print(f"[diag] {name:15s} mean={m:.4f}  std={sd:.4f}", flush=True)
        if "oracle" in diag_hss and "final" in diag_hss:
            gap = np.asarray(diag_hss["oracle"]) - np.asarray(diag_hss["final"])
            print(f"[diag] oracle-final   mean={float(gap.mean()):+.4f}  std={float(gap.std()):.4f}", flush=True)
        for name in ("single", "medoid_pick", "confidence_pick", "final"):
            if f"{name}_v" in diag_counts:
                v_m, v_s = mean_std(diag_counts[f"{name}_v"])
                e_m, e_s = mean_std(diag_counts[f"{name}_e"])
                print(f"[diag] {name:15s} size={v_m:.1f}±{v_s:.1f}v/{e_m:.1f}±{e_s:.1f}e", flush=True)
    st = summary["selection_stats"]
    print(f"[sanity] stage-2 used={st.get('stage2_used', 0)}  stage-1 fallback={st.get('stage1_fallback', 0)}  "
          f"empty fallback={st.get('empty_fallback', 0)}", flush=True)
    if args.ensemble_candidate_dump is not None:
        with open(args.ensemble_candidate_dump, "w") as f:
            for i in sorted(cand_rows):
                for row in cand_rows[i]:
                    f.write(json.dumps(row, separators=(",", ":")) + "\n")
        print(f"[ranker/dump] wrote {sum(map(len, cand_rows.values()))} candidate rows to "
              f"{args.ensemble_candidate_dump}", flush=True)
    print("=" * 60, flush=True)
    return summary


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def _build_stage2_cfg(args, params: Dict[str, Any], device: torch.device) -> Stage2Config:
    """Resolve --stage2_ckpt / env / params, load the Stage2Diffusion model,
    and assemble a ``Stage2Config``. The two-stage pipeline is mandatory;
    ``resolve_stage2_ckpt_path`` raises if no ckpt is configured."""
    ckpt_path = resolve_stage2_ckpt_path(args.stage2_ckpt, params)
    model, s2_args = load_stage2_model(ckpt_path, device)
    n_pts = (args.stage2_n_pts if args.stage2_n_pts is not None
             else s2_args.get("n_pts", 16384))
    k_verts = s2_args.get("k_verts", 64)
    n_sample_steps = (args.stage2_n_sample_steps if args.stage2_n_sample_steps is not None
                      else s2_args.get("n_sample_steps", 20))
    validity_thresh = (args.stage2_validity_thresh if args.stage2_validity_thresh is not None
                       else s2_args.get("validity_thresh", 0.0))
    # Keep stage-2 inference on the original random sampler. Earlier FPS
    # experiments added extra plumbing here, but the current submission/eval
    # path intentionally does not switch sampling modes from CLI or ckpt args.
    sampling = "random"
    # Oversample budgets: random uses a smaller candidate pool; voxel is left
    # as a code path for old experiments but is not selected by this script.
    def _default_oversample(s: str) -> int:
        if s == "voxel":
            return 16_000
        return 10_000
    n_col_oversample = (args.stage2_n_col_oversample
                        if args.stage2_n_col_oversample is not None
                        else _default_oversample(sampling))
    n_dep_oversample = (args.stage2_n_dep_oversample
                        if args.stage2_n_dep_oversample is not None
                        else _default_oversample(sampling))
    fps_max_exact_iters = None
    bf16_ok = device.type == "cuda" and torch.cuda.is_bf16_supported(including_emulation=False)
    if device.type == "cuda" and not bf16_ok and (args.encoder_bf16 or args.denoiser_bf16):
        print(f"[gpu] {torch.cuda.get_device_name(device)} has no native bf16: --encoder_bf16/--denoiser_bf16 "
              f"DISABLED, running those parts in fp32", flush=True)
    cfg = Stage2Config(
        model=model,
        n_pts=n_pts,
        k_verts=k_verts,
        n_sample_steps=n_sample_steps,
        validity_thresh=validity_thresh,
        above_m=args.stage2_above_m,
        below_m=args.stage2_below_m,
        side_m=args.stage2_side_m,
        n_col_oversample=n_col_oversample,
        n_dep_oversample=n_dep_oversample,
        n_depth_per_image_cap=args.stage2_n_depth_per_image_cap,
        sampling=sampling,
        density_voxel_size_m=args.stage2_density_voxel_size_m,
        density_kernel_radius=args.stage2_density_kernel_radius,
        density_kernel_axis=args.stage2_density_kernel_axis,
        density_response_power=args.stage2_density_response_power,
        density_planarity_suppression=args.stage2_density_planarity_suppression,
        density_planarity_radius=args.stage2_density_planarity_radius,
        density_planarity_min_points=args.stage2_density_planarity_min_points,
        density_min_per_voxel=args.stage2_density_min_per_voxel,
        ensemble_n=args.ensemble_n,
        ensemble_merge_m=args.ensemble_merge_m,
        ensemble_mode=args.ensemble_mode,
        ensemble_strategy=args.ensemble_strategy,
        ensemble_refine_positions=(not args.no_position_refine),
        ensemble_refine_agg=args.ensemble_refine_agg,
        ensemble_top_k=args.ensemble_top_k,
        ensemble_edge_vote=(not args.no_edge_vote),
        ensemble_edge_vote_frac=args.ensemble_edge_vote_frac,
        ensemble_vertex_vote_frac=args.ensemble_vertex_vote_frac,
        ensemble_stage2_last_k=args.ensemble_stage2_last_k,
        ensemble_selector=args.ensemble_selector,
        ensemble_ranker_path=args.ensemble_ranker_path,
        ensemble_ranker=(
            _load_ensemble_ranker(args.ensemble_ranker_path)
            if args.ensemble_selector == "ranker" else None
        ),
        ensemble_fixed_candidate=args.ensemble_fixed_candidate,
        ensemble_topk_fuse=args.ensemble_topk_fuse,
        fps_max_exact_iters=fps_max_exact_iters,
        seed=args.seed,
        encoder_bf16=args.encoder_bf16 and bf16_ok,
        denoiser_bf16=args.denoiser_bf16 and bf16_ok,
        cuda_graph=args.cuda_graph and device.type == "cuda",
        compile=args.compile and device.type == "cuda",
    )
    if device.type != "cuda" and (args.encoder_bf16 or args.denoiser_bf16 or args.tf32 or args.cuda_graph
                                  or args.compile or args.fps_kernel != "torch"):
        print(f"[gpu] device={device.type}: --encoder_bf16/--denoiser_bf16/--tf32/--cuda_graph/--compile/"
              f"--fps_kernel triton are CUDA-only and DISABLED here; running fp32 eager with the torch FPS loop",
              flush=True)
    if device.type == "cuda" and args.fps_kernel == "triton":
        try:
            from models import fps_triton  # noqa: F401  (imports triton)
        except ImportError as exc:
            raise SystemExit(f"[gpu] --fps_kernel triton (the default) needs the 'triton' package, which failed to "
                             f"import ({exc}); install triton or run with --fps_kernel torch (same anchors, "
                             f"slower)") from exc
    torch.backends.cuda.matmul.allow_tf32 = args.tf32 and device.type == "cuda"
    models.scene_encoder.FPS_BACKEND = args.fps_kernel if device.type == "cuda" else "torch"
    torch.backends.cuda.enable_cudnn_sdp(args.cudnn_sdpa)
    print(f"[gpu] seed={cfg.seed}  encoder_bf16={cfg.encoder_bf16}  denoiser_bf16={cfg.denoiser_bf16}  "
          f"tf32={torch.backends.cuda.matmul.allow_tf32}  cuda_graph={cfg.cuda_graph}  compile={cfg.compile}  "
          f"fps_kernel={models.scene_encoder.FPS_BACKEND}  cudnn_sdpa={args.cudnn_sdpa}", flush=True)
    extra = ""
    if cfg.sampling == "voxel":
        extra = (f"  density(voxel={cfg.density_voxel_size_m:.2f}m "
                 f"kernel={cfg.density_kernel_axis}:r{cfg.density_kernel_radius} "
                 f"planarity_supp={cfg.density_planarity_suppression:.2f})")
    elif cfg.sampling == "fps":
        extra = (f"  fps_max_exact_iters="
                 f"{'full' if cfg.fps_max_exact_iters is None else cfg.fps_max_exact_iters}")
    print(f"[stage2] enabled  n_pts={cfg.n_pts}  steps={cfg.n_sample_steps}  "
          f"sampling={cfg.sampling}  oversample={cfg.n_col_oversample}+{cfg.n_dep_oversample}  "
          f"hull=(+{cfg.above_m:.2f}/-{cfg.below_m:.2f}/±{cfg.side_m:.2f}){extra}",
          flush=True)
    if cfg.ensemble_n > 1:
        refine_str = (cfg.ensemble_refine_agg
                      if cfg.ensemble_refine_positions else "off")
        topk_str = ("all" if cfg.ensemble_top_k == 0
                    else f"top{cfg.ensemble_top_k}")
        edge_str = (f"vote>={cfg.ensemble_edge_vote_frac:.2f}"
                    if cfg.ensemble_edge_vote else "picked")
        vdrop_str = (f"vote>={cfg.ensemble_vertex_vote_frac:.2f}"
                     if cfg.ensemble_vertex_vote_frac > 0.0 else "off")
        print(f"[ensemble] N={cfg.ensemble_n}  strategy={cfg.ensemble_strategy}  "
              f"mode={cfg.ensemble_mode}  tau={cfg.ensemble_merge_m:.2f}m  "
              f"refine={refine_str}  members={topk_str}  edges={edge_str}  "
              f"vdrop={vdrop_str}  s2_lastk={cfg.ensemble_stage2_last_k}  "
              f"selector={cfg.ensemble_selector}", flush=True)
    return cfg


def parse_args(argv=None):
    p = argparse.ArgumentParser(description="S23DR 2026 submission script (trained model)")
    p.add_argument("--ckpt", default=None,
                   help="Checkpoint path; falls back to $S23DR_CKPT, params['ckpt'], "
                        "then ./test_checkpoint.pth")
    p.add_argument("--params", default="params.json")
    p.add_argument("--n_sample_steps", type=int, default=50,
                   help="Stage-1 diffusion ODE steps at inference (default: 50).")
    p.add_argument("--n_pts", type=int, default=None,
                   help="Stage-1 scene points at inference (default: ckpt args / 8192)")
    p.add_argument("--validity_thresh", type=float, default=0.0,
                   help="Drop predicted vertices below this validity logit "
                        "(default: 0.0)")
    p.add_argument("--device", default="cuda")
    # ---- data + pipeline ----------------------------------------------------
    p.add_argument("--data_dir", default="/tmp/data",
                   help="Test-server data dir (*public*/**/*.tar, *private*/**/*.tar, loader script); "
                        "downloaded with snapshot_download(params['dataset']) when missing.")
    p.add_argument("--loader", choices=["tar", "hf"], default="tar",
                   help="'tar': read the samples straight from the tars (rows equal to the loader script's; "
                        "members it does not read are skipped, as it skips them). 'hf': datasets.load_dataset on "
                        "the loader script, as released (Arrow build first); rows are decoded in the workers "
                        "either way.")
    p.add_argument("--colmap_order", choices=["pycolmap", "file"], default="pycolmap",
                   help="COLMAP point / image order: 'pycolmap' = exact released preprocessing (emulates "
                        "pycolmap's libstdc++ hash-map order); 'file' = portable file order (perturbs the "
                        "subsampled scenes like a different random draw).")
    p.add_argument("--n_workers", type=int, default=max(1, min(8, len(os.sched_getaffinity(0)) - 2)),
                   help="CPU worker processes (tar read, preprocessing, stage-2 build, selection), ~1 GB RAM "
                        "each. Default: CPUs in this process's affinity minus 2, at most 8 (more did not "
                        "speed up an H200), at least 1.")
    p.add_argument("--batch_samples", type=int, default=1,
                   help="Samples per GPU batch S (stage 1: S*ensemble_n trajectories). Larger is faster on a "
                        "big GPU: ~10 GB GPU memory at 8, ~20 GB at 16 (with CUDA graphs each stage captures "
                        "one graph for this shape). With bf16 / TF32 the predictions depend on S.")
    p.add_argument("--partial_batch", choices=["wait", "pad"], default="wait",
                   help="Fewer than --batch_samples ready while more are coming: 'wait' for a full batch "
                        "(partial batches only at the end of the data); 'pad' runs them as soon as the GPU "
                        "would idle.")
    p.add_argument("--stall_timeout", type=float, default=600.0,
                   help="Abort when no worker reports anything for this many seconds while samples are in flight.")
    # ---- GPU numerics / seeding --------------------------------------------
    p.add_argument("--seed", type=int, default=0,
                   help="Per-sample torch seed base: the x0 draws of every sample are reseeded "
                        "from sha1(order_id/seed/stage/n), so outputs do not depend on batching.")
    p.add_argument("--encoder_bf16", action=argparse.BooleanOptionalAction, default=True,
                   help="bf16 autocast in the scene encoders (FPS anchors and the encoder output stay "
                        "fp32). CUDA only.")
    p.add_argument("--denoiser_bf16", action=argparse.BooleanOptionalAction, default=True,
                   help="bf16 autocast in the denoiser blocks (ODE state, residual stream, embedding "
                        "and output heads stay fp32). CUDA only.")
    p.add_argument("--tf32", action=argparse.BooleanOptionalAction, default=True,
                   help="TF32 tensor cores for the remaining fp32 matmuls. CUDA only.")
    p.add_argument("--cuda_graph", action=argparse.BooleanOptionalAction, default=True,
                   help="Capture each denoiser ODE loop as a CUDA graph per batch shape (same kernels, no "
                        "launch overhead; one capture per new shape). CUDA only.")
    p.add_argument("--compile", action=argparse.BooleanOptionalAction, default=False,
                   help="torch.compile the denoiser step (fused elementwise kernels); compiles once per "
                        "model and batch shape on first use (tens of seconds). CUDA only.")
    p.add_argument("--cudnn_sdpa", action=argparse.BooleanOptionalAction, default=True,
                   help="Allow PyTorch's cuDNN attention backend (bf16; runtime-compiled kernels per new "
                        "shape, cached on disk). --no-cudnn_sdpa uses the flash / memory-efficient backends.")
    p.add_argument("--fps_kernel", choices=["torch", "triton"], default="triton",
                   help="Scene-encoder anchor FPS: 'torch' loop (~6 launches per anchor) or one fused "
                        "Triton kernel per call (identical indices). CUDA only.")
    p.add_argument("--output", default="submission.json")
    p.add_argument("--limit", type=int, default=0,
                   help="If >0, only process the first N samples per split (debug)")
    # ---- stage-2 refinement (optional) -----------------------------------
    p.add_argument("--stage2_ckpt", default=None,
                   help="Stage-2 refinement checkpoint. Falls back to "
                        "$S23DR_STAGE2_CKPT then params['stage2_ckpt']. "
                        "When unset, runs stage-1 only.")
    p.add_argument("--stage2_n_pts", type=int, default=None,
                   help="Stage-2 scene points (default: ckpt args / 16384).")
    p.add_argument("--stage2_n_sample_steps", type=int, default=50,
                   help="Stage-2 ODE steps (default: 50 — 2.5x training, "
                        "inference oversampling).")
    p.add_argument("--stage2_validity_thresh", type=float, default=0.0,
                   help="Stage-2 validity logit threshold (default: 0.0).")
    p.add_argument("--stage2_above_m", type=float, default=0.5,
                   help="Hull inflation upward (metres). Default 0.5.")
    p.add_argument("--stage2_below_m", type=float, default=0.5,
                   help="Hull inflation downward (metres). Default 0.5.")
    p.add_argument("--stage2_side_m", type=float, default=0.5,
                   help="Hull inflation laterally in X/Y (metres). Default 0.5.")
    p.add_argument("--stage2_n_col_oversample", type=int, default=None,
                   help="Stage-2 COLMAP oversample before sampling drops to n_pts//2. "
                        "Default: 10k for random sampling.")
    p.add_argument("--stage2_n_dep_oversample", type=int, default=None,
                   help="Stage-2 depth oversample before sampling drops to n_pts//2. "
                        "Default: 10k for random sampling.")
    p.add_argument("--stage2_n_depth_per_image_cap", type=int, default=30_000,
                   help="Cap on per-image depth pixels considered before the hull test.")
    p.add_argument("--stage2_sampling", choices=["random"], default="random",
                   help="Stage-2 scene sampling mode. The eval/submission path "
                        "is locked to random sampling.")
    p.add_argument("--stage2_fps_max_exact_iters", type=int, default=None,
                   help=argparse.SUPPRESS)
    # ---- stage-2 density-contrast hyperparams (only used when --stage2_sampling=voxel) -
    p.add_argument("--stage2_density_voxel_size_m", type=float, default=0.25)
    p.add_argument("--stage2_density_kernel_radius", type=int, default=3)
    p.add_argument("--stage2_density_kernel_axis",
                   choices=["cube", "x", "y", "z"], default="cube")
    p.add_argument("--stage2_density_response_power", type=float, default=1.0)
    p.add_argument("--stage2_density_planarity_suppression", type=float, default=1.0)
    p.add_argument("--stage2_density_planarity_radius", type=int, default=1)
    p.add_argument("--stage2_density_planarity_min_points", type=int, default=12)
    p.add_argument("--stage2_density_min_per_voxel", type=int, default=0)
    # ---- inference-time ensembling ---------------------------------------
    p.add_argument("--ensemble_n", type=int, default=16,
                   help="Run N stage-1 random-init trajectories and combine "
                        "them per --ensemble_mode. Default 16 (paired with "
                        "--ensemble_strategy union_hull this is ~1.2x wall "
                        "since stage-2 shares one encoder pass at B=N). "
                        "Set to 1 to disable.")
    p.add_argument("--ensemble_merge_m", type=float, default=0.5,
                   help="Vertex match threshold in metres for ensemble "
                        "selection (medoid Hungarian distance, position "
                        "refinement correspondents, consensus clustering). "
                        "Default 0.5 — matches the HSS metric's vert_thresh.")
    p.add_argument("--ensemble_strategy",
                   choices=["union_hull", "per_seed"], default="union_hull",
                   help="How stage-2 is run across the N ensemble members. "
                        "'union_hull' (default) builds ONE stage-2 scene "
                        "from the union of all stage-1 vertex predictions, "
                        "encodes once, and runs a B=N denoiser batch with "
                        "per-slot init_verts. 'per_seed' runs N independent "
                        "(build → encode → denoise) passes; slower but more "
                        "robust if union-hull occasionally fails.")
    p.add_argument("--ensemble_mode",
                   choices=["medoid", "consensus", "confidence"],
                   default="medoid",
                   help="How to combine the N ensemble runs. "
                        "'medoid' (default) picks the run most similar to "
                        "the others by Hungarian-matched distance. "
                        "'confidence' picks the run with the highest mean "
                        "validity logit. 'consensus' merges vertices and "
                        "majority-votes edges (lost recall in earlier tests).")
    p.add_argument("--no_position_refine", action="store_true",
                   help="Disable position refinement. By default, after the "
                        "selector (medoid / confidence) picks a run, each "
                        "vertex of that run is replaced with the per-axis "
                        "aggregate (see --ensemble_refine_agg) of itself "
                        "and its Hungarian-matched correspondents in the "
                        "other N-1 runs (within --ensemble_merge_m). "
                        "Topology unchanged; only vertex positions denoised.")
    p.add_argument("--ensemble_refine_agg", choices=["median", "mean", "wmean"],
                   default="mean",
                   help="Aggregator for position refinement. 'mean' "
                        "(default) has lower variance under iid noise; "
                        "'median' is robust to outlier correspondents; "
                        "'wmean' is a softmax-of-logit weighted mean (each "
                        "correspondent contributes proportional to "
                        "exp(validity_logit), so high-confidence runs "
                        "dominate). 'wmean' only kicks in when validity "
                        "logits are non-trivial — falls back to plain mean "
                        "when weights are uniform or missing.")
    p.add_argument("--ensemble_top_k", type=int, default=0,
                   help="Soft-medoid: restrict the correspondent / voter set "
                        "used by position refinement and edge voting to the "
                        "K most central runs (lowest pairwise Hungarian "
                        "distance). 0 (default) = use all N. Typical values "
                        "for N=16: 5-8. The picked run (medoid) is always "
                        "included.")
    p.add_argument("--no_edge_vote", action="store_true", default=True,
                   help="Keep the picked medoid/confidence run's edges "
                        "verbatim. This is the default.")
    p.add_argument("--edge_vote", action="store_false", dest="no_edge_vote",
                   help="Enable edge majority voting: after selection each "
                        "non-picked run's edges are relabelled into the picked "
                        "run's vertex index space via the same Hungarian match "
                        "used for position refinement, and edges with >= "
                        "--ensemble_edge_vote_frac of votes survive.")
    p.add_argument("--ensemble_edge_vote_frac", type=float, default=0.5,
                   help="Edge vote fraction (default 0.5 = strict majority). "
                        "An edge (i,j) in picked-vertex space is kept iff at "
                        "least ceil(M * frac) runs vote for it, where M is "
                        "the active voter set (top_k if set, else N).")
    p.add_argument("--ensemble_vertex_vote_frac", type=float, default=0.0,
                   help="Vertex consensus drop fraction (default 0.0 = off). "
                        "When > 0, a picked-run vertex survives iff at least "
                        "ceil(M * frac) voter runs have a Hungarian "
                        "correspondent within tau. The picked run itself is "
                        "always one voter (self-vote). Tightens precision by "
                        "dropping spurious one-run-only detections — "
                        "complements --ensemble_edge_vote. Used by both "
                        "medoid/confidence modes (picked-then-refine) and "
                        "consensus mode (sets the cluster-support threshold).")
    p.add_argument("--ensemble_stage2_last_k", type=int, default=1,
                   help="Average the last K stage-2 denoiser steps' "
                        "predictions (positions + validity / edge logits) "
                        "before thresholding. 1 (default) = use only the "
                        "final step (current behaviour). 3-5 mildly smooths "
                        "ODE jitter near the trajectory endpoint at zero "
                        "extra compute.")
    p.add_argument("--ensemble_selector", choices=["legacy", "ranker", "fixed"],
                   default="legacy",
                   help="Final ensemble chooser. 'legacy' (default) keeps the "
                        "medoid/confidence/consensus path with no reranker. "
                        "'ranker' builds "
                        "raw/refined/voted/additive-edge candidates and picks "
                        "with --ensemble_ranker_path if present, otherwise a "
                        "small built-in heuristic. 'fixed' picks a named "
                        "candidate family.")
    p.add_argument("--ensemble_fixed_candidate", default="confidence_mean_add",
                   help="Candidate name used by --ensemble_selector fixed. "
                        "Default confidence_mean_add, falling back to "
                        "medoid_mean_add when the confidence candidate is "
                        "identical to the medoid and therefore absent.")
    p.add_argument("--ensemble_topk_fuse", type=int, default=3,
                   help="Top-K ranker-scored candidates to fuse (mean-refine "
                        "positions + edge-vote union) when "
                        "--ensemble_selector=ranker. 1 disables fusion and "
                        "keeps the argmax candidate.")
    p.add_argument("--ensemble_ranker_path", default="ensemble_ranker_v5.npz",
                   help="NPZ produced by --train_ensemble_ranker_jsonl. Used "
                        "only when --ensemble_selector=ranker. If missing, "
                        "ranker mode falls back to a heuristic scorer.")
    p.add_argument("--ensemble_candidate_dump", default=None,
                   help="In --sanity mode, write ranker candidate features "
                        "and GT HSS labels as JSONL for fast selector training.")
    p.add_argument("--train_ensemble_ranker_jsonl", default=None,
                   help="Train the tiny NumPy ridge ranker from a candidate "
                        "JSONL dump and exit. No model checkpoint/GPU needed.")
    p.add_argument("--ensemble_ranker_out", default="ensemble_ranker.npz",
                   help="Output path for --train_ensemble_ranker_jsonl.")
    p.add_argument("--ensemble_ranker_l2", type=float, default=1e-2,
                   help="Ridge L2 for --train_ensemble_ranker_jsonl.")
    # ---- local sanity check (no submission) ------------------------------
    p.add_argument("--sanity", action="store_true",
                   help="Local pre-submission sanity check: load default ckpt, "
                        "run the inference pipeline on validation samples of the "
                        "public trainval dataset, score against GT, print HSS, and "
                        "exit. Writes no submission.json.")
    p.add_argument("--sanity_n", type=int, default=0,
                   help="Number of val samples to score in --sanity mode (the first N of the split). "
                        "0 (default) means score the entire split. Without --sanity_data_dir, N > 0 streams "
                        "only those samples from the Hub; 0 downloads the whole split.")
    p.add_argument("--sanity_split", default="validation",
                   help="Split to draw sanity samples from (default 'validation').")
    p.add_argument("--sanity_dataset", default="usm3d/hoho22k_2026_trainval",
                   help="HF dataset id with GT used for --sanity scoring (gated: accept its terms on the "
                        "Hub and log in with 'hf auth login').")
    p.add_argument("--sanity_cache_dir", default="cache",
                   help="Cache dir for --sanity data: <dir>/<dataset>/data/<split>/ holds the full shards "
                        "(--sanity_n 0), <dir>/<dataset>/stream/<split>/ the streamed sample prefixes; later "
                        "runs that need no more samples reuse them offline.")
    p.add_argument("--sanity_data_dir", default=None,
                   help="Use the *.tar files below this dir (GT included) instead of downloading.")
    p.add_argument("--sanity_ensemble_diagnostics", action="store_true",
                   help="In --sanity mode, score ensemble alternatives: "
                        "member0, medoid pick, confidence pick, final fused, "
                        "and oracle-best member. Diagnostic only; normal "
                        "predictions are unchanged.")
    return p.parse_args(argv)


def main(argv=None) -> Optional[Dict[str, Any]]:
    """Returns the pipeline summary (``run_pipeline``; with the sanity means in --sanity mode)."""
    args = parse_args(argv)

    if args.train_ensemble_ranker_jsonl:
        train_ensemble_ranker_jsonl(
            args.train_ensemble_ranker_jsonl,
            args.ensemble_ranker_out,
            l2=args.ensemble_ranker_l2,
        )
        return None
    if args.batch_samples < 1 or args.n_workers < 1:
        raise SystemExit("--batch_samples and --n_workers must be >= 1")

    # Workers start first: their imports and warm-up overlap with the dataset indexing and model loads.
    # SIGINT is ignored while they are spawned, so each worker ignores it from its first instruction on.
    previous = signal.signal(signal.SIGINT, signal.SIG_IGN)
    workers = start_workers(args.n_workers)

    def on_sigint(_signum, _frame):  # Ctrl-C: stop now (a running download's threads would keep the process alive)
        print("[interrupt] stopping", flush=True)
        kill_workers(workers)
        os._exit(130)

    signal.signal(signal.SIGINT, on_sigint)
    try:
        return _main(args, workers)
    except BaseException:
        kill_workers(workers)
        raise
    finally:
        signal.signal(signal.SIGINT, previous)


def _main(args, workers) -> Dict[str, Any]:
    hf_splits: Dict[str, Any] = {}
    if args.sanity:
        # --sanity needs neither the test data nor params.json: score the public trainval GT.
        params: Dict[str, Any] = {}
        if Path(args.params).exists():
            with open(args.params) as f:
                params = json.load(f)
        items = sanity_items(args)
    else:
        print("------------ Loading dataset ------------", flush=True)
        with open(args.params) as f:
            params = json.load(f)
        print(params, flush=True)

        print("pwd:", flush=True);  os.system("pwd")
        os.system("ls -lahtr")
        print(f"{args.data_dir}/");       os.system(f"ls -lahtr {shlex.quote(args.data_dir)}/ 2>/dev/null")
        print(f"{args.data_dir}/data");   os.system(f"ls -lahtrR {shlex.quote(args.data_dir)}/data 2>/dev/null")

        data_path = resolve_data_dir(args.data_dir, params)
        files = split_tars(data_path)
        if args.loader == "tar":
            items = tar_items(files, args.limit)
        else:
            items, hf_splits = hf_items(data_path, files, args.limit)
        print(f"[data] {len(items)} samples (--loader {args.loader}, --limit {args.limit})", flush=True)

    # ---- model: loaded ONCE -----------------------------------------------
    ckpt_path = resolve_ckpt_path(args.ckpt, params)
    if args.device == "cuda" and not torch.cuda.is_available():
        if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
            device = torch.device("mps")
        else:
            device = torch.device("cpu")
    else:
        device = torch.device(args.device)
    if device.type == "cpu":
        print("[warn] CUDA/MPS unavailable — running on CPU; this will be slow.", flush=True)
    if device.type == "cuda":
        # This process's CPU work is now only the GPU loop's small batch copies: torch's 16-thread OpenMP
        # pool made them slower (stage-2 batch assembly +15 ms/sample, measured), so one thread.
        torch.set_num_threads(1)
    model, ckpt_args = load_model(ckpt_path, device)

    n_pts           = (args.n_pts if args.n_pts is not None
                       else ckpt_args.get("n_pts", 8192))
    use_depth       = ckpt_args.get("use_depth", True)
    n_sample_steps  = (args.n_sample_steps if args.n_sample_steps is not None
                       else ckpt_args.get("n_sample_steps", 50))
    validity_thresh = (args.validity_thresh if args.validity_thresh is not None
                       else ckpt_args.get("validity_thresh", 0.0))
    print(f"[infer] n_pts={n_pts}  use_depth={use_depth}  "
          f"n_sample_steps={n_sample_steps}  validity_thresh={validity_thresh}  "
          f"torch_threads={torch.get_num_threads()}  n_workers={args.n_workers}  batch_samples={args.batch_samples}  partial_batch={args.partial_batch}  "
          f"colmap_order={args.colmap_order}", flush=True)

    stage2_cfg = _build_stage2_cfg(args, params, device)
    host_cfg = copy.copy(stage2_cfg)  # what the workers need: every knob except the GPU model
    host_cfg.model = None
    opts = {"n_pts": n_pts, "use_depth": use_depth, "colmap_order": args.colmap_order, "cfg": host_cfg,
            "hf_splits": hf_splits, "sanity": args.sanity,
            "diagnostics": args.sanity and (args.sanity_ensemble_diagnostics or args.ensemble_candidate_dump is not None),
            "dump": args.sanity and args.ensemble_candidate_dump is not None}
    for p, tx, _rx in workers:
        try:
            tx.send(("init", opts))
        except (BrokenPipeError, ConnectionResetError):  # a worker died during start-up
            p.join(timeout=5)
            check_workers(workers)
            raise

    if args.sanity:
        return run_sanity_check(workers, items, model, stage2_cfg, device, n_sample_steps, validity_thresh,
                                args)

    # ---- inference --------------------------------------------------------
    print("------------ Running inference ------------", flush=True)
    solution, summary = run_pipeline(workers, items, model, stage2_cfg, device, n_sample_steps,
                                     validity_thresh, args, _print_prediction)

    print("------------ Saving results ------------", flush=True)
    with open(args.output, "w") as f:
        json.dump(solution, f)
    print(f"[done] wrote {len(solution)} predictions → {args.output}  (FAILED: {summary['n_failed']})", flush=True)
    return summary


if __name__ == "__main__":
    summary = main()
    if summary is not None and summary["n_failed"]:
        print(f"[done] {summary['n_failed']} of {summary['n']} samples FAILED (see '[predict] ... FAILED' above); "
              f"their predictions are empty solutions. Exit code 1.", flush=True)
        sys.exit(1)