id int64 1 6.07M | name stringlengths 1 295 | code stringlengths 12 426k | language stringclasses 1
value | source_file stringlengths 5 202 | start_line int64 1 158k | end_line int64 1 158k | repo dict |
|---|---|---|---|---|---|---|---|
4,501 | add | def add(self, context_id: str) -> Context:
assert context_id
context_obj = Context()
self._active_items[context_id] = context_obj
return context_obj | python | wandb/sdk/internal/context.py | 57 | 61 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,502 | get | def get(self, context_id: str) -> Optional[Context]:
item = self._active_items.get(context_id)
return item | python | wandb/sdk/internal/context.py | 63 | 65 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,503 | release | def release(self, context_id: str) -> None:
if not context_id:
return
_ = self._active_items.pop(context_id, None) | python | wandb/sdk/internal/context.py | 67 | 70 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,504 | cancel | def cancel(self, context_id: str) -> bool:
item = self.get(context_id)
if item:
item.cancel()
return True
return False | python | wandb/sdk/internal/context.py | 72 | 77 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,505 | __init__ | def __init__(self, start_chunk_id: int = 0) -> None:
self._chunk_id = start_chunk_id | python | wandb/sdk/internal/file_stream.py | 58 | 59 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,506 | process_chunks | def process_chunks(
self, chunks: List[Chunk]
) -> Union[bool, "ProcessedChunk", "ProcessedBinaryChunk", List["ProcessedChunk"]]:
chunk_id = self._chunk_id
self._chunk_id += len(chunks)
return {"offset": chunk_id, "content": [c.data for c in chunks]} | python | wandb/sdk/internal/file_stream.py | 61 | 66 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,507 | process_chunks | def process_chunks(self, chunks: List[Chunk]) -> "ProcessedChunk":
chunk_id = self._chunk_id
# TODO: chunk_id is getting reset on each request...
self._chunk_id += len(chunks)
chunk_data = []
for chunk in chunks:
if len(chunk.data) > util.MAX_LINE_BYTES:
msg = "Metric data exceeds maximum size of {} ({})".format(
util.to_human_size(util.MAX_LINE_BYTES),
util.to_human_size(len(chunk.data)),
)
wandb.termerror(msg, repeat=False)
wandb._sentry.message(msg, repeat=False)
else:
chunk_data.append(chunk.data)
return {
"offset": chunk_id,
"content": chunk_data,
} | python | wandb/sdk/internal/file_stream.py | 70 | 89 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,508 | process_chunks | def process_chunks(self, chunks: List[Chunk]) -> Union[bool, "ProcessedChunk"]:
data = chunks[-1].data
if len(data) > util.MAX_LINE_BYTES:
msg = "Summary data exceeds maximum size of {}. Dropping it.".format(
util.to_human_size(util.MAX_LINE_BYTES)
)
wandb.termerror(msg, repeat=False)
wandb._sentry.message(msg, repeat=False)
return False
return {"offset": 0, "content": [data]} | python | wandb/sdk/internal/file_stream.py | 93 | 102 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,509 | __init__ | def __init__(self) -> None:
self.found_cr = False
self.cr = None
self.last_normal = None | python | wandb/sdk/internal/file_stream.py | 121 | 124 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,510 | __init__ | def __init__(self, start_chunk_id: int = 0) -> None:
super().__init__(start_chunk_id=start_chunk_id)
self._prev_chunk = None
self.global_offset = 0
# cr refers to carriage return \r
self.stderr = StreamCRState()
self.stdout = StreamCRState() | python | wandb/sdk/internal/file_stream.py | 140 | 147 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,511 | get_consecutive_offsets | def get_consecutive_offsets(console: Dict[int, str]) -> List[List[int]]:
"""Compress consecutive line numbers into an interval.
Args:
console: Dict[int, str] which maps offsets (line numbers) to lines of text.
It represents a mini version of our console dashboard on the UI.
Returns:
A list of intervals (we compress consecutive line numbers into an interval).
Example:
>>> console = {2: "", 3: "", 4: "", 5: "", 10: "", 11: "", 20: ""}
>>> get_consecutive_offsets(console)
[(2, 5), (10, 11), (20, 20)]
"""
offsets = sorted(list(console.keys()))
intervals: List = []
for i, num in enumerate(offsets):
if i == 0:
intervals.append([num, num])
continue
largest = intervals[-1][1]
if num == largest + 1:
intervals[-1][1] = num
else:
intervals.append([num, num])
return intervals | python | wandb/sdk/internal/file_stream.py | 150 | 176 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,512 | split_chunk | def split_chunk(chunk: Chunk) -> Tuple[str, str]:
r"""Split chunks.
Args:
chunk: object with two fields: filename (str) & data (str)
`chunk.data` is a str containing the lines we want. It usually contains \n or \r or both.
`chunk.data` has two possible formats (for the two streams - stdout and stderr):
- "2020-08-25T20:38:36.895321 this is my line of text\nsecond line\n"
- "ERROR 2020-08-25T20:38:36.895321 this is my line of text\nsecond line\nthird\n".
Here's another example with a carriage return \r.
- "ERROR 2020-08-25T20:38:36.895321 \r progress bar\n"
Returns:
A 2-tuple of strings.
First str is prefix, either "ERROR {timestamp} " or "{timestamp} ".
Second str is the rest of the string.
Example:
>>> chunk = Chunk(filename="output.log", data="ERROR 2020-08-25T20:38 this is my line of text\n")
>>> split_chunk(chunk)
("ERROR 2020-08-25T20:38 ", "this is my line of text\n")
"""
prefix = ""
token, rest = chunk.data.split(" ", 1)
if token == "ERROR":
prefix += token + " "
token, rest = rest.split(" ", 1)
prefix += token + " "
return prefix, rest | python | wandb/sdk/internal/file_stream.py | 179 | 208 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,513 | process_chunks | def process_chunks(self, chunks: List) -> List["ProcessedChunk"]:
r"""Process chunks.
Args:
chunks: List of Chunk objects. See description of chunk above in `split_chunk(...)`.
Returns:
List[Dict]. Each dict in the list contains two keys: an `offset` which holds the line number
and `content` which maps to a list of consecutive lines starting from that offset.
`offset` here means global line number in our console on the UI.
Example:
>>> chunks = [
Chunk("output.log", "ERROR 2020-08-25T20:38 this is my line of text\nboom\n"),
Chunk("output.log", "2020-08-25T20:38 this is test\n"),
]
>>> process_chunks(chunks)
[
{"offset": 0, "content": [
"ERROR 2020-08-25T20:38 this is my line of text\n",
"ERROR 2020-08-25T20:38 boom\n",
"2020-08-25T20:38 this is test\n"
]
}
]
"""
# Dict[int->str], each offset (line number) mapped to a line.
# Represents a mini-version of our console pane on the UI.
console = {}
sep = os.linesep
for c in chunks:
prefix, logs_str = self.split_chunk(c)
logs = logs_str.split(sep)
for line in logs:
stream = self.stderr if prefix.startswith("ERROR ") else self.stdout
if line.startswith("\r"):
# line starting with \r will always overwrite a previous offset.
offset: int = (
stream.cr
if (stream.found_cr and stream.cr is not None)
else (stream.last_normal or 0)
)
stream.cr = offset
stream.found_cr = True
console[offset] = prefix + line[1:] + "\n"
# Usually logs_str = "\r progress bar\n" for progress bar updates.
# If instead logs_str = "\r progress bar\n text\n text\n",
# treat this as the end of a progress bar and reset accordingly.
if (
logs_str.count(sep) > 1
and logs_str.replace(sep, "").count("\r") == 1
):
stream.found_cr = False
elif line:
console[self.global_offset] = prefix + line + "\n"
stream.last_normal = self.global_offset
self.global_offset += 1
intervals = self.get_consecutive_offsets(console)
ret = []
for a, b in intervals:
processed_chunk: "ProcessedChunk" = {
"offset": a,
"content": [console[i] for i in range(a, b + 1)],
}
ret.append(processed_chunk)
return ret | python | wandb/sdk/internal/file_stream.py | 210 | 280 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,514 | __init__ | def __init__(self) -> None:
super().__init__()
self._offset: int = 0 | python | wandb/sdk/internal/file_stream.py | 284 | 286 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,515 | process_chunks | def process_chunks(self, chunks: List[Chunk]) -> "ProcessedBinaryChunk":
data = b"".join([c.data for c in chunks])
enc = base64.b64encode(data).decode("ascii")
self._offset += len(data)
return {"offset": self._offset, "content": enc, "encoding": "base64"} | python | wandb/sdk/internal/file_stream.py | 288 | 292 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,516 | __init__ | def __init__(
self,
api: "internal_api.Api",
run_id: str,
start_time: float,
settings: Optional[dict] = None,
) -> None:
settings = settings or dict()
# NOTE: exc_info is set in thread_except_body context and readable by calling threads
self._exc_info: Optional[
Union[
Tuple[Type[BaseException], BaseException, TracebackType],
Tuple[None, None, None],
]
] = None
self._settings = settings
self._api = api
self._run_id = run_id
self._start_time = start_time
self._client = requests.Session()
# todo: actually use the timeout once more thorough error injection in testing covers it
# self._client.post = functools.partial(self._client.post, timeout=self.HTTP_TIMEOUT)
self._client.auth = ("api", api.api_key or "")
self._client.headers.update(
{
"User-Agent": api.user_agent,
"X-WANDB-USERNAME": env.get_username() or "",
"X-WANDB-USER-EMAIL": env.get_user_email() or "",
}
)
self._file_policies: Dict[str, "DefaultFilePolicy"] = {}
self._dropped_chunks: int = 0
self._queue: queue.Queue = queue.Queue()
self._thread = threading.Thread(target=self._thread_except_body)
# It seems we need to make this a daemon thread to get sync.py's atexit handler to run, which
# cleans this thread up.
self._thread.name = "FileStreamThread"
self._thread.daemon = True
self._init_endpoint() | python | wandb/sdk/internal/file_stream.py | 317 | 355 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,517 | _init_endpoint | def _init_endpoint(self) -> None:
settings = self._api.settings()
settings.update(self._settings)
self._endpoint = "{base}/files/{entity}/{project}/{run}/file_stream".format(
base=settings["base_url"],
entity=settings["entity"],
project=settings["project"],
run=self._run_id,
) | python | wandb/sdk/internal/file_stream.py | 357 | 365 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,518 | start | def start(self) -> None:
self._init_endpoint()
self._thread.start() | python | wandb/sdk/internal/file_stream.py | 367 | 369 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,519 | set_default_file_policy | def set_default_file_policy(
self, filename: str, file_policy: "DefaultFilePolicy"
) -> None:
"""Set an upload policy for a file unless one has already been set."""
if filename not in self._file_policies:
self._file_policies[filename] = file_policy | python | wandb/sdk/internal/file_stream.py | 371 | 376 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,520 | set_file_policy | def set_file_policy(self, filename: str, file_policy: "DefaultFilePolicy") -> None:
self._file_policies[filename] = file_policy | python | wandb/sdk/internal/file_stream.py | 378 | 379 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,521 | heartbeat_seconds | def heartbeat_seconds(self) -> Union[int, float]:
# Defaults to 30
heartbeat_seconds: Union[int, float] = self._api.dynamic_settings[
"heartbeat_seconds"
]
return heartbeat_seconds | python | wandb/sdk/internal/file_stream.py | 382 | 387 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,522 | rate_limit_seconds | def rate_limit_seconds(self) -> Union[int, float]:
run_time = time.time() - self._start_time
if run_time < 60:
return max(1.0, self.heartbeat_seconds / 15)
elif run_time < 300:
return max(2.5, self.heartbeat_seconds / 3)
else:
return max(5.0, self.heartbeat_seconds) | python | wandb/sdk/internal/file_stream.py | 389 | 396 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,523 | _read_queue | def _read_queue(self) -> List:
# called from the push thread (_thread_body), this does an initial read
# that'll block for up to rate_limit_seconds. Then it tries to read
# as much out of the queue as it can. We do this because the http post
# to the server happens within _thread_body, and can take longer than
# our rate limit. So next time we get a chance to read the queue we want
# read all the stuff that queue'd up since last time.
#
# If we have more than MAX_ITEMS_PER_PUSH in the queue then the push thread
# will get behind and data will buffer up in the queue.
return util.read_many_from_queue(
self._queue, self.MAX_ITEMS_PER_PUSH, self.rate_limit_seconds()
) | python | wandb/sdk/internal/file_stream.py | 398 | 410 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,524 | _thread_body | def _thread_body(self) -> None:
posted_data_time = time.time()
posted_anything_time = time.time()
ready_chunks = []
uploaded: Set[str] = set()
finished: Optional["FileStreamApi.Finish"] = None
while finished is None:
items = self._read_queue()
for item in items:
if isinstance(item, self.Finish):
finished = item
elif isinstance(item, self.Preempting):
request_with_retry(
self._client.post,
self._endpoint,
json={
"complete": False,
"preempting": True,
"dropped": self._dropped_chunks,
"uploaded": list(uploaded),
},
)
uploaded = set()
elif isinstance(item, self.PushSuccess):
uploaded.add(item.save_name)
else:
# item is Chunk
ready_chunks.append(item)
cur_time = time.time()
if ready_chunks and (
finished or cur_time - posted_data_time > self.rate_limit_seconds()
):
posted_data_time = cur_time
posted_anything_time = cur_time
success = self._send(ready_chunks, uploaded=uploaded)
ready_chunks = []
if success:
uploaded = set()
# If there aren't ready chunks or uploaded files, we still want to
# send regular heartbeats so the backend doesn't erroneously mark this
# run as crashed.
if cur_time - posted_anything_time > self.heartbeat_seconds:
posted_anything_time = cur_time
# If we encountered an error trying to publish the
# list of uploaded files, don't reset the `uploaded`
# list. Retry publishing the list on the next attempt.
if not isinstance(
request_with_retry(
self._client.post,
self._endpoint,
json={
"complete": False,
"failed": False,
"dropped": self._dropped_chunks,
"uploaded": list(uploaded),
},
),
Exception,
):
uploaded = set()
# post the final close message. (item is self.Finish instance now)
request_with_retry(
self._client.post,
self._endpoint,
json={
"complete": True,
"exitcode": int(finished.exitcode),
"dropped": self._dropped_chunks,
"uploaded": list(uploaded),
},
) | python | wandb/sdk/internal/file_stream.py | 412 | 487 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,525 | _thread_except_body | def _thread_except_body(self) -> None:
# TODO: Consolidate with internal_util.ExceptionThread
try:
self._thread_body()
except Exception as e:
exc_info = sys.exc_info()
self._exc_info = exc_info
logger.exception("generic exception in filestream thread")
wandb._sentry.exception(exc_info)
raise e | python | wandb/sdk/internal/file_stream.py | 489 | 498 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,526 | _handle_response | def _handle_response(self, response: Union[Exception, "requests.Response"]) -> None:
"""Log dropped chunks and updates dynamic settings."""
if isinstance(response, Exception):
wandb.termerror(
"Dropped streaming file chunk (see wandb/debug-internal.log)"
)
logging.exception("dropped chunk %s" % response)
self._dropped_chunks += 1
else:
parsed: Optional[dict] = None
try:
parsed = response.json()
except Exception:
pass
if isinstance(parsed, dict):
limits = parsed.get("limits")
if isinstance(limits, dict):
self._api.dynamic_settings.update(limits) | python | wandb/sdk/internal/file_stream.py | 500 | 517 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,527 | _send | def _send(self, chunks: List[Chunk], uploaded: Optional[Set[str]] = None) -> bool:
uploaded_list = list(uploaded or [])
# create files dict. dict of <filename: chunks> pairs where chunks are a list of
# [chunk_id, chunk_data] tuples (as lists since this will be json).
files = {}
# Groupby needs group keys to be consecutive, so sort first.
chunks.sort(key=lambda c: c.filename)
for filename, file_chunks in itertools.groupby(chunks, lambda c: c.filename):
file_chunks_list = list(file_chunks) # groupby returns iterator
# Specific file policies are set by internal/sender.py
self.set_default_file_policy(filename, DefaultFilePolicy())
files[filename] = self._file_policies[filename].process_chunks(
file_chunks_list
)
if not files[filename]:
del files[filename]
for fs in file_stream_utils.split_files(files, max_bytes=util.MAX_LINE_BYTES):
self._handle_response(
request_with_retry(
self._client.post,
self._endpoint,
json={"files": fs, "dropped": self._dropped_chunks},
retry_callback=self._api.retry_callback,
)
)
if uploaded_list:
if isinstance(
request_with_retry(
self._client.post,
self._endpoint,
json={
"complete": False,
"failed": False,
"dropped": self._dropped_chunks,
"uploaded": uploaded_list,
},
),
Exception,
):
return False
return True | python | wandb/sdk/internal/file_stream.py | 519 | 561 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,528 | stream_file | def stream_file(self, path: str) -> None:
name = path.split("/")[-1]
with open(path) as f:
self._send([Chunk(name, line) for line in f]) | python | wandb/sdk/internal/file_stream.py | 563 | 566 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,529 | enqueue_preempting | def enqueue_preempting(self) -> None:
self._queue.put(self.Preempting()) | python | wandb/sdk/internal/file_stream.py | 568 | 569 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,530 | push | def push(self, filename: str, data: Any) -> None:
"""Push a chunk of a file to the streaming endpoint.
Arguments:
filename: Name of file that this is a chunk of.
data: File data.
"""
self._queue.put(Chunk(filename, data)) | python | wandb/sdk/internal/file_stream.py | 571 | 578 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,531 | push_success | def push_success(self, artifact_id: str, save_name: str) -> None:
"""Notification that a file upload has been successfully completed.
Arguments:
artifact_id: ID of artifact
save_name: saved name of the uploaded file
"""
self._queue.put(self.PushSuccess(artifact_id, save_name)) | python | wandb/sdk/internal/file_stream.py | 580 | 587 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,532 | finish | def finish(self, exitcode: int) -> None:
"""Clean up.
Anything pushed after finish will be dropped.
Arguments:
exitcode: The exitcode of the watched process.
"""
self._queue.put(self.Finish(exitcode))
# TODO(jhr): join on a thread which exited with an exception is a noop, clean up this path
self._thread.join()
if self._exc_info:
logger.error("FileStream exception", exc_info=self._exc_info)
# re-raising the original exception, will get re-caught in internal.py for the sender thread
if self._exc_info[1] is not None:
raise self._exc_info[1].with_traceback(self._exc_info[2]) | python | wandb/sdk/internal/file_stream.py | 589 | 604 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,533 | request_with_retry | def request_with_retry(
func: Callable,
*args: Any,
**kwargs: Any,
) -> Union["requests.Response", "requests.RequestException"]:
"""Perform a requests http call, retrying with exponential backoff.
Arguments:
func: An http-requesting function to call, like requests.post
max_retries: Maximum retries before giving up.
By default, we retry 30 times in ~2 hours before dropping the chunk
*args: passed through to func
**kwargs: passed through to func
"""
max_retries: int = kwargs.pop("max_retries", 30)
retry_callback: Optional[Callable] = kwargs.pop("retry_callback", None)
sleep = 2
retry_count = 0
while True:
try:
response: "requests.Response" = func(*args, **kwargs)
response.raise_for_status()
return response
except (
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
requests.exceptions.Timeout,
) as e:
if isinstance(e, requests.exceptions.HTTPError):
# Non-retriable HTTP errors.
#
# We retry 500s just to be cautious, and because the back end
# returns them when there are infrastructure issues. If retrying
# some request winds up being problematic, we'll change the
# back end to indicate that it shouldn't be retried.
if e.response is not None and e.response.status_code in {
400,
403,
404,
409,
}:
return e
if retry_count == max_retries:
return e
retry_count += 1
delay = sleep + random.random() * 0.25 * sleep
if isinstance(e, requests.exceptions.HTTPError) and (
e.response is not None and e.response.status_code == 429
):
err_str = (
"Filestream rate limit exceeded, retrying in {} seconds".format(
delay
)
)
if retry_callback:
retry_callback(e.response.status_code, err_str)
logger.info(err_str)
else:
pass
logger.warning(
"requests_with_retry encountered retryable exception: %s. func: %s, args: %s, kwargs: %s",
e,
func,
args,
kwargs,
)
time.sleep(delay)
sleep *= 2
if sleep > MAX_SLEEP_SECONDS:
sleep = MAX_SLEEP_SECONDS
except requests.exceptions.RequestException as e:
error_message = "unknown error"
try:
error_message = response.json()["error"] # todo: clean this up
except Exception:
pass
logger.error(f"requests_with_retry error: {error_message}")
logger.exception(
"requests_with_retry encountered unretryable exception: %s", e
)
return e | python | wandb/sdk/internal/file_stream.py | 610 | 691 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,534 | __init__ | def __init__(self, min_samples=None):
self._samples = min_samples or 64
# force power of 2 samples
self._samples = 2 ** int(math.ceil(math.log(self._samples, 2)))
# target oversample by factor of 2
self._samples2 = self._samples * 2
# max size of each buffer
self._max = self._samples2 // 2
self._shift = 0
self._mask = (1 << self._shift) - 1
self._buckets = int(math.log(self._samples2, 2))
self._buckets_bits = int(math.log(self._buckets, 2))
self._buckets_mask = (1 << self._buckets_bits + 1) - 1
self._buckets_index = 0
self._bucket = []
self._index = [0] * self._buckets
self._count = 0
self._log2 = [0]
# pre-allocate buckets
for _ in range(self._buckets):
self._bucket.append([0] * self._max)
# compute integer log2
self._log2 += [int(math.log(i, 2)) for i in range(1, 2**self._buckets + 1)] | python | wandb/sdk/internal/sample.py | 7 | 30 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,535 | _show | def _show(self):
print("=" * 20)
for b in range(self._buckets):
b = (b + self._buckets_index) % self._buckets
vals = [self._bucket[b][i] for i in range(self._index[b])]
print(f"{b}: {vals}") | python | wandb/sdk/internal/sample.py | 32 | 37 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,536 | add | def add(self, val):
self._count += 1
cnt = self._count
if cnt & self._mask:
return
b = cnt >> self._shift
b = self._log2[b] # b = int(math.log(b, 2))
if b >= self._buckets:
self._index[self._buckets_index] = 0
self._buckets_index = (self._buckets_index + 1) % self._buckets
self._shift += 1
self._mask = (self._mask << 1) | 1
b += self._buckets - 1
b = (b + self._buckets_index) % self._buckets
self._bucket[b][self._index[b]] = val
self._index[b] += 1 | python | wandb/sdk/internal/sample.py | 39 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,537 | get | def get(self):
full = []
sampled = []
# self._show()
for b in range(self._buckets):
max_num = 2**b
b = (b + self._buckets_index) % self._buckets
modb = self._index[b] // max_num
for i in range(self._index[b]):
if not modb or i % modb == 0:
sampled.append(self._bucket[b][i])
full.append(self._bucket[b][i])
if len(sampled) < self._samples:
return tuple(full)
return tuple(sampled) | python | wandb/sdk/internal/sample.py | 56 | 70 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,538 | __init__ | def __init__(
self,
settings: SettingsStatic,
record_q: "Queue[pb.Record]",
result_q: "Queue[pb.Result]",
sender_q: "Queue[pb.Record]",
interface: InterfaceQueue,
context_keeper: context.ContextKeeper,
):
self._settings = settings
self._record_q = record_q
self._result_q = result_q
self._sender_q = sender_q
self._interface = interface
self._context_keeper = context_keeper
# TODO(cancel_paused): implement me
# self._sender_cancel_set = set()
self._ds = None
self._flow_control = None
self._status_report = None
self._record_num = 0
self._telemetry_obj = tpb.TelemetryRecord()
self._telemetry_overflow = False
self._use_flow_control = not (
self._settings._flow_control_disabled or self._settings._offline
) | python | wandb/sdk/internal/writer.py | 40 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,539 | open | def open(self) -> None:
self._ds = datastore.DataStore()
self._ds.open_for_write(self._settings.sync_file)
self._flow_control = flow_control.FlowControl(
settings=self._settings,
write_record=self._write_record,
forward_record=self._forward_record,
pause_marker=self._pause_marker,
recover_records=self._recover_records,
) | python | wandb/sdk/internal/writer.py | 69 | 78 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,540 | _forward_record | def _forward_record(self, record: "pb.Record") -> None:
self._context_keeper.add_from_record(record)
tracelog.log_message_queue(record, self._sender_q)
self._sender_q.put(record) | python | wandb/sdk/internal/writer.py | 80 | 83 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,541 | _send_mark | def _send_mark(self) -> None:
sender_mark = pb.SenderMarkRequest()
record = self._interface._make_request(sender_mark=sender_mark)
self._forward_record(record) | python | wandb/sdk/internal/writer.py | 85 | 88 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,542 | _maybe_send_telemetry | def _maybe_send_telemetry(self) -> None:
if self._telemetry_overflow:
return
self._telemetry_overflow = True
with telemetry.context(obj=self._telemetry_obj) as tel:
tel.feature.flow_control_overflow = True
telemetry_record = pb.TelemetryRecordRequest(telemetry=self._telemetry_obj)
record = self._interface._make_request(telemetry_record=telemetry_record)
self._forward_record(record) | python | wandb/sdk/internal/writer.py | 90 | 98 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,543 | _pause_marker | def _pause_marker(self) -> None:
self._maybe_send_telemetry()
self._send_mark() | python | wandb/sdk/internal/writer.py | 100 | 102 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,544 | _write_record | def _write_record(self, record: "pb.Record") -> int:
assert self._ds
self._record_num += 1
proto_util._assign_record_num(record, self._record_num)
ret = self._ds.write(record)
assert ret is not None
_start_offset, end_offset, _flush_offset = ret
proto_util._assign_end_offset(record, end_offset)
return end_offset | python | wandb/sdk/internal/writer.py | 104 | 114 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,545 | _ensure_flushed | def _ensure_flushed(self, offset: int) -> None:
if self._ds:
self._ds.ensure_flushed(offset) | python | wandb/sdk/internal/writer.py | 116 | 118 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,546 | _recover_records | def _recover_records(self, start: int, end: int) -> None:
sender_read = pb.SenderReadRequest(start_offset=start, final_offset=end)
# TODO(cancel_paused): implement me
# for cancel_id in self._sender_cancel_set:
# sender_read.cancel_list.append(cancel_id)
record = self._interface._make_request(sender_read=sender_read)
self._ensure_flushed(end)
self._forward_record(record) | python | wandb/sdk/internal/writer.py | 120 | 127 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,547 | _write | def _write(self, record: "pb.Record") -> None:
if not self._ds:
self.open()
assert self._flow_control
if not record.control.local:
self._write_record(record)
if self._use_flow_control:
self._flow_control.flow(record)
elif not self._settings._offline or record.control.always_send:
# when flow_control is disabled we pass through all records to
# the sender as long as we are online. The exception is there
# are special records that we always pass to the sender
# (namely the exit record so we can trigger the defer shutdown
# state machine)
self._forward_record(record) | python | wandb/sdk/internal/writer.py | 129 | 145 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,548 | write | def write(self, record: "pb.Record") -> None:
record_type = record.WhichOneof("record_type")
assert record_type
writer_str = "write_" + record_type
write_handler: Callable[["pb.Record"], None] = getattr(
self, writer_str, self._write
)
write_handler(record) | python | wandb/sdk/internal/writer.py | 147 | 154 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,549 | write_request | def write_request(self, record: "pb.Record") -> None:
request_type = record.request.WhichOneof("request_type")
assert request_type
write_request_str = "write_request_" + request_type
write_request_handler: Optional[Callable[["pb.Record"], None]] = getattr(
self, write_request_str, None
)
if write_request_handler:
return write_request_handler(record)
self._write(record) | python | wandb/sdk/internal/writer.py | 156 | 165 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,550 | write_request_run_status | def write_request_run_status(self, record: "pb.Record") -> None:
result = proto_util._result_from_record(record)
if self._status_report:
result.response.run_status_response.sync_time.CopyFrom(
self._status_report.sync_time
)
send_record_num = self._status_report.record_num
result.response.run_status_response.sync_items_total = self._record_num
result.response.run_status_response.sync_items_pending = (
self._record_num - send_record_num
)
self._respond_result(result) | python | wandb/sdk/internal/writer.py | 167 | 178 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,551 | write_request_status_report | def write_request_status_report(self, record: "pb.Record") -> None:
self._status_report = record.request.status_report
self._write(record) | python | wandb/sdk/internal/writer.py | 180 | 182 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,552 | write_request_cancel | def write_request_cancel(self, record: "pb.Record") -> None:
cancel_id = record.request.cancel.cancel_slot
self._context_keeper.cancel(cancel_id)
# TODO(cancel_paused): implement me
# cancelled = self._context_keeper.cancel(cancel_id)
# if not cancelled:
# self._sender_cancel_set.add(cancel_id) | python | wandb/sdk/internal/writer.py | 184 | 191 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,553 | _respond_result | def _respond_result(self, result: "pb.Result") -> None:
tracelog.log_message_queue(result, self._result_q)
self._result_q.put(result) | python | wandb/sdk/internal/writer.py | 193 | 195 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,554 | finish | def finish(self) -> None:
if self._flow_control:
self._flow_control.flush()
if self._ds:
self._ds.close()
# TODO(debug_context) see context.py
# self._context_keeper._debug_print_orphans(print_to_stdout=self._settings._debug) | python | wandb/sdk/internal/writer.py | 197 | 203 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,555 | debounce | def debounce(self) -> None:
pass | python | wandb/sdk/internal/writer.py | 205 | 206 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,556 | __init__ | def __init__(
self,
api: "internal_api.Api",
file_stream: "file_stream.FileStreamApi",
settings: Optional["SettingsStatic"] = None,
) -> None:
self._api = api
self._tempdir = tempfile.TemporaryDirectory("wandb")
self._stats = stats.Stats()
self._incoming_queue: "queue.Queue[step_checksum.Event]" = queue.Queue()
self._event_queue: "queue.Queue[step_upload.Event]" = queue.Queue()
self._step_checksum = step_checksum.StepChecksum(
self._api,
self._tempdir,
self._incoming_queue,
self._event_queue,
self._stats,
)
self._step_checksum.start()
self._step_upload = step_upload.StepUpload(
self._api,
self._stats,
self._event_queue,
self.MAX_UPLOAD_JOBS,
file_stream=file_stream,
settings=settings,
)
self._step_upload.start() | python | wandb/sdk/internal/file_pusher.py | 40 | 72 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,557 | get_status | def get_status(self) -> Tuple[bool, stats.Summary]:
running = self.is_alive()
summary = self._stats.summary()
return running, summary | python | wandb/sdk/internal/file_pusher.py | 74 | 77 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,558 | print_status | def print_status(self, prefix: bool = True) -> None:
step = 0
spinner_states = ["-", "\\", "|", "/"]
stop = False
while True:
if not self.is_alive():
stop = True
summary = self._stats.summary()
line = " {:.2f}MB of {:.2f}MB uploaded ({:.2f}MB deduped)\r".format(
summary.uploaded_bytes / 1048576.0,
summary.total_bytes / 1048576.0,
summary.deduped_bytes / 1048576.0,
)
line = spinner_states[step % 4] + line
step += 1
wandb.termlog(line, newline=False, prefix=prefix)
if stop:
break
time.sleep(0.25)
dedupe_fraction = (
summary.deduped_bytes / float(summary.total_bytes)
if summary.total_bytes > 0
else 0
)
if dedupe_fraction > 0.01:
wandb.termlog(
"W&B sync reduced upload amount by %.1f%% "
% (dedupe_fraction * 100),
prefix=prefix,
)
# clear progress line.
wandb.termlog(" " * 79, prefix=prefix) | python | wandb/sdk/internal/file_pusher.py | 79 | 110 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,559 | file_counts_by_category | def file_counts_by_category(self) -> stats.FileCountsByCategory:
return self._stats.file_counts_by_category() | python | wandb/sdk/internal/file_pusher.py | 112 | 113 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,560 | file_changed | def file_changed(
self,
save_name: dir_watcher.SaveName,
path: str,
copy: bool = True,
):
"""Tell the file pusher that a file's changed and should be uploaded.
Arguments:
save_name: string logical location of the file relative to the run
directory.
path: actual string path of the file to upload on the filesystem.
"""
# Tests in linux were failing because wandb-events.jsonl didn't exist
if not os.path.exists(path) or not os.path.isfile(path):
return
if os.path.getsize(path) == 0:
return
save_name = dir_watcher.SaveName(wandb.util.to_forward_slash_path(save_name))
event = step_checksum.RequestUpload(
path,
dir_watcher.SaveName(save_name),
copy,
)
self._incoming_queue.put(event) | python | wandb/sdk/internal/file_pusher.py | 115 | 140 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,561 | store_manifest_files | def store_manifest_files(
self,
manifest: "artifacts.ArtifactManifest",
artifact_id: str,
save_fn: "internal_artifacts.SaveFn",
save_fn_async: "internal_artifacts.SaveFnAsync",
) -> None:
event = step_checksum.RequestStoreManifestFiles(
manifest, artifact_id, save_fn, save_fn_async
)
self._incoming_queue.put(event) | python | wandb/sdk/internal/file_pusher.py | 142 | 152 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,562 | commit_artifact | def commit_artifact(
self,
artifact_id: str,
*,
finalize: bool = True,
before_commit: step_upload.PreCommitFn,
result_future: "concurrent.futures.Future[None]",
):
event = step_checksum.RequestCommitArtifact(
artifact_id, finalize, before_commit, result_future
)
self._incoming_queue.put(event) | python | wandb/sdk/internal/file_pusher.py | 154 | 165 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,563 | finish | def finish(self, callback: Optional[step_upload.OnRequestFinishFn] = None):
logger.info("shutting down file pusher")
self._incoming_queue.put(step_checksum.RequestFinish(callback)) | python | wandb/sdk/internal/file_pusher.py | 167 | 169 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,564 | join | def join(self) -> None:
# NOTE: must have called finish before join
logger.info("waiting for file pusher")
while self.is_alive():
time.sleep(0.5) | python | wandb/sdk/internal/file_pusher.py | 171 | 175 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,565 | is_alive | def is_alive(self) -> bool:
return self._step_checksum.is_alive() or self._step_upload.is_alive() | python | wandb/sdk/internal/file_pusher.py | 177 | 178 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,566 | __call__ | def __call__(
self, entry: ArtifactManifestEntry, progress_callback: "ProgressFn"
) -> bool:
pass | python | wandb/sdk/internal/artifacts.py | 28 | 31 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,567 | __call__ | def __call__(
self, entry: ArtifactManifestEntry, progress_callback: "ProgressFn"
) -> Awaitable[bool]:
pass | python | wandb/sdk/internal/artifacts.py | 34 | 37 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,568 | __init__ | def __init__(
self,
api: "InternalApi",
digest: str,
manifest_json: Dict,
file_pusher: "FilePusher",
is_user_created: bool = False,
) -> None:
self._api = api
self._file_pusher = file_pusher
self._digest = digest
self._manifest = ArtifactManifest.from_manifest_json(manifest_json)
self._is_user_created = is_user_created
self._server_artifact = None | python | wandb/sdk/internal/artifacts.py | 43 | 56 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,569 | save | def save(
self,
type: str,
name: str,
client_id: str,
sequence_client_id: str,
distributed_id: Optional[str] = None,
finalize: bool = True,
metadata: Optional[Dict] = None,
description: Optional[str] = None,
aliases: Optional[Sequence[str]] = None,
labels: Optional[List[str]] = None,
use_after_commit: bool = False,
incremental: bool = False,
history_step: Optional[int] = None,
) -> Optional[Dict]:
try:
return self._save_internal(
type,
name,
client_id,
sequence_client_id,
distributed_id,
finalize,
metadata,
description,
aliases,
labels,
use_after_commit,
incremental,
history_step,
)
finally:
self._cleanup_staged_entries() | python | wandb/sdk/internal/artifacts.py | 58 | 91 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,570 | _save_internal | def _save_internal(
self,
type: str,
name: str,
client_id: str,
sequence_client_id: str,
distributed_id: Optional[str] = None,
finalize: bool = True,
metadata: Optional[Dict] = None,
description: Optional[str] = None,
aliases: Optional[Sequence[str]] = None,
labels: Optional[List[str]] = None,
use_after_commit: bool = False,
incremental: bool = False,
history_step: Optional[int] = None,
) -> Optional[Dict]:
aliases = aliases or []
alias_specs = []
for alias in aliases:
if ":" in alias:
# Users can explicitly alias this artifact to names
# other than the primary one passed in by using the
# 'secondaryName:alias' notation.
idx = alias.index(":")
artifact_collection_name = alias[: idx - 1]
tag = alias[idx + 1 :]
else:
artifact_collection_name = name
tag = alias
alias_specs.append(
{
"artifactCollectionName": artifact_collection_name,
"alias": tag,
}
)
"""Returns the server artifact."""
self._server_artifact, latest = self._api.create_artifact(
type,
name,
self._digest,
metadata=metadata,
aliases=alias_specs,
labels=labels,
description=description,
is_user_created=self._is_user_created,
distributed_id=distributed_id,
client_id=client_id,
sequence_client_id=sequence_client_id,
enable_digest_deduplication=use_after_commit, # Reuse logical duplicates in the `use_artifact` flow
history_step=history_step,
)
# TODO(artifacts):
# if it's committed, all is good. If it's committing, just moving ahead isn't necessarily
# correct. It may be better to poll until it's committed or failed, and then decided what to
# do
assert self._server_artifact is not None # mypy optionality unwrapper
artifact_id = self._server_artifact["id"]
latest_artifact_id = latest["id"] if latest else None
if (
self._server_artifact["state"] == "COMMITTED"
or self._server_artifact["state"] == "COMMITTING"
):
# TODO: update aliases, labels, description etc?
if use_after_commit:
self._api.use_artifact(artifact_id)
return self._server_artifact
elif (
self._server_artifact["state"] != "PENDING"
and self._server_artifact["state"] != "DELETED"
):
raise Exception(
'Unknown artifact state "{}"'.format(self._server_artifact["state"])
)
manifest_type = "FULL"
manifest_filename = "wandb_manifest.json"
if incremental:
manifest_type = "INCREMENTAL"
manifest_filename = "wandb_manifest.incremental.json"
elif distributed_id:
manifest_type = "PATCH"
manifest_filename = "wandb_manifest.patch.json"
artifact_manifest_id, _ = self._api.create_artifact_manifest(
manifest_filename,
"",
artifact_id,
base_artifact_id=latest_artifact_id,
include_upload=False,
type=manifest_type,
)
step_prepare = wandb.filesync.step_prepare.StepPrepare(
self._api, 0.1, 0.01, 1000
) # TODO: params
step_prepare.start()
# Upload Artifact "L1" files, the actual artifact contents
self._file_pusher.store_manifest_files(
self._manifest,
artifact_id,
lambda entry, progress_callback: self._manifest.storage_policy.store_file_sync(
artifact_id,
artifact_manifest_id,
entry,
step_prepare,
progress_callback=progress_callback,
),
lambda entry, progress_callback: self._manifest.storage_policy.store_file_async(
artifact_id,
artifact_manifest_id,
entry,
step_prepare,
progress_callback=progress_callback,
),
)
def before_commit() -> None:
self._resolve_client_id_manifest_references()
with tempfile.NamedTemporaryFile("w+", suffix=".json", delete=False) as fp:
path = os.path.abspath(fp.name)
json.dump(self._manifest.to_manifest_json(), fp, indent=4)
digest = md5_file_b64(path)
if distributed_id or incremental:
# If we're in the distributed flow, we want to update the
# patch manifest we created with our finalized digest.
_, resp = self._api.update_artifact_manifest(
artifact_manifest_id,
digest=digest,
)
else:
# In the regular flow, we can recreate the full manifest with the
# updated digest.
#
# NOTE: We do this for backwards compatibility with older backends
# that don't support the 'updateArtifactManifest' API.
_, resp = self._api.create_artifact_manifest(
manifest_filename,
digest,
artifact_id,
base_artifact_id=latest_artifact_id,
)
# We're duplicating the file upload logic a little, which isn't great.
upload_url = resp["uploadUrl"]
upload_headers = resp["uploadHeaders"]
extra_headers = {}
for upload_header in upload_headers:
key, val = upload_header.split(":", 1)
extra_headers[key] = val
with open(path, "rb") as fp2:
self._api.upload_file_retry(
upload_url,
fp2,
extra_headers=extra_headers,
)
commit_result: "concurrent.futures.Future[None]" = concurrent.futures.Future()
# This will queue the commit. It will only happen after all the file uploads are done
self._file_pusher.commit_artifact(
artifact_id,
finalize=finalize,
before_commit=before_commit,
result_future=commit_result,
)
# Block until all artifact files are uploaded and the
# artifact is committed.
try:
commit_result.result()
finally:
step_prepare.shutdown()
if finalize and use_after_commit:
self._api.use_artifact(artifact_id)
return self._server_artifact | python | wandb/sdk/internal/artifacts.py | 93 | 271 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,571 | before_commit | def before_commit() -> None:
self._resolve_client_id_manifest_references()
with tempfile.NamedTemporaryFile("w+", suffix=".json", delete=False) as fp:
path = os.path.abspath(fp.name)
json.dump(self._manifest.to_manifest_json(), fp, indent=4)
digest = md5_file_b64(path)
if distributed_id or incremental:
# If we're in the distributed flow, we want to update the
# patch manifest we created with our finalized digest.
_, resp = self._api.update_artifact_manifest(
artifact_manifest_id,
digest=digest,
)
else:
# In the regular flow, we can recreate the full manifest with the
# updated digest.
#
# NOTE: We do this for backwards compatibility with older backends
# that don't support the 'updateArtifactManifest' API.
_, resp = self._api.create_artifact_manifest(
manifest_filename,
digest,
artifact_id,
base_artifact_id=latest_artifact_id,
)
# We're duplicating the file upload logic a little, which isn't great.
upload_url = resp["uploadUrl"]
upload_headers = resp["uploadHeaders"]
extra_headers = {}
for upload_header in upload_headers:
key, val = upload_header.split(":", 1)
extra_headers[key] = val
with open(path, "rb") as fp2:
self._api.upload_file_retry(
upload_url,
fp2,
extra_headers=extra_headers,
) | python | wandb/sdk/internal/artifacts.py | 211 | 249 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,572 | _resolve_client_id_manifest_references | def _resolve_client_id_manifest_references(self) -> None:
for entry_path in self._manifest.entries:
entry = self._manifest.entries[entry_path]
if entry.ref is not None:
if entry.ref.startswith("wandb-client-artifact:"):
client_id = util.host_from_path(entry.ref)
artifact_file_path = util.uri_from_path(entry.ref)
artifact_id = self._api._resolve_client_id(client_id)
if artifact_id is None:
raise RuntimeError(f"Could not resolve client id {client_id}")
entry.ref = util.URIStr(
"wandb-artifact://{}/{}".format(
b64_to_hex_id(B64MD5(artifact_id)), artifact_file_path
)
) | python | wandb/sdk/internal/artifacts.py | 273 | 287 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,573 | _cleanup_staged_entries | def _cleanup_staged_entries(self) -> None:
"""Remove all staging copies of local files.
We made a staging copy of each local file to freeze it at "add" time.
We need to delete them once we've uploaded the file or confirmed we
already have a committed copy.
"""
staging_dir = get_staging_dir()
for entry in self._manifest.entries.values():
if entry.local_path and entry.local_path.startswith(staging_dir):
try:
os.remove(entry.local_path)
except OSError:
pass | python | wandb/sdk/internal/artifacts.py | 289 | 302 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,574 | get_staging_dir | def get_staging_dir() -> FilePathStr:
path = os.path.join(env.get_data_dir(), "artifacts", "staging")
try:
mkdir_exists_ok(path)
except OSError as e:
raise PermissionError(
f"Unable to write staging files to {path}. To fix this problem, please set "
f"{env.DATA_DIR} to a directory where you have the necessary write access."
) from e
return FilePathStr(os.path.abspath(os.path.expanduser(path))) | python | wandb/sdk/internal/artifacts.py | 305 | 315 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,575 | __init__ | def __init__(self, stopped: "Event") -> None:
threading.Thread.__init__(self)
self.__stopped = stopped
self.__exception = None | python | wandb/sdk/internal/internal_util.py | 39 | 42 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,576 | _run | def _run(self) -> None:
raise NotImplementedError | python | wandb/sdk/internal/internal_util.py | 44 | 45 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,577 | run | def run(self) -> None:
try:
self._run()
except Exception:
self.__exception = sys.exc_info()
finally:
if self.__exception and self.__stopped:
self.__stopped.set() | python | wandb/sdk/internal/internal_util.py | 47 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,578 | get_exception | def get_exception(self) -> Optional["ExceptionType"]:
return self.__exception | python | wandb/sdk/internal/internal_util.py | 56 | 57 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,579 | __init__ | def __init__(
self,
input_record_q: "Queue[Record]",
result_q: "Queue[Result]",
stopped: "Event",
debounce_interval_ms: "float" = 1000,
) -> None:
ExceptionThread.__init__(self, stopped=stopped)
self._input_record_q = input_record_q
self._result_q = result_q
self._stopped = stopped
self._debounce_interval_ms = debounce_interval_ms | python | wandb/sdk/internal/internal_util.py | 63 | 74 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,580 | _setup | def _setup(self) -> None:
raise NotImplementedError | python | wandb/sdk/internal/internal_util.py | 76 | 77 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,581 | _process | def _process(self, record: "Record") -> None:
raise NotImplementedError | python | wandb/sdk/internal/internal_util.py | 79 | 80 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,582 | _finish | def _finish(self) -> None:
raise NotImplementedError | python | wandb/sdk/internal/internal_util.py | 82 | 83 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,583 | _debounce | def _debounce(self) -> None:
raise NotImplementedError | python | wandb/sdk/internal/internal_util.py | 85 | 86 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,584 | _run | def _run(self) -> None:
self._setup()
start = time.time()
while not self._stopped.is_set():
if time.time() - start >= self._debounce_interval_ms / 1000.0:
self._debounce()
start = time.time()
try:
record = self._input_record_q.get(timeout=1)
except queue.Empty:
continue
tracelog.log_message_dequeue(record, self._input_record_q)
self._process(record)
self._finish() | python | wandb/sdk/internal/internal_util.py | 88 | 101 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,585 | __call__ | def __call__(self, new_bytes: int, total_bytes: int) -> None:
pass | python | wandb/sdk/internal/progress.py | 16 | 17 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,586 | __init__ | def __init__(
self, file: IO[bytes], callback: Optional["ProgressFn"] = None
) -> None:
self.file = file
if callback is None:
def callback_(new_bytes: int, total_bytes: int) -> None:
pass
callback = callback_
self.callback: "ProgressFn" = callback
self.bytes_read = 0
self.len = os.fstat(file.fileno()).st_size | python | wandb/sdk/internal/progress.py | 25 | 38 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,587 | callback_ | def callback_(new_bytes: int, total_bytes: int) -> None:
pass | python | wandb/sdk/internal/progress.py | 31 | 32 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,588 | read | def read(self, size=-1):
"""Read bytes and call the callback."""
bites = self.file.read(size)
self.bytes_read += len(bites)
if not bites and self.bytes_read < self.len:
# Files shrinking during uploads causes request timeouts. Maybe
# we could avoid those by updating the self.len in real-time, but
# files getting truncated while uploading seems like something
# that shouldn't really be happening anyway.
raise CommError(
"File {} size shrank from {} to {} while it was being uploaded.".format(
self.file.name, self.len, self.bytes_read
)
)
# Growing files are also likely to be bad, but our code didn't break
# on those in the past so it's riskier to make that an error now.
self.callback(len(bites), self.bytes_read)
return bites | python | wandb/sdk/internal/progress.py | 40 | 57 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,589 | rewind | def rewind(self) -> None:
self.callback(-self.bytes_read, 0)
self.bytes_read = 0
self.file.seek(0) | python | wandb/sdk/internal/progress.py | 59 | 62 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,590 | __getattr__ | def __getattr__(self, name):
"""Fallback to the file object for attrs not defined here."""
if hasattr(self.file, name):
return getattr(self.file, name)
else:
raise AttributeError | python | wandb/sdk/internal/progress.py | 64 | 69 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,591 | __iter__ | def __iter__(self):
return self | python | wandb/sdk/internal/progress.py | 71 | 72 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,592 | __next__ | def __next__(self):
bites = self.read(self.ITER_BYTES)
if len(bites) == 0:
raise StopIteration
return bites | python | wandb/sdk/internal/progress.py | 74 | 78 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,593 | __len__ | def __len__(self):
return self.len | python | wandb/sdk/internal/progress.py | 80 | 81 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,594 | __init__ | def __init__(self, progress: Progress) -> None:
self._progress = progress | python | wandb/sdk/internal/progress.py | 95 | 96 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,595 | __aiter__ | def __aiter__(self):
return self | python | wandb/sdk/internal/progress.py | 98 | 99 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,596 | __anext__ | async def __anext__(self):
try:
return next(self._progress)
except StopIteration:
raise StopAsyncIteration | python | wandb/sdk/internal/progress.py | 101 | 105 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,597 | __len__ | def __len__(self):
return len(self._progress) | python | wandb/sdk/internal/progress.py | 107 | 108 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,598 | rewind | def rewind(self) -> None:
self._progress.rewind() | python | wandb/sdk/internal/progress.py | 110 | 111 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,599 | torch_trace_handler | def torch_trace_handler():
"""Create a trace handler for traces generated by the profiler.
Provide as an argument to `torch.profiler.profile`:
```python
torch.profiler.profile(..., on_trace_ready=wandb.profiler.torch_trace_handler())
```
Calling this function ensures that profiler charts & tables can be viewed in your run dashboard
on wandb.ai.
Please note that `wandb.init()` must be called before this function is invoked.
The PyTorch (torch) version must also be at least 1.9, in order to ensure stability
of their Profiler API.
Args:
None
Returns:
None
Raises:
UsageError if wandb.init() hasn't been called before profiling.
Error if torch version is less than 1.9.0.
Examples:
```python
run = wandb.init()
run.config.id = "profile_code"
with torch.profiler.profile(
schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1),
on_trace_ready=wandb.profiler.torch_trace_handler(),
record_shapes=True,
with_stack=True,
) as prof:
for i, batch in enumerate(dataloader):
if step >= 5:
break
train(batch)
prof.step()
```
"""
from pkg_resources import parse_version
torch = wandb.util.get_module(PYTORCH_MODULE, required=True)
torch_profiler = wandb.util.get_module(PYTORCH_PROFILER_MODULE, required=True)
if parse_version(torch.__version__) < parse_version("1.9.0"):
raise Error(
f"torch version must be at least 1.9 in order to use the PyTorch Profiler API.\
\nVersion of torch currently installed: {torch.__version__}"
)
try:
logdir = os.path.join(wandb.run.dir, "pytorch_traces") # type: ignore
os.mkdir(logdir)
except AttributeError:
raise UsageError(
"Please call `wandb.init()` before `wandb.profiler.torch_trace_handler()`"
) from None
with telemetry.context() as tel:
tel.feature.torch_profiler_trace = True
return torch_profiler.tensorboard_trace_handler(logdir) | python | wandb/sdk/internal/profiler.py | 12 | 77 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,600 | strtobytes | def strtobytes(x):
"""strtobytes."""
return bytes(x, "iso8859-1") | python | wandb/sdk/internal/datastore.py | 52 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.