Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: [LS-2561] Stream compress multipart runs #1316

Merged
merged 57 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
a5efbb8
start of compression
angus-langchain Dec 10, 2024
c10a8ad
manually encode
angus-langchain Dec 10, 2024
d456776
set boundary
angus-langchain Dec 10, 2024
0359235
add zstandard
angus-langchain Dec 10, 2024
08bce98
set limits from config
angus-langchain Dec 10, 2024
800472a
add slots
angus-langchain Dec 10, 2024
d4e45e1
lint
angus-langchain Dec 10, 2024
46c8740
fix mypy
angus-langchain Dec 10, 2024
a5cba8d
implement correct timeouts
angus-langchain Dec 10, 2024
c32cb0c
stream instead of read data from buffer
angus-langchain Dec 10, 2024
2aafc20
fix client type
angus-langchain Dec 10, 2024
03e4e02
separate compressed buffer from tracing queue
angus-langchain Dec 10, 2024
c952536
clean up update multipart
angus-langchain Dec 10, 2024
c3fdd36
address comments
angus-langchain Dec 10, 2024
d6b186d
just write directly to compressor instead of streaming
angus-langchain Dec 10, 2024
f061c0b
set trcing queue to none
angus-langchain Dec 10, 2024
8a0a60e
send multipart req
angus-langchain Dec 10, 2024
b2113ba
remove flush
angus-langchain Dec 11, 2024
982429a
remove print
angus-langchain Dec 11, 2024
5b58940
set compression level
angus-langchain Dec 11, 2024
f2e5ed9
remove prints
angus-langchain Dec 11, 2024
e7dc6bc
pass buffer directly to request
angus-langchain Dec 11, 2024
3ab6b39
resolve conflict
angus-langchain Dec 11, 2024
fb8fa96
lint
angus-langchain Dec 11, 2024
9d0a4ec
my fixes
angus-langchain Dec 11, 2024
f3e7971
black reformatting
angus-langchain Dec 11, 2024
066b9b6
multithreaded compression
angus-langchain Dec 11, 2024
ec15660
add parallel works for sending multipart req
angus-langchain Dec 12, 2024
35e9843
reformatting
angus-langchain Dec 12, 2024
59b5f27
black reformat
angus-langchain Dec 12, 2024
ce44b25
mypy
angus-langchain Dec 12, 2024
181f839
increase payload size to 20mb
angus-langchain Dec 12, 2024
0120dce
use multipart
angus-langchain Dec 12, 2024
e2ada65
use threadpoolexecutor
angus-langchain Dec 12, 2024
25f4f19
fix thread garbage collection
angus-langchain Dec 12, 2024
5b0cca4
add flush method
angus-langchain Dec 12, 2024
f59f7be
return early
angus-langchain Dec 12, 2024
b76e662
lint
angus-langchain Dec 13, 2024
efa4bd6
wait
angus-langchain Dec 13, 2024
0e06bde
signal bg threads data is available instead of sleeping
angus-langchain Dec 13, 2024
f997895
improve buffer checks
angus-langchain Dec 13, 2024
fbc217f
mypy
angus-langchain Dec 13, 2024
7b6c201
Use more threads for backend requests
angus-langchain Dec 19, 2024
35d46ed
fix futures waiting
angus-langchain Dec 19, 2024
dbef2ec
remove unused slot
angus-langchain Dec 19, 2024
6fad596
Flush background threads
angus-langchain Dec 19, 2024
5cc947a
make boundary constant
angus-langchain Dec 19, 2024
d4b2aa4
Remove slot for bool val
angus-langchain Dec 19, 2024
63e55f7
Use a single join() rather than copying the header strings
angus-langchain Dec 19, 2024
874c748
Add zstandard license
angus-langchain Dec 19, 2024
0b3d6b8
lint
angus-langchain Dec 20, 2024
7739939
Create compressed runs object
angus-langchain Dec 20, 2024
3ec9b6e
Make zstd optional
angus-langchain Dec 20, 2024
f9aac67
Make zstandard level configurable
angus-langchain Dec 20, 2024
2ac7a35
mypy ignore optional imports
angus-langchain Dec 20, 2024
3b291c3
lint
angus-langchain Dec 20, 2024
c64fb92
poetry lock
angus-langchain Dec 20, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions python/docs/templates/zstandard/COPYRIGHT.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright (c) 2016, Gregory Szorc

Check notice on line 1 in python/docs/templates/zstandard/COPYRIGHT.txt

View workflow job for this annotation

GitHub Actions / benchmark

Benchmark results

........... WARNING: the benchmark result may be unstable * the standard deviation (98.5 ms) is 14% of the mean (707 ms) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_5_000_run_trees: Mean +- std dev: 707 ms +- 98 ms ........... WARNING: the benchmark result may be unstable * the standard deviation (206 ms) is 14% of the mean (1.45 sec) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_10_000_run_trees: Mean +- std dev: 1.45 sec +- 0.21 sec ........... WARNING: the benchmark result may be unstable * the standard deviation (206 ms) is 14% of the mean (1.44 sec) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. create_20_000_run_trees: Mean +- std dev: 1.44 sec +- 0.21 sec ........... dumps_class_nested_py_branch_and_leaf_200x400: Mean +- std dev: 691 us +- 5 us ........... dumps_class_nested_py_leaf_50x100: Mean +- std dev: 25.7 ms +- 0.2 ms ........... dumps_class_nested_py_leaf_100x200: Mean +- std dev: 105 ms +- 3 ms ........... dumps_dataclass_nested_50x100: Mean +- std dev: 26.1 ms +- 0.2 ms ........... WARNING: the benchmark result may be unstable * the standard deviation (20.2 ms) is 26% of the mean (78.5 ms) * the maximum (123 ms) is 57% greater than the mean (78.5 ms) Try to rerun the benchmark with more runs, values and/or loops. Run 'python -m pyperf system tune' command to reduce the system jitter. Use pyperf stats, pyperf dump and pyperf hist to analyze results. Use --quiet option to hide these warnings. dumps_pydantic_nested_50x100: Mean +- std dev: 78.5 ms +- 20.2 ms ........... dumps_pydanticv1_nested_50x100: Mean +- std dev: 203 ms +- 3 ms

Check notice on line 1 in python/docs/templates/zstandard/COPYRIGHT.txt

View workflow job for this annotation

GitHub Actions / benchmark

Comparison against main

+-----------------------------------------------+----------+------------------------+ | Benchmark | main | changes | +===============================================+==========+========================+ | dumps_pydanticv1_nested_50x100 | 220 ms | 203 ms: 1.08x faster | +-----------------------------------------------+----------+------------------------+ | create_5_000_run_trees | 731 ms | 707 ms: 1.03x faster | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_branch_and_leaf_200x400 | 690 us | 691 us: 1.00x slower | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_leaf_100x200 | 104 ms | 105 ms: 1.01x slower | +-----------------------------------------------+----------+------------------------+ | dumps_dataclass_nested_50x100 | 25.5 ms | 26.1 ms: 1.02x slower | +-----------------------------------------------+----------+------------------------+ | dumps_class_nested_py_leaf_50x100 | 25.1 ms | 25.7 ms: 1.03x slower | +-----------------------------------------------+----------+------------------------+ | create_10_000_run_trees | 1.41 sec | 1.45 sec: 1.03x slower | +-----------------------------------------------+----------+------------------------+ | create_20_000_run_trees | 1.39 sec | 1.44 sec: 1.03x slower | +-----------------------------------------------+----------+------------------------+ | dumps_pydantic_nested_50x100 | 65.9 ms | 78.5 ms: 1.19x slower | +-----------------------------------------------+----------+------------------------+ | Geometric mean | (ref) | 1.02x slower | +-----------------------------------------------+----------+------------------------+
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
117 changes: 117 additions & 0 deletions python/langsmith/_internal/_background_thread.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from __future__ import annotations

import concurrent.futures as cf
import functools
import io
import logging
import sys
import threading
import weakref
from multiprocessing import cpu_count
from queue import Empty, Queue
from typing import (
TYPE_CHECKING,
List,
Optional,
Union,
cast,
)
Expand All @@ -18,6 +22,7 @@
_AUTO_SCALE_DOWN_NEMPTY_TRIGGER,
_AUTO_SCALE_UP_NTHREADS_LIMIT,
_AUTO_SCALE_UP_QSIZE_TRIGGER,
_BOUNDARY,
)
from langsmith._internal._operations import (
SerializedFeedbackOperation,
Expand All @@ -30,6 +35,8 @@

logger = logging.getLogger("langsmith.client")

HTTP_REQUEST_THREAD_POOL = cf.ThreadPoolExecutor(max_workers=cpu_count() * 3)
hinthornw marked this conversation as resolved.
Show resolved Hide resolved


@functools.total_ordering
class TracingQueueItem:
Expand Down Expand Up @@ -88,6 +95,37 @@ def _tracing_thread_drain_queue(
return next_batch


def _tracing_thread_drain_compressed_buffer(
client: Client, size_limit: int = 100, size_limit_bytes: int | None = 20_971_520
) -> Optional[io.BytesIO]:
assert client.compressed_runs is not None
with client.compressed_runs.lock:
current_size = client.compressed_runs.buffer.tell()

if size_limit is not None and size_limit <= 0:
raise ValueError(f"size_limit must be positive; got {size_limit}")
if size_limit_bytes is not None and size_limit_bytes < 0:
raise ValueError(
f"size_limit_bytes must be nonnegative; got {size_limit_bytes}"
)

if (size_limit_bytes is None or current_size < size_limit_bytes) and (
size_limit is None or client.compressed_runs.run_count < size_limit
):
return None

# Write final boundary and close compression stream
client.compressed_runs.compressor_writer.write(f"--{_BOUNDARY}--\r\n".encode())
client.compressed_runs.compressor_writer.close()

filled_buffer = client.compressed_runs.buffer

client.compressed_runs.reset()

filled_buffer.seek(0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we have a buffer we can just pass it directly to requests no? no need for iterator

return filled_buffer


def _tracing_thread_handle_batch(
client: Client,
tracing_queue: Queue,
Expand Down Expand Up @@ -200,6 +238,85 @@ def keep_thread_active() -> bool:
_tracing_thread_handle_batch(client, tracing_queue, next_batch, use_multipart)


def tracing_control_thread_func_compress_parallel(
client_ref: weakref.ref[Client],
) -> None:
client = client_ref()
if client is None:
return

batch_ingest_config = _ensure_ingest_config(client.info)
size_limit: int = batch_ingest_config["size_limit"]
size_limit_bytes = batch_ingest_config.get("size_limit_bytes", 20_971_520)
num_known_refs = 3

def keep_thread_active() -> bool:
# if `client.cleanup()` was called, stop thread
if not client or (
hasattr(client, "_manual_cleanup") and client._manual_cleanup
):
return False
if not threading.main_thread().is_alive():
# main thread is dead. should not be active
return False
if hasattr(sys, "getrefcount"):
# check if client refs count indicates we're the only remaining
# reference to the client

# Count active threads
thread_pool = HTTP_REQUEST_THREAD_POOL._threads
active_count = sum(
1 for thread in thread_pool if thread is not None and thread.is_alive()
)

return sys.getrefcount(client) > num_known_refs + active_count
else:
# in PyPy, there is no sys.getrefcount attribute
# for now, keep thread alive
return True

while True:
triggered = client._data_available_event.wait(timeout=0.05)
if not keep_thread_active():
break
if not triggered:
continue
client._data_available_event.clear()

data_stream = _tracing_thread_drain_compressed_buffer(
client, size_limit, size_limit_bytes
)

if data_stream is not None:
try:
future = HTTP_REQUEST_THREAD_POOL.submit(
client._send_compressed_multipart_req, data_stream
)
client._futures.add(future)
except RuntimeError:
client._send_compressed_multipart_req(data_stream)

# Drain the buffer on exit
try:
final_data_stream = _tracing_thread_drain_compressed_buffer(
client, size_limit=1, size_limit_bytes=1
) # Force final drain
if final_data_stream is not None:
try:
cf.wait(
[
HTTP_REQUEST_THREAD_POOL.submit(
client._send_compressed_multipart_req, final_data_stream
)
]
)
except RuntimeError:
client._send_compressed_multipart_req(final_data_stream)

except Exception:
logger.error("Error in final cleanup", exc_info=True)


def _tracing_sub_thread_func(
client_ref: weakref.ref[Client],
use_multipart: bool,
Expand Down
40 changes: 40 additions & 0 deletions python/langsmith/_internal/_compressed_runs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import io
import threading

try:
from zstandard import ZstdCompressor # type: ignore[import]

HAVE_ZSTD = True
except ImportError:
HAVE_ZSTD = False

from langsmith import utils as ls_utils

compression_level = ls_utils.get_env_var("RUN_COMPRESSION_LEVEL", 3)


class CompressedRuns:
def __init__(self):
self.buffer = io.BytesIO()
self.run_count = 0
self.lock = threading.Lock()
if not HAVE_ZSTD:
raise ImportError(
"zstandard package required for compression. "
"Install with 'pip install langsmith[compression]'"
)
self.compressor_writer = ZstdCompressor(
level=compression_level, threads=-1
).stream_writer(self.buffer, closefd=False)

def reset(self):
self.buffer = io.BytesIO()
self.run_count = 0
if not HAVE_ZSTD:
raise ImportError(
"zstandard package required for compression. "
"Install with 'pip install langsmith[compression]'"
)
self.compressor_writer = ZstdCompressor(
level=compression_level, threads=-1
).stream_writer(self.buffer, closefd=False)
3 changes: 3 additions & 0 deletions python/langsmith/_internal/_constants.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import uuid

_SIZE_LIMIT_BYTES = 20_971_520 # 20MB by default
_AUTO_SCALE_UP_QSIZE_TRIGGER = 200
_AUTO_SCALE_UP_NTHREADS_LIMIT = 32
_AUTO_SCALE_DOWN_NEMPTY_TRIGGER = 4
_BLOCKSIZE_BYTES = 1024 * 1024 # 1MB
_BOUNDARY = uuid.uuid4().hex
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to be unique every time? or should we hardcode it here?

41 changes: 41 additions & 0 deletions python/langsmith/_internal/_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
import uuid
from typing import Literal, Optional, Union, cast

try:
from zstandard import ZstdCompressionWriter # type: ignore[import]
except ImportError:

class ZstdCompressionWriter: # type: ignore[no-redef]
"""only used for typing checks."""


from langsmith import schemas as ls_schemas
from langsmith._internal import _orjson
from langsmith._internal._multipart import MultipartPart, MultipartPartsAndContext
Expand Down Expand Up @@ -271,3 +279,36 @@ def serialized_run_operation_to_multipart_parts_and_context(
acc_parts,
f"trace={op.trace_id},id={op.id}",
)


def compress_multipart_parts_and_context(
hinthornw marked this conversation as resolved.
Show resolved Hide resolved
parts_and_context: MultipartPartsAndContext,
compressor_writer: ZstdCompressionWriter,
boundary: str,
) -> None:
for part_name, (filename, data, content_type, headers) in parts_and_context.parts:
header_parts = [
f"--{boundary}\r\n",
f'Content-Disposition: form-data; name="{part_name}"',
]

if filename:
header_parts.append(f'; filename="{filename}"')

header_parts.extend(
[
f"\r\nContent-Type: {content_type}\r\n",
*[f"{k}: {v}\r\n" for k, v in headers.items()],
"\r\n",
]
)

compressor_writer.write("".join(header_parts).encode())

if isinstance(data, (bytes, bytearray)):
compressor_writer.write(data)
else:
compressor_writer.write(str(data).encode())

# Write part terminator
compressor_writer.write(b"\r\n")
Loading
Loading