-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathfilemanager.py
More file actions
635 lines (514 loc) · 19 KB
/
filemanager.py
File metadata and controls
635 lines (514 loc) · 19 KB
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
from __future__ import annotations
import math
import os
import shutil
import stat
import tempfile
import uuid
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from functools import partial
from pathlib import Path
from typing import Any, BinaryIO, Dict, List, Tuple
import requests
from filelock import FileLock
from requests.structures import CaseInsensitiveDict
from tqdm import tqdm
from together.abstract import api_requestor
from together.constants import (
DISABLE_TQDM,
DOWNLOAD_BLOCK_SIZE,
MAX_CONCURRENT_PARTS,
MAX_FILE_SIZE_GB,
MAX_RETRIES,
MIN_PART_SIZE_MB,
NUM_BYTES_IN_GB,
TARGET_PART_SIZE_MB,
MAX_MULTIPART_PARTS,
MULTIPART_UPLOAD_TIMEOUT,
)
from together.error import (
APIError,
AuthenticationError,
DownloadError,
FileTypeError,
ResponseError,
)
from together.together_response import TogetherResponse
from together.types import (
FilePurpose,
FileResponse,
FileType,
TogetherClient,
TogetherRequest,
)
from tqdm.utils import CallbackIOWrapper
import together.utils
def chmod_and_replace(src: Path, dst: Path) -> None:
"""Set correct permission before moving a blob from tmp directory to cache dir.
Do not take into account the `umask` from the process as there is no convenient way
to get it that is thread-safe.
"""
# Get umask by creating a temporary file in the cache folder.
tmp_file = dst.parent / f"tmp_{uuid.uuid4()}"
try:
tmp_file.touch()
cache_dir_mode = Path(tmp_file).stat().st_mode
os.chmod(src.as_posix(), stat.S_IMODE(cache_dir_mode))
finally:
tmp_file.unlink()
shutil.move(src.as_posix(), dst.as_posix())
def _get_file_size(
headers: CaseInsensitiveDict[str],
) -> int:
"""
Extracts file size from header
"""
total_size_in_bytes = 0
parts = headers.get("Content-Range", "").split(" ")
if len(parts) == 2:
range_parts = parts[1].split("/")
if len(range_parts) == 2:
total_size_in_bytes = int(range_parts[1])
return total_size_in_bytes
def _prepare_output(
headers: CaseInsensitiveDict[str],
step: int = -1,
output: Path | None = None,
remote_name: str | None = None,
) -> Path:
"""
Generates output file name from remote name and headers
"""
if output:
return output
content_type = str(headers.get("content-type"))
assert remote_name, (
"No model name found in fine_tune object. "
"Please specify an `output` file name."
)
if step > 0:
remote_name += f"-checkpoint-{step}"
if "x-tar" in content_type.lower():
remote_name += ".tar.gz"
else:
remote_name += ".tar.zst"
return Path(remote_name)
class DownloadManager:
def __init__(self, client: TogetherClient) -> None:
self._client = client
def get_file_metadata(
self,
url: str,
output: Path | None = None,
remote_name: str | None = None,
fetch_metadata: bool = False,
) -> Tuple[Path, int]:
"""
gets remote file head and parses out file name and file size
"""
if not fetch_metadata:
if isinstance(output, Path):
file_path = output
else:
assert isinstance(remote_name, str)
file_path = Path(remote_name)
return file_path, 0
requestor = api_requestor.APIRequestor(
client=self._client,
)
response = requestor.request_raw(
options=TogetherRequest(
method="GET",
url=url,
headers={"Range": "bytes=0-1"},
),
remaining_retries=MAX_RETRIES,
stream=False,
)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
raise APIError(
"Error fetching file metadata", http_status=response.status_code
) from e
headers = response.headers
assert isinstance(headers, CaseInsensitiveDict)
file_path = _prepare_output(
headers=headers,
output=output,
remote_name=remote_name,
)
file_size = _get_file_size(headers)
return file_path, file_size
def download(
self,
url: str,
output: Path | None = None,
remote_name: str | None = None,
fetch_metadata: bool = False,
) -> Tuple[str, int]:
requestor = api_requestor.APIRequestor(
client=self._client,
)
# pre-fetch remote file name and file size
file_path, file_size = self.get_file_metadata(
url, output, remote_name, fetch_metadata
)
temp_file_manager = partial(
tempfile.NamedTemporaryFile, mode="wb", dir=file_path.parent, delete=False
)
# Prevent parallel downloads of the same file with a lock.
lock_path = Path(file_path.as_posix() + ".lock")
with FileLock(lock_path.as_posix()):
with temp_file_manager() as temp_file:
response = requestor.request_raw(
options=TogetherRequest(
method="GET",
url=url,
),
remaining_retries=MAX_RETRIES,
stream=True,
request_timeout=3600,
)
try:
response.raise_for_status()
except Exception as e:
os.remove(lock_path)
raise APIError(
"Error downloading file", http_status=response.status_code
) from e
if not fetch_metadata:
file_size = int(response.headers.get("content-length", 0))
with tqdm(
total=file_size,
unit="B",
unit_scale=True,
desc=f"Downloading file {file_path.name}",
disable=bool(DISABLE_TQDM),
) as pbar:
for chunk in response.iter_content(DOWNLOAD_BLOCK_SIZE):
pbar.update(len(chunk))
temp_file.write(chunk)
# Raise exception if remote file size does not match downloaded file size
if os.stat(temp_file.name).st_size != file_size:
DownloadError(
f"Downloaded file size `{pbar.n}` bytes does not match "
f"remote file size `{file_size}` bytes."
)
# Moves temp file to output file path
chmod_and_replace(Path(temp_file.name), file_path)
os.remove(lock_path)
return str(file_path.resolve()), file_size
class UploadManager:
def __init__(self, client: TogetherClient) -> None:
self._client = client
@classmethod
def _redirect_error_handler(
cls, requestor: api_requestor.APIRequestor, response: requests.Response
) -> None:
if response.status_code == 401:
raise AuthenticationError(
"This job would exceed your free trial credits. "
"Please upgrade to a paid account through "
"Settings -> Billing on api.together.ai to continue.",
)
elif response.status_code != 302:
raise APIError(
f"Unexpected error raised by endpoint: {response.content.decode()}, headers: {response.headers}",
http_status=response.status_code,
)
def get_upload_url(
self,
url: str,
file: Path,
purpose: FilePurpose,
filetype: FileType,
) -> Tuple[str, str]:
data = {
"purpose": purpose.value,
"file_name": file.name,
"file_type": filetype.value,
}
requestor = api_requestor.APIRequestor(
client=self._client,
)
method = "POST"
headers = together.utils.get_headers(method, requestor.api_key)
response = requestor.request_raw(
options=TogetherRequest(
method=method,
url=url,
params=data,
allow_redirects=False,
override_headers=True,
headers=headers,
),
remaining_retries=MAX_RETRIES,
)
self._redirect_error_handler(requestor, response)
redirect_url = response.headers["Location"]
file_id = response.headers["X-Together-File-Id"]
return redirect_url, file_id
def callback(self, url: str) -> TogetherResponse:
requestor = api_requestor.APIRequestor(
client=self._client,
)
response, _, _ = requestor.request(
options=TogetherRequest(
method="POST",
url=url,
),
)
return response
def upload(
self,
url: str,
file: Path,
purpose: FilePurpose,
redirect: bool = False,
) -> FileResponse:
file_id = None
requestor = api_requestor.APIRequestor(
client=self._client,
)
redirect_url = None
if redirect:
if file.suffix == ".jsonl":
filetype = FileType.jsonl
elif file.suffix == ".parquet":
filetype = FileType.parquet
elif file.suffix == ".csv":
filetype = FileType.csv
else:
raise FileTypeError(
f"Unknown extension of file {file}. "
"Only files with extensions .jsonl and .parquet are supported."
)
redirect_url, file_id = self.get_upload_url(url, file, purpose, filetype)
file_size = os.stat(file).st_size
with tqdm(
total=file_size,
unit="B",
unit_scale=True,
desc=f"Uploading file {file.name}",
disable=bool(DISABLE_TQDM),
) as pbar:
with file.open("rb") as f:
wrapped_file = CallbackIOWrapper(pbar.update, f, "read")
if redirect:
callback_response = requestor.request_raw(
options=TogetherRequest(
method="PUT",
url=redirect_url,
params=wrapped_file,
override_headers=True,
),
absolute=True,
remaining_retries=MAX_RETRIES,
)
else:
response, _, _ = requestor.request(
options=TogetherRequest(
method="PUT",
url=url,
params=wrapped_file,
),
)
if redirect:
assert isinstance(callback_response, requests.Response)
if not callback_response.status_code == 200:
raise APIError(
f"Error during file upload: {callback_response.content.decode()}, headers: {callback_response.headers}",
http_status=callback_response.status_code,
)
response = self.callback(f"{url}/{file_id}/preprocess")
assert isinstance(response, TogetherResponse)
return FileResponse(**response.data)
class MultipartUploadManager:
"""Handles multipart uploads for large files"""
def __init__(self, client: TogetherClient) -> None:
self._client = client
self.max_concurrent_parts = MAX_CONCURRENT_PARTS
def upload(
self,
url: str,
file: Path,
purpose: FilePurpose,
) -> FileResponse:
"""Upload large file using multipart upload"""
file_size = os.stat(file).st_size
file_size_gb = file_size / NUM_BYTES_IN_GB
if file_size_gb > MAX_FILE_SIZE_GB:
raise FileTypeError(
f"File size {file_size_gb:.1f}GB exceeds maximum supported size of {MAX_FILE_SIZE_GB}GB"
)
part_size, num_parts = self._calculate_parts(file_size)
file_type = self._get_file_type(file)
upload_info = None
try:
upload_info = self._initiate_upload(
url, file, file_size, num_parts, purpose, file_type
)
completed_parts = self._upload_parts_concurrent(
file, upload_info, part_size
)
return self._complete_upload(
url, upload_info["upload_id"], upload_info["file_id"], completed_parts
)
except Exception as e:
# Cleanup on failure
if upload_info is not None:
self._abort_upload(
url, upload_info["upload_id"], upload_info["file_id"]
)
raise e
def _get_file_type(self, file: Path) -> str:
"""Get file type from extension, raising ValueError for unsupported extensions"""
if file.suffix == ".jsonl":
return "jsonl"
elif file.suffix == ".parquet":
return "parquet"
elif file.suffix == ".csv":
return "csv"
else:
raise ValueError(
f"Unsupported file extension: '{file.suffix}'. "
f"Supported extensions: .jsonl, .parquet, .csv"
)
def _calculate_parts(self, file_size: int) -> tuple[int, int]:
"""Calculate optimal part size and count"""
min_part_size = MIN_PART_SIZE_MB * 1024 * 1024 # 5MB
target_part_size = TARGET_PART_SIZE_MB * 1024 * 1024 # 100MB
if file_size <= target_part_size:
return file_size, 1
num_parts = min(MAX_MULTIPART_PARTS, math.ceil(file_size / target_part_size))
part_size = math.ceil(file_size / num_parts)
if part_size < min_part_size:
part_size = min_part_size
num_parts = math.ceil(file_size / part_size)
return part_size, num_parts
def _initiate_upload(
self,
url: str,
file: Path,
file_size: int,
num_parts: int,
purpose: FilePurpose,
file_type: str,
) -> Any:
"""Initiate multipart upload with backend"""
requestor = api_requestor.APIRequestor(client=self._client)
payload = {
"file_name": file.name,
"file_size": file_size,
"num_parts": num_parts,
"purpose": purpose.value,
"file_type": file_type,
}
response, _, _ = requestor.request(
options=TogetherRequest(
method="POST",
url="files/multipart/initiate",
params=payload,
),
)
return response.data
def _submit_part(
self,
executor: ThreadPoolExecutor,
f: BinaryIO,
part_info: Dict[str, Any],
part_size: int,
) -> Future[str]:
"""Submit a single part for upload and return the future"""
f.seek((part_info["PartNumber"] - 1) * part_size)
part_data = f.read(part_size)
return executor.submit(self._upload_single_part, part_info, part_data)
def _upload_parts_concurrent(
self, file: Path, upload_info: Dict[str, Any], part_size: int
) -> List[Dict[str, Any]]:
"""Upload file parts concurrently with progress tracking"""
parts = upload_info["parts"]
completed_parts = []
with ThreadPoolExecutor(max_workers=self.max_concurrent_parts) as executor:
with tqdm(total=len(parts), desc="Uploading parts", unit="part") as pbar:
with open(file, "rb") as f:
future_to_part = {}
part_index = 0
# Submit initial batch limited by max_concurrent_parts
for _ in range(min(self.max_concurrent_parts, len(parts))):
part_info = parts[part_index]
future = self._submit_part(executor, f, part_info, part_size)
future_to_part[future] = part_info["PartNumber"]
part_index += 1
# Process completions and submit new parts (sliding window)
while future_to_part:
done_future = next(as_completed(future_to_part))
part_number = future_to_part.pop(done_future)
try:
etag = done_future.result()
completed_parts.append(
{"part_number": part_number, "etag": etag}
)
pbar.update(1)
except Exception as e:
raise Exception(f"Failed to upload part {part_number}: {e}")
# Submit next part if available
if part_index < len(parts):
part_info = parts[part_index]
future = self._submit_part(
executor, f, part_info, part_size
)
future_to_part[future] = part_info["PartNumber"]
part_index += 1
completed_parts.sort(key=lambda x: x["part_number"])
return completed_parts
def _upload_single_part(self, part_info: Dict[str, Any], part_data: bytes) -> str:
"""Upload a single part and return ETag"""
response = requests.put(
part_info["URL"],
data=part_data,
headers=part_info.get("Headers", {}),
timeout=MULTIPART_UPLOAD_TIMEOUT,
)
response.raise_for_status()
etag = response.headers.get("ETag", "").strip('"')
if not etag:
raise ResponseError(f"No ETag returned for part {part_info['PartNumber']}")
return etag
def _complete_upload(
self,
url: str,
upload_id: str,
file_id: str,
completed_parts: List[Dict[str, Any]],
) -> FileResponse:
"""Complete the multipart upload"""
requestor = api_requestor.APIRequestor(client=self._client)
payload = {
"upload_id": upload_id,
"file_id": file_id,
"parts": completed_parts,
}
response, _, _ = requestor.request(
options=TogetherRequest(
method="POST",
url="files/multipart/complete",
params=payload,
),
)
return FileResponse(**response.data.get("file", response.data))
def _abort_upload(self, url: str, upload_id: str, file_id: str) -> None:
"""Abort the multipart upload"""
requestor = api_requestor.APIRequestor(client=self._client)
payload = {
"upload_id": upload_id,
"file_id": file_id,
}
requestor.request(
options=TogetherRequest(
method="POST",
url="files/multipart/abort",
params=payload,
),
)