ShiromiyaGamer commited on
Commit
b66714e
1 Parent(s): 339a64c

Upload feature_utils.py

Browse files
Files changed (1) hide show
  1. feature_utils.py +66 -0
feature_utils.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import logging
7
+ import os
8
+ import sys
9
+
10
+ import tqdm
11
+ from npy_append_array import NpyAppendArray
12
+
13
+
14
+ logging.basicConfig(
15
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
16
+ datefmt="%Y-%m-%d %H:%M:%S",
17
+ level=os.environ.get("LOGLEVEL", "INFO").upper(),
18
+ stream=sys.stdout,
19
+ )
20
+ logger = logging.getLogger("feature_utils")
21
+
22
+
23
+ def get_shard_range(tot, nshard, rank):
24
+ assert rank < nshard and rank >= 0, f"invaid rank/nshard {rank}/{nshard}"
25
+ start = round(tot / nshard * rank)
26
+ end = round(tot / nshard * (rank + 1))
27
+ assert start < end, f"start={start}, end={end}"
28
+ logger.info(
29
+ f"rank {rank} of {nshard}, process {end-start} "
30
+ f"({start}-{end}) out of {tot}"
31
+ )
32
+ return start, end
33
+
34
+
35
+ def get_path_iterator(tsv, nshard, rank):
36
+ with open(tsv, "r", encoding="utf-8") as f:
37
+ root = f.readline().rstrip()
38
+ lines = [line.rstrip() for line in f]
39
+ start, end = get_shard_range(len(lines), nshard, rank)
40
+ lines = lines[start:end]
41
+ def iterate():
42
+ for line in lines:
43
+ subpath, nsample = line.split("\t")
44
+ yield f"{root}/{subpath}", int(nsample)
45
+ return iterate, len(lines)
46
+
47
+
48
+ def dump_feature(reader, generator, num, split, nshard, rank, feat_dir):
49
+ iterator = generator()
50
+
51
+ feat_path = f"{feat_dir}/{split}_{rank}_{nshard}.npy"
52
+ leng_path = f"{feat_dir}/{split}_{rank}_{nshard}.len"
53
+
54
+ os.makedirs(feat_dir, exist_ok=True)
55
+ if os.path.exists(feat_path):
56
+ os.remove(feat_path)
57
+
58
+ feat_f = NpyAppendArray(feat_path)
59
+ with open(leng_path, "w", encoding="utf-8") as leng_f:
60
+ for path, nsample in tqdm.tqdm(iterator, total=num):
61
+ feat = reader.get_feats(path, nsample)
62
+ feat_f.append(feat.cpu().numpy())
63
+ leng_f.write(f"{len(feat)}\n")
64
+ logger.info("finished successfully")
65
+
66
+