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

[Frontend]: enable generator interface for offline inference #9780

Open
wants to merge 22 commits into
base: main
Choose a base branch
from

Conversation

sethkimmel3
Copy link
Contributor

@sethkimmel3 sethkimmel3 commented Oct 29, 2024

I'm proposing the ability to add custom callback functions to the generate method for offline inference. This is helpful in longer running jobs when users want to programmatically track completion time, see results as they're generating, and so forth. Suggestions like #6154 seem to indicate a desire for such functionality.

The interface is quite simple; it looks something like:

def some_callback_function(payload):
    # log the latest output, update job status metadata, etc.

llm.generate(inputs, state_callback=some_callback_function)

Some considerations:

  • It would probably be important to profile throughput degradation when users choose to enable this. It's possible the impact is minimal but perhaps the vllm team has tools to check this easily.
  • I think there's a case to passing less data in the payload, but the current approach maximizes user customizability. It could be possible to add an option to only invoke the callback every n generations to mitigate impacts on performance.
  • It may be worth adding the same feature to the encode method, so users can similarly track progress of embedding generation.

BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE


PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Adding or changing kernels

Each custom kernel needs a schema and one or more implementations to be registered with PyTorch.

  • Make sure custom ops are registered following PyTorch guidelines: Custom C++ and CUDA Operators and The Custom Operators Manual
  • Custom operations that return Tensors require meta-functions. Meta-functions should be implemented and registered in python so that dynamic dims can be handled automatically. See above documents for a description of meta-functions.
  • Use torch.libary.opcheck() to test the function registration and meta-function for any registered ops. See tests/kernels for examples.
  • When changing the C++ signature of an existing op, the schema must be updated to reflect the changes.
  • If a new custom type is needed, see the following document: Custom Class Support in PT2.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

Copy link

👋 Hi! Thank you for contributing to the vLLM project.
Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of those by going to your fastcheck build on Buildkite UI (linked in the PR checks section) and unblock them. If you do not have permission to unblock, ping simon-mo or khluu to add you in our Buildkite org.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can do one of these:

  • Add ready label to the PR
  • Enable auto-merge.

🚀

@mergify mergify bot added the frontend label Oct 29, 2024
@mergify mergify bot added the ci/build label Oct 30, 2024
@sethkimmel3 sethkimmel3 changed the title add state callback [Frontend]: add state callback Oct 31, 2024
@sethkimmel3 sethkimmel3 changed the title [Frontend]: add state callback [Frontend]: enable state callbacks for offline inference Oct 31, 2024
@sethkimmel3 sethkimmel3 marked this pull request as ready for review October 31, 2024 01:10
@sethkimmel3
Copy link
Contributor Author

sethkimmel3 commented Nov 2, 2024

I've been using this branch, and it seems like performance overhead created is minimal if the user implements async methods in the callback. I'm not sure if it would make sense to be able to pass an async function as the callback itself, or just let the user handle their own implementation.

This is how I've gotten it to be performant:

import asyncio

# start a new event loop
progress_loop = asyncio.new_event_loop()
pending_tasks = []

def run_event_loop():
    asyncio.set_event_loop(progress_loop)
    progress_loop.run_forever()

loop_thread = threading.Thread(target=run_event_loop, daemon=True)
loop_thread.start()

# define my callback function logic, run in the new event loop
def some_callback_function(payload):
    task = asyncio.run_coroutine_threadsafe(some_async_function(payload), progress_loop)
    pending_tasks.append(task)

async def some_async_function(payload):
    await my_custom_logic(payload)

# generate outputs
try: 
    self.llm.generate(inputs, state_callback=some_callback_function)
finally:
    for task in pending_tasks:
        try:
            task.result(timeout=1.0)
        except Exception as e:
            print(f"Error waiting for task: {e}")

    ### close the new event loop
    progress_loop.call_soon_threadsafe(progress_loop.stop)
    loop_thread.join(timeout=1.0)
    progress_loop.close()

We'd certainly want to write some documentation about how to implement this so as to not hurt performance.

@simon-mo
Copy link
Collaborator

simon-mo commented Nov 4, 2024

I’m still a bit curious about the primary use case. I understand what it can be used for. But what are you exactly using this for at the moment? Asking because

  • If just to track progress, we can send less information and periodically (instead of every token) to reduce performance issue
  • We also recommend directly using the LLMEngine class for further customization https://github.com/vllm-project/vllm/blob/main/examples/llm_engine_example.py
  • Alternatively, generate can be modified to return a generator instead of the complete list, that can be used to avoid injecting callbacks.

@sethkimmel3
Copy link
Contributor Author

Thanks for responding here @simon-mo

My current use case is simply exposing progress to an external interface. Currently, the only way to see progress is via tdqm, so it's not flexible for creating additional interfaces or exposing to external users. In the future, I think there is a strong case to "streaming" outputs to an interface as they're being generated, so users can terminate runs if responses don't seem right. Finally, I think there's a case to streaming them on the fly so responses can be cached in the case of pre-emption.

To respond to your suggestions directly:

  • I agree less data can likely be sent for just tracking progress. But if we want to enable the above use-cases, this should at least allow for returning generated text if not logprobs as well.
  • I think the LLMEngine class might be the appropriate answer here. I certainly don't want to overload the main methods with extraneous parameters that can be handled elsewhere. I guess it really depends on how many other users care about this being abstracted for them.
  • Modifying generate to return a generator seems like a good idea but could be a severely breaking change, no?

@njhill
Copy link
Member

njhill commented Nov 4, 2024

  • Modifying generate to return a generator seems like a good idea but could be a severely breaking change, no?

I had been thinking this would be good to add anyhow. It won't be breaking because we would add a stream parameter to control whether or not a generator/iterator is returned.

@sethkimmel3
Copy link
Contributor Author

sethkimmel3 commented Nov 5, 2024

Thanks for the suggestion @njhill. Good point about simply leaving the default behavior as is.

If you prefer that route @simon-mo - I'll go ahead and implement it here.

@simon-mo
Copy link
Collaborator

simon-mo commented Nov 5, 2024

stream parameter does sound better here! Or even another alternative method named generate_stream

@sethkimmel3 sethkimmel3 changed the title [Frontend]: enable state callbacks for offline inference [Frontend]: enable generator interface for offline inference Nov 6, 2024
@sethkimmel3
Copy link
Contributor Author

sethkimmel3 commented Nov 6, 2024

I've modified the generate method so it will instead return a generator type when stream is set to True. Let me know if this is preferable, or if I should instead separate out a generate_stream method as @simon-mo had suggested.

One consideration @simon-mo - the generator will not necessarily yield results in the same order as the inputs, correct? Given this is the case, we can either implement a buffer to handle this on behalf of the client (which might hurt performance) or just indicate that the user should handle this themselves if desired and document how to do so.

cc: @njhill

Copy link

mergify bot commented Nov 6, 2024

This pull request has merge conflicts that must be resolved before it can be
merged. Please rebase the PR, @sethkimmel3.

https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify bot added the needs-rebase label Nov 6, 2024
@mergify mergify bot removed the needs-rebase label Nov 6, 2024
@sethkimmel3
Copy link
Contributor Author

@simon-mo @njhill - let me know what's preferable from the above comment when you can :)

@njhill
Copy link
Member

njhill commented Nov 11, 2024

Thanks @sethkimmel3. There's a couple of issues I think (which I hadn't considered when suggesting the stream arg):

  • The same python function can't dynamically return either a unary value or a be a generator, we would have to have the yields in a separate function which is called from generate() to obtain the generator in the stream case
  • Having the generator yield between each step would likely have some performance implications since any work done by the caller would hold up generation of the next tokens. A possible solution to this would be to spawn a thread which runs the step loop and adds the results into a queue, and then the returned generator just pulls from this queue.

@sethkimmel3
Copy link
Contributor Author

sethkimmel3 commented Nov 12, 2024

Thanks @njhill - I'll do some work here considering these issues.

Copy link

mergify bot commented Nov 15, 2024

This pull request has merge conflicts that must be resolved before it can be
merged. Please rebase the PR, @sethkimmel3.

https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify bot added the needs-rebase label Nov 15, 2024
@hmellor
Copy link
Collaborator

hmellor commented Dec 19, 2024

Hi @sethkimmel3, do you plan to continue working on this PR? I notice it's been over a month since the last activity here.

@sethkimmel3
Copy link
Contributor Author

Hey @hmellor - I do plan to continue this work; I'm not sure when.

@hmellor
Copy link
Collaborator

hmellor commented Dec 19, 2024

Ok, thanks for the update!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants