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 | class SvmTrains(Trains):
def __init__(
self,
dataname: str,
filename: str = "train.in",
chunk_size: int = 1_000_000,
**kwargs: Any,
):
Trains.__init__(self,
dataname,
filename=filename,
chunk_size=chunk_size,
**kwargs)
self.info = SimpleNamespace(
total=0,
pos=0,
neg=0,
line_count=0,
raw_chunk_n=0,
chunk_size=chunk_size,
)
def connect(self, manager: "SyncManager") -> None:
"""Move local statistics into a namespace owned by the session Manager."""
if self._lock is not None:
return
local = self.info
super().connect(manager)
self.info = manager.Namespace()
self.info.total = local.total
self.info.pos = local.pos
self.info.neg = local.neg
self.info.line_count = local.line_count
self.info.raw_chunk_n = local.raw_chunk_n
self.info.chunk_size = local.chunk_size
def disconnect(self) -> None:
"""Copy shared statistics locally before discarding Manager proxies."""
if self._lock is None:
return
shared = self.info
self.info = SimpleNamespace(
total=shared.total,
pos=shared.pos,
neg=shared.neg,
line_count=shared.line_count,
raw_chunk_n=shared.raw_chunk_n,
chunk_size=shared.chunk_size,
)
super().disconnect()
def represent(self) -> dict[str, Any]:
return dict(
cls=f"{self.__class__.__module__}.{self.__class__.__name__}",
dataname=self._dataname,
filename=self._filename,
chunk_size=self.info.chunk_size,
)
def reset(
self,
dataname: (str | None) = None,
filename: str = "train.in",
) -> None:
super().reset(dataname=dataname, filename=filename)
if hasattr(self, "info"):
self.info.total = 0
self.info.pos = 0
self.info.neg = 0
self.info.line_count = 0
self.info.raw_chunk_n = 0
def exists(self) -> bool:
return svm.exists(self.path())
def stats(
self,
instance: tuple[str, str],
strategy: str,
samples: str,
) -> None:
count = samples.count("\n")
s0 = samples[0]
pos = samples.count("\n1 ") + (1 if s0 == "1" else 0)
neg = samples.count("\n0 ") + (1 if s0 == "0" else 0)
self.info.total += count
self.info.pos += pos
self.info.neg += neg
with open(self.path() + "-stats.txt", "a") as infa:
infa.write(f"{instance} {strategy}: {count} ({pos} / {neg})\n")
def save(
self,
instance: tuple[str, str],
strategy: str,
samples: str,
) -> None:
if (not samples) or (not self._enabled):
return
new_lines = samples.count("\n")
if self._lock is None:
raise RuntimeError("SvmTrains must be connected before evaluation")
self._lock.acquire()
try:
if self.info.line_count + new_lines > self.info.chunk_size and \
self.info.line_count > 0:
self.info.raw_chunk_n += 1
self.info.line_count = 0
raw_path = svm.raw_path(self.path(), self.info.raw_chunk_n)
os.makedirs(os.path.dirname(self.path()), exist_ok=True)
with open(raw_path, "a") as fa:
fa.write(samples)
self.info.line_count += new_lines
self.stats(instance, strategy, samples)
finally:
self._lock.release()
def compress(self,
chunk_size: int | None = None,
cores: int | None = None) -> None:
logger.info(
f"Training vectors count: {self.info.total} ({self.info.pos} / {self.info.neg}) "
)
svm.compress(self.path(),
chunk_size=chunk_size or self.info.chunk_size,
cores=cores)
def train_data_snapshot(self) -> None:
"""Persist counts and uncompressed bytes for the current logical file."""
path = self.path()
if not svm.exists(path):
return
metadata = svm.metadata_load(path)
if svm.format(path).startswith("text/"):
raw_bytes = svm.size(path)
else:
raw_bytes = metadata.get("raw_bytes")
if self.info.total or "vectors" not in metadata:
metadata.update({
"vectors": self.info.total,
"positive": self.info.pos,
"negative": self.info.neg,
})
if raw_bytes is not None:
metadata["raw_bytes"] = raw_bytes
svm.metadata_save(path, metadata)
def train_data_stats(
self,
dataset: str,
path: str | None = None,
) -> dict[str, Any] | None:
"""Return report-ready statistics without loading vector data."""
path = path or self.path()
if not svm.exists(path):
return None
storage = svm.storage(path)
metadata = svm.metadata_load(path)
if "raw_bytes" not in metadata and storage["format"].startswith("text/"):
metadata["raw_bytes"] = storage["stored_bytes"]
return {
"dataset": dataset,
"path": path,
**metadata,
**storage,
}
def merge(
self,
previous: str | tuple[str, ...],
outfilename: str,
) -> None:
assert self._filename != outfilename
assert type(previous) is str
if not svm.exists(self.path()):
logger.warning(f"Trains not found: {self.path()}.")
return
f_out = self.path(filename=outfilename)
svm.merge(previous, self.path(), f_out)
#self.reset(filename=outfilename)
def link(self, src: str | tuple[str]):
assert isinstance(src, str)
if not svm.exists(src):
logger.warning(f"Link source not found: {src}.")
return
dst = self.path()
if svm.exists(dst):
logger.warning(f"Link targed exists: {dst}.")
return
svm.link(src, dst)
|