KingNish commited on
Commit
c80ca96
·
verified ·
1 Parent(s): f5135ef

Upload ./RepCodec/examples/feature_utils.py with huggingface_hub

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