Yo <@U071FMQUR7W> are there any concurrency contro...
# daft-dev
e
Yo @Cory Grinstead are there any concurrency controls for row-wise udfs?
k
There currently aren’t any. What would you want to use them for?
e
Throttling LLM clients. Once I try to run 1000 rows, I tried instantiating the client inside the func and it finished the job, but I ran into event_loop errors.
I’m also getting a pickle error when I specify concurrency on my batch variant of the same workload
👀 1
k
Gotcha. So my understanding is that the concurrency controls are there to do rate limiting
I'm not super happy about the current concurrency design with
@daft.udf
because it's kind of a roundabout way of describing rate limits. what users probably want to express are some combination of • number of UDF calls to make per second/minute/hour/etc in total • number of UDF calls to make per second/minute/hour/etc per machine/IP • in special cases, some mechanism to dynamically tell Daft to throttle requests What are your thoughts on this?
I’m also getting a pickle error when I specify concurrency on my batch variant of the same workload
Could you share more about this error and the code you are trying to run?
e
Definitely. I think for me I just know that by default daft is going to scale horizontally as much as it can based on the load, but I’d like to be able to specify that limit. I suppose that the number of workers? Then I can make assumptions about an individual worker's limitations and go from there. I can run 200 rows no problem. But as I increase the load, I expect I’m getting more workers and then exhausting my event_loop. The job does finish when I instantiate an AsyncOpenAI client inside. Here is the job:
Copy code
@daft.udf(return_dtype=daft.DataType.string(), concurrency=8)
def struct_output_batch(
        model_id: str, 
        text_col: daft.Series, 
        image_col: daft.Series,
        extra_body: dict | None = None
    ) -> list[str]:
    

    async def generate(model_id: str, text: str, image: str) -> str:
        result = await client.chat.completions.create(
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": text},
                        {
                            "type": "image_url",
                            "image_url": {"url": f"data:image/png;base64,{image}"},
                        },
                    ],
                }
            ],
            model=model_id,
            extra_body={"guided_choice": ["A", "B", "C", "D"]},
        )
        return result.choices[0].message.content

    texts = text_col.to_pylist()
    images = image_col.to_pylist()

    async def gather_completions() -> list[str]:
        tasks = [generate(model_id, t,i) for t,i in zip(texts,images) ]
        return await asyncio.gather(*tasks)

    return asyncio.run(gather_completions())
Pretty much llm_generate without event loop protection and an added explicit image and extra body arg.
Removing the concurrency argument in the udf decorator removes the error of:
Copy code
ERROR:daft_local_execution:Error when running pipeline node UDF struct_output_batch
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipython-input-1876801372.py in <cell line: 0>()
     42                                                     image_col = df["image_base64"],
     43                                                     extra_body={"guided_choice": ["A", "B", "C", "D"]}
---> 44                                                 )).collect()
     45 collect = time.time()
     46 print(f"Collect time: {collect-start} seconds")

5 frames
/usr/local/lib/python3.12/dist-packages/daft/execution/udf.py in __init__(self, project_expr, passthrough_exprs)
     84             [Expression._from_pyexpr(expr) for expr in passthrough_exprs] + [Expression._from_pyexpr(project_expr)]
     85         )
---> 86         expr_projection_bytes = pickle.dumps(expr_projection)
     87         self.handle_conn.send((_ENTER, expr_projection_bytes))
     88         response = self.handle_conn.recv()

RuntimeError: Failed to serialize: TypeError: cannot pickle '_thread.RLock' object
s
@Everett Kleven are you defining the OpenAI
client
outside of the UDF, as a global var?
e
Sorry the above is the batch udf which yields the pickle error for adding the concurrency param. Here is the row_wise udf with openai_client instantiated:
Copy code
# instantiating a new client inside the funciton..... (this is crazy)
@daft.func(return_dtype=daft.DataType.string())
async def struct_output_rowwise(model_id: str, text: str, image: str) -> str:
    from openai import AsyncOpenAI
    api_key = "none"
    base_url = "http://0.0.0.0:8000/v1"
    client = AsyncOpenAI(api_key=api_key, base_url=base_url)


    result = await client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": text},
                    {
                        "type": "image_url",
                        "image_url": {"url": f"data:image/png;base64,{image}"},
                    },
                ],
            }
        ],
        model=model_id,
        extra_body={"guided_choice": ["A", "B", "C", "D"]},
    )
    return result.choices[0].message.content
Where I just get a bunch of these errors:
Copy code
RuntimeError: no running event loop

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.12/dist-packages/httpx/_client.py", line 1985, in aclose
    await self._transport.aclose()
  File "/usr/local/lib/python3.12/dist-packages/httpx/_transports/default.py", line 406, in aclose
    await self._pool.aclose()
  File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection_pool.py", line 353, in aclose
    await self._close_connections(closing_connections)
  File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection_pool.py", line 345, in _close_connections
    await connection.aclose()
  File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/connection.py", line 173, in aclose
    await self._connection.aclose()
  File "/usr/local/lib/python3.12/dist-packages/httpcore/_async/http11.py", line 258, in aclose
    await self._network_stream.aclose()
  File "/usr/local/lib/python3.12/dist-packages/httpcore/_backends/anyio.py", line 53, in aclose
    await self._stream.aclose()
  File "/usr/local/lib/python3.12/dist-packages/anyio/_backends/_asyncio.py", line 1314, in aclose
    self._transport.close()
  File "/usr/lib/python3.12/asyncio/selector_events.py", line 1213, in close
    super().close()
  File "/usr/lib/python3.12/asyncio/selector_events.py", line 875, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "/usr/lib/python3.12/asyncio/base_events.py", line 799, in call_soon
    self._check_closed()
  File "/usr/lib/python3.12/asyncio/base_events.py", line 545, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-2115' coro=<AsyncClient.aclose() done, defined at /usr/local/lib/python3.12/dist-packages/httpx/_client.py:1978> exception=RuntimeError('Event loop is closed')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/dist-packages/daft/udf/row_wise.py", line 90, in __call_async_batch
    event_loop = asyncio.get_running_loop()
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
👍 1
HOLD ON HOLD ON....
This doesn't make any sense. I didn't await the client instantiation and my func is
async def
... I'm trying the sync client now.
nvm I don't need to await the client.
👍 1
s
Copy code
# instantiating a new client inside the funciton..... (this is crazy)
Yeah totally agree, we're working on designing a new way to instantiate this
e
I mean ideally I'd use a batch udf as a class and include client instantiation in the init
s
Thats probably the best approach for the time being, but we're trying to move away from that format with the new
daft.func
types. But absolutely, that would be best for now. Alternatively, could you also try moving the
AsyncOpenAI(api_key=api_key, base_url=base_url)
outside the UDF?
e
Hmm I must have been running into a different error before. This works as well:
Copy code
from openai import OpenAI
api_key = "none"
base_url = "http://0.0.0.0:8000/v1"
client = OpenAI(api_key=api_key, base_url=base_url)

@daft.func(return_dtype=daft.DataType.string())
async def struct_output_rowwise(model_id: str, text: str, image: str) -> str:
    result = await client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": text},
                    {
                        "type": "image_url",
                        "image_url": {"url": f"data:image/png;base64,{image}"},
                    },
                ],
            }
        ],
        model=model_id,
        extra_body={"guided_choice": ["A", "B", "C", "D"]},
    )
    return result.choices[0].message.content


# Lets try 1000 rows

start = time.time()
df_result_rowwise = df.limit(1000).with_column("result", struct_output_rowwise(
                                                    model_id, 
                                                    df["user"], 
                                                    df["image_base64"]
                                                )).collect()
collect = time.time()
print(f"Collect time: {collect-start} seconds")
but I get an error after the job finishes. Its the same error, which turns out to be more distracting than anything
s
This error?
Copy code
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/dist-packages/daft/udf/row_wise.py", line 90, in __call_async_batch
    event_loop = asyncio.get_running_loop()
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
e
Yep
👍 1
Thats just got to be event loop starvation right?
s
Not sure exactly, that code path should only run once per row. Will look into it. Do you mind creating a GitHub issue with the reproducer?
e
Sure! Will do.
c
what's odd to me is how that error is even surfacing?
Copy code
try:
        event_loop = asyncio.get_running_loop() # <---- here 
        outputs = asyncio.run_coroutine_threadsafe(run_tasks(), event_loop).result()
    except RuntimeError:
        outputs = asyncio.run(run_tasks())
We're catching the RuntimeError's so i'm not entirely sure how that error ever gets surfaced 🤔
e
It’s weird. The whole workload runs and then I get the error at the end
🤔 1
c
that is really odd. Once you have a MRE/issue open, feel free to tag me and I'd be happy take a closer look!
z
we meet similar problem about event loop during using batch udf,we got a practice about using event loop in our case from @Xin Xianyin , hope it can helpful
Copy code
class CustomUDF:
    def __init__(self) -> None:
        self._local = threading.local()

def _get_event_loop(self) -> asyncio.AbstractEventLoop:
    """Get or create the event loop of current thread."""
    if not hasattr(self._local, "loop"):
        self._local.loop = asyncio.new_event_loop()
    return self._local.loop

async def async_run(self, a: list[str]) -> list[str]:
    pass

def __call__(self, a: Series) -> Series:
    loop = self._get_event_loop()
    if loop.is_running():
        future = asyncio.run_coroutine_threadsafe(self.async_run(a.to_pylist()), loop)
        results = future.result()
    else:
        results = loop.run_until_complete(self.async_run(a.to_pylist()))
    
    pass
👀 1
e
Having a hard time reproducing that concurrency arg error for python function decorated udfs (not daft.func) Last nights release may have fixed it... still working through the full example.
k
Thanks for filing this. @Srinivas Lade maybe you can take a look?
👍 1