kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 705e0654af7d443a74137969742f7639c41b8a5113e44746430a59a97ccc44d9 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-19 12:05 -07:00 |
| Committer | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-19 12:22 -07:00 |
| Parents | 7ef69e0d6d29 |
10 files changed
modified .flake8 +2 −0
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | # shebang has extra meaning in fbcode lints, so I think it's not worth trying |
| 15 | 15 | # to line this up with executable bit |
| 16 | 16 | EXE001, |
| 17 | + # random naming hints don't need | |
| 18 | + N802, | |
| 17 | 19 | # these ignores are from flake8-bugbear; please fix! |
| 18 | 20 | B007,B008,B950 |
| 19 | 21 | optional-ascii-coding = True |
modified llama_stack/distribution/control_plane/__init__.py +0 −2
| @@ -3,5 +3,3 @@ | ||
| 3 | 3 | # |
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | - | |
| 7 | -from .control_plane import * # noqa: F401 F403 |
modified llama_stack/distribution/control_plane/adapters/redis/config.py +2 −0
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | +from typing import Optional | |
| 8 | + | |
| 7 | 9 | from llama_models.schema_utils import json_schema_type |
| 8 | 10 | from pydantic import BaseModel, Field |
| 9 | 11 |
modified llama_stack/providers/impls/meta_reference/agents/agent_instance.py +1 −0
| @@ -619,6 +619,7 @@ | ||
| 619 | 619 | else: |
| 620 | 620 | return True |
| 621 | 621 | |
| 622 | + print(f"{enabled_tools=}") | |
| 622 | 623 | return AgentTool.memory.value in enabled_tools |
| 623 | 624 | |
| 624 | 625 | def _memory_tool_definition(self) -> Optional[MemoryToolDefinition]: |
modified llama_stack/providers/impls/meta_reference/agents/safety.py +1 −3
| @@ -43,12 +43,10 @@ | ||
| 43 | 43 | if len(messages) > 0 and messages[0].role != Role.user.value: |
| 44 | 44 | messages[0] = UserMessage(content=messages[0].content) |
| 45 | 45 | |
| 46 | - res = await self.safety_api.run_shields( | |
| 46 | + results = await self.safety_api.run_shields( | |
| 47 | 47 | messages=messages, |
| 48 | 48 | shields=shields, |
| 49 | 49 | ) |
| 50 | - | |
| 51 | - results = res.responses | |
| 52 | 50 | for shield, r in zip(shields, results): |
| 53 | 51 | if r.is_violation: |
| 54 | 52 | if shield.on_violation_action == OnViolationAction.RAISE: |
added llama_stack/providers/impls/meta_reference/agents/tests/test_chat_agent.py +216 −0
| @@ -0,0 +1,216 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +from typing import AsyncIterator, List, Optional, Union | |
| 8 | +from unittest.mock import MagicMock | |
| 9 | + | |
| 10 | +import pytest | |
| 11 | + | |
| 12 | +from llama_stack.apis.inference import * # noqa: F403 | |
| 13 | +from llama_stack.apis.memory import * # noqa: F403 | |
| 14 | +from llama_stack.apis.safety import * # noqa: F403 | |
| 15 | +from llama_stack.apis.agents import * # noqa: F403 | |
| 16 | + | |
| 17 | +from ..agent_instance import ChatAgent | |
| 18 | + | |
| 19 | + | |
| 20 | +class MockInferenceAPI: | |
| 21 | + async def chat_completion( | |
| 22 | + self, | |
| 23 | + model: str, | |
| 24 | + messages: List[Message], | |
| 25 | + sampling_params: Optional[SamplingParams] = SamplingParams(), | |
| 26 | + tools: Optional[List[ToolDefinition]] = None, | |
| 27 | + tool_choice: Optional[ToolChoice] = None, | |
| 28 | + tool_prompt_format: Optional[ToolPromptFormat] = None, | |
| 29 | + stream: Optional[bool] = False, | |
| 30 | + logprobs: Optional[LogProbConfig] = None, | |
| 31 | + ) -> AsyncIterator[ | |
| 32 | + Union[ChatCompletionResponseStreamChunk, ChatCompletionResponse] | |
| 33 | + ]: | |
| 34 | + if stream: | |
| 35 | + yield ChatCompletionResponseStreamChunk( | |
| 36 | + event=ChatCompletionResponseEvent( | |
| 37 | + event_type="start", | |
| 38 | + delta="", | |
| 39 | + ) | |
| 40 | + ) | |
| 41 | + | |
| 42 | + yield ChatCompletionResponseStreamChunk( | |
| 43 | + event=ChatCompletionResponseEvent( | |
| 44 | + event_type="progress", | |
| 45 | + delta="Mock response", | |
| 46 | + ) | |
| 47 | + ) | |
| 48 | + | |
| 49 | + yield ChatCompletionResponseStreamChunk( | |
| 50 | + event=ChatCompletionResponseEvent( | |
| 51 | + event_type="complete", | |
| 52 | + delta="", | |
| 53 | + stop_reason="end_of_turn", | |
| 54 | + ) | |
| 55 | + ) | |
| 56 | + else: | |
| 57 | + yield ChatCompletionResponse( | |
| 58 | + completion_message=CompletionMessage( | |
| 59 | + role="assistant", content="Mock response", stop_reason="end_of_turn" | |
| 60 | + ), | |
| 61 | + logprobs=[0.1, 0.2, 0.3] if logprobs else None, | |
| 62 | + ) | |
| 63 | + | |
| 64 | + | |
| 65 | +class MockSafetyAPI: | |
| 66 | + async def run_shields( | |
| 67 | + self, messages: List[Message], shields: List[MagicMock] | |
| 68 | + ) -> List[ShieldResponse]: | |
| 69 | + return [ShieldResponse(shield_type="mock_shield", is_violation=False)] | |
| 70 | + | |
| 71 | + | |
| 72 | +class MockMemoryAPI: | |
| 73 | + def __init__(self): | |
| 74 | + self.memory_banks = {} | |
| 75 | + self.documents = {} | |
| 76 | + | |
| 77 | + async def create_memory_bank(self, name, config, url=None): | |
| 78 | + bank_id = f"bank_{len(self.memory_banks)}" | |
| 79 | + bank = MemoryBank(bank_id, name, config, url) | |
| 80 | + self.memory_banks[bank_id] = bank | |
| 81 | + self.documents[bank_id] = {} | |
| 82 | + return bank | |
| 83 | + | |
| 84 | + async def list_memory_banks(self): | |
| 85 | + return list(self.memory_banks.values()) | |
| 86 | + | |
| 87 | + async def get_memory_bank(self, bank_id): | |
| 88 | + return self.memory_banks.get(bank_id) | |
| 89 | + | |
| 90 | + async def drop_memory_bank(self, bank_id): | |
| 91 | + if bank_id in self.memory_banks: | |
| 92 | + del self.memory_banks[bank_id] | |
| 93 | + del self.documents[bank_id] | |
| 94 | + return bank_id | |
| 95 | + | |
| 96 | + async def insert_documents(self, bank_id, documents, ttl_seconds=None): | |
| 97 | + if bank_id not in self.documents: | |
| 98 | + raise ValueError(f"Bank {bank_id} not found") | |
| 99 | + for doc in documents: | |
| 100 | + self.documents[bank_id][doc.document_id] = doc | |
| 101 | + | |
| 102 | + async def update_documents(self, bank_id, documents): | |
| 103 | + if bank_id not in self.documents: | |
| 104 | + raise ValueError(f"Bank {bank_id} not found") | |
| 105 | + for doc in documents: | |
| 106 | + if doc.document_id in self.documents[bank_id]: | |
| 107 | + self.documents[bank_id][doc.document_id] = doc | |
| 108 | + | |
| 109 | + async def query_documents(self, bank_id, query, params=None): | |
| 110 | + if bank_id not in self.documents: | |
| 111 | + raise ValueError(f"Bank {bank_id} not found") | |
| 112 | + # Simple mock implementation: return all documents | |
| 113 | + chunks = [ | |
| 114 | + {"content": doc.content, "token_count": 10, "document_id": doc.document_id} | |
| 115 | + for doc in self.documents[bank_id].values() | |
| 116 | + ] | |
| 117 | + scores = [1.0] * len(chunks) | |
| 118 | + return {"chunks": chunks, "scores": scores} | |
| 119 | + | |
| 120 | + async def get_documents(self, bank_id, document_ids): | |
| 121 | + if bank_id not in self.documents: | |
| 122 | + raise ValueError(f"Bank {bank_id} not found") | |
| 123 | + return [ | |
| 124 | + self.documents[bank_id][doc_id] | |
| 125 | + for doc_id in document_ids | |
| 126 | + if doc_id in self.documents[bank_id] | |
| 127 | + ] | |
| 128 | + | |
| 129 | + async def delete_documents(self, bank_id, document_ids): | |
| 130 | + if bank_id not in self.documents: | |
| 131 | + raise ValueError(f"Bank {bank_id} not found") | |
| 132 | + for doc_id in document_ids: | |
| 133 | + self.documents[bank_id].pop(doc_id, None) | |
| 134 | + | |
| 135 | + | |
| 136 | +@pytest.fixture | |
| 137 | +def mock_inference_api(): | |
| 138 | + return MockInferenceAPI() | |
| 139 | + | |
| 140 | + | |
| 141 | +@pytest.fixture | |
| 142 | +def mock_safety_api(): | |
| 143 | + return MockSafetyAPI() | |
| 144 | + | |
| 145 | + | |
| 146 | +@pytest.fixture | |
| 147 | +def mock_memory_api(): | |
| 148 | + return MockMemoryAPI() | |
| 149 | + | |
| 150 | + | |
| 151 | +@pytest.fixture | |
| 152 | +def chat_agent(mock_inference_api, mock_safety_api, mock_memory_api): | |
| 153 | + # You'll need to adjust this based on the actual ChatAgent constructor | |
| 154 | + agent_config = AgentConfig( | |
| 155 | + model="test_model", | |
| 156 | + instructions="You are a helpful assistant.", | |
| 157 | + sampling_params=SamplingParams(), | |
| 158 | + tools=[], | |
| 159 | + tool_choice=ToolChoice.auto, | |
| 160 | + input_shields=[], | |
| 161 | + output_shields=[], | |
| 162 | + ) | |
| 163 | + return ChatAgent( | |
| 164 | + agent_config=agent_config, | |
| 165 | + inference_api=mock_inference_api, | |
| 166 | + memory_api=mock_memory_api, | |
| 167 | + safety_api=mock_safety_api, | |
| 168 | + builtin_tools=[], | |
| 169 | + ) | |
| 170 | + | |
| 171 | + | |
| 172 | +@pytest.mark.asyncio | |
| 173 | +async def test_chat_agent_create_session(chat_agent): | |
| 174 | + session = chat_agent.create_session("Test Session") | |
| 175 | + assert session.session_name == "Test Session" | |
| 176 | + assert session.turns == [] | |
| 177 | + assert session.session_id in chat_agent.sessions | |
| 178 | + | |
| 179 | + | |
| 180 | +@pytest.mark.asyncio | |
| 181 | +async def test_chat_agent_create_and_execute_turn(chat_agent): | |
| 182 | + session = chat_agent.create_session("Test Session") | |
| 183 | + request = AgentTurnCreateRequest( | |
| 184 | + agent_id="random", | |
| 185 | + session_id=session.session_id, | |
| 186 | + messages=[UserMessage(content="Hello")], | |
| 187 | + ) | |
| 188 | + | |
| 189 | + responses = [] | |
| 190 | + async for response in chat_agent.create_and_execute_turn(request): | |
| 191 | + responses.append(response) | |
| 192 | + | |
| 193 | + print(responses) | |
| 194 | + assert len(responses) > 0 | |
| 195 | + assert len(responses) == 4 # TurnStart, StepStart, StepComplete, TurnComplete | |
| 196 | + assert responses[0].event.payload.turn_id is not None | |
| 197 | + | |
| 198 | + | |
| 199 | +@pytest.mark.asyncio | |
| 200 | +async def test_run_shields_wrapper(chat_agent): | |
| 201 | + messages = [UserMessage(content="Test message")] | |
| 202 | + shields = [ShieldDefinition(shield_type="test_shield")] | |
| 203 | + | |
| 204 | + responses = [ | |
| 205 | + chunk | |
| 206 | + async for chunk in chat_agent.run_shields_wrapper( | |
| 207 | + turn_id="test_turn_id", | |
| 208 | + messages=messages, | |
| 209 | + shields=shields, | |
| 210 | + touchpoint="user-input", | |
| 211 | + ) | |
| 212 | + ] | |
| 213 | + | |
| 214 | + assert len(responses) == 2 # StepStart, StepComplete | |
| 215 | + assert responses[0].event.payload.step_type.value == "shield_call" | |
| 216 | + assert not responses[1].event.payload.step_details.response.is_violation |
added llama_stack/providers/impls/meta_reference/inference/quantization/fp8_txest_disabled.py +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 8 | +# This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. | |
| 9 | + | |
| 10 | +import unittest | |
| 11 | + | |
| 12 | +import torch | |
| 13 | + | |
| 14 | +from fp8_impls import ffn_swiglu_fp8_dynamic, FfnQuantizeMode, quantize_fp8 | |
| 15 | +from hypothesis import given, settings, strategies as st | |
| 16 | +from torch import Tensor | |
| 17 | + | |
| 18 | + | |
| 19 | +@unittest.skipIf( | |
| 20 | + not torch.cuda.is_available() | |
| 21 | + or torch.cuda.get_device_properties(torch.cuda.current_device()).major < 9, | |
| 22 | + "Skip when H100 is not available", | |
| 23 | +) | |
| 24 | +class FP8Tests(unittest.TestCase): | |
| 25 | + @settings(deadline=None) | |
| 26 | + @given( | |
| 27 | + D=st.sampled_from([4096, 8192]), | |
| 28 | + HD_L=st.sampled_from([1280, 2560]), | |
| 29 | + B=st.sampled_from([1, 2]), | |
| 30 | + T=st.sampled_from([2048, 4096]), | |
| 31 | + UB=st.sampled_from([1000, 10000]), | |
| 32 | + ) | |
| 33 | + def test_fp8_ffn( | |
| 34 | + self, | |
| 35 | + D: int, # noqa | |
| 36 | + HD_L: int, | |
| 37 | + B: int, | |
| 38 | + T: int, | |
| 39 | + UB: float, | |
| 40 | + ) -> None: | |
| 41 | + x = torch.randn(size=(B, T, D), dtype=torch.bfloat16, device="cuda") * 0.1 | |
| 42 | + w1 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01 | |
| 43 | + w3 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01 | |
| 44 | + w2 = torch.randn(size=(D, HD_L), dtype=torch.bfloat16, device="cuda") * 0.1 | |
| 45 | + | |
| 46 | + x_q = quantize_fp8(x, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 47 | + w1_q = quantize_fp8(w1, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 48 | + w3_q = quantize_fp8(w3, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 49 | + w2_q = quantize_fp8(w2, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 50 | + | |
| 51 | + def ref_ffn(x: Tensor, w1: Tensor, w3: Tensor, w2: Tensor) -> Tensor: | |
| 52 | + (B, T, D) = x.shape # noqa: N806 | |
| 53 | + (HD_L, D_) = w1.shape # noqa: N806 | |
| 54 | + assert D_ == D | |
| 55 | + | |
| 56 | + x1 = x.view(B * T, D) @ w1.T | |
| 57 | + x2 = x.view(B * T, D) @ w3.T | |
| 58 | + | |
| 59 | + z = torch.nn.functional.silu(x1) * x2 | |
| 60 | + return (z @ w2.T).view(B, T, D).to(torch.bfloat16) | |
| 61 | + | |
| 62 | + v = ffn_swiglu_fp8_dynamic(x, w1_q, w3_q, w2_q) | |
| 63 | + | |
| 64 | + # Fake quant | |
| 65 | + x = x_q.weight.bfloat16() * x_q.scale.unsqueeze(-1) | |
| 66 | + w1 = w1_q.weight.bfloat16() * w1_q.scale.unsqueeze(-1) | |
| 67 | + w3 = w3_q.weight.bfloat16() * w3_q.scale.unsqueeze(-1) | |
| 68 | + w2 = w2_q.weight.bfloat16() * w2_q.scale.unsqueeze(-1) | |
| 69 | + | |
| 70 | + v_ref = ref_ffn(x, w1, w3, w2) | |
| 71 | + | |
| 72 | + torch.testing.assert_close(v_ref, v, atol=4.0e-3, rtol=4.0e-3) | |
| 73 | + | |
| 74 | + | |
| 75 | +if __name__ == "__main__": | |
| 76 | + unittest.main() |
deleted llama_stack/providers/impls/meta_reference/inference/quantization/test_fp8.py +0 −76
| @@ -1,76 +0,0 @@ | ||
| 1 | -# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | -# All rights reserved. | |
| 3 | -# | |
| 4 | -# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | -# the root directory of this source tree. | |
| 6 | - | |
| 7 | -# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 8 | -# This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement. | |
| 9 | - | |
| 10 | -import unittest | |
| 11 | - | |
| 12 | -import torch | |
| 13 | - | |
| 14 | -from fp8_impls import ffn_swiglu_fp8_dynamic, FfnQuantizeMode, quantize_fp8 | |
| 15 | -from hypothesis import given, settings, strategies as st | |
| 16 | -from torch import Tensor | |
| 17 | - | |
| 18 | - | |
| 19 | -@unittest.skipIf( | |
| 20 | - not torch.cuda.is_available() | |
| 21 | - or torch.cuda.get_device_properties(torch.cuda.current_device()).major < 9, | |
| 22 | - "Skip when H100 is not available", | |
| 23 | -) | |
| 24 | -class FP8Tests(unittest.TestCase): | |
| 25 | - @settings(deadline=None) | |
| 26 | - @given( | |
| 27 | - D=st.sampled_from([4096, 8192]), | |
| 28 | - HD_L=st.sampled_from([1280, 2560]), | |
| 29 | - B=st.sampled_from([1, 2]), | |
| 30 | - T=st.sampled_from([2048, 4096]), | |
| 31 | - UB=st.sampled_from([1000, 10000]), | |
| 32 | - ) | |
| 33 | - def test_fp8_ffn( | |
| 34 | - self, | |
| 35 | - D: int, # noqa | |
| 36 | - HD_L: int, | |
| 37 | - B: int, | |
| 38 | - T: int, | |
| 39 | - UB: float, | |
| 40 | - ) -> None: | |
| 41 | - x = torch.randn(size=(B, T, D), dtype=torch.bfloat16, device="cuda") * 0.1 | |
| 42 | - w1 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01 | |
| 43 | - w3 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01 | |
| 44 | - w2 = torch.randn(size=(D, HD_L), dtype=torch.bfloat16, device="cuda") * 0.1 | |
| 45 | - | |
| 46 | - x_q = quantize_fp8(x, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 47 | - w1_q = quantize_fp8(w1, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 48 | - w3_q = quantize_fp8(w3, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 49 | - w2_q = quantize_fp8(w2, UB, mode=FfnQuantizeMode.FP8_ROWWISE) | |
| 50 | - | |
| 51 | - def ref_ffn(x: Tensor, w1: Tensor, w3: Tensor, w2: Tensor) -> Tensor: | |
| 52 | - (B, T, D) = x.shape # noqa: N806 | |
| 53 | - (HD_L, D_) = w1.shape # noqa: N806 | |
| 54 | - assert D_ == D | |
| 55 | - | |
| 56 | - x1 = x.view(B * T, D) @ w1.T | |
| 57 | - x2 = x.view(B * T, D) @ w3.T | |
| 58 | - | |
| 59 | - z = torch.nn.functional.silu(x1) * x2 | |
| 60 | - return (z @ w2.T).view(B, T, D).to(torch.bfloat16) | |
| 61 | - | |
| 62 | - v = ffn_swiglu_fp8_dynamic(x, w1_q, w3_q, w2_q) | |
| 63 | - | |
| 64 | - # Fake quant | |
| 65 | - x = x_q.weight.bfloat16() * x_q.scale.unsqueeze(-1) | |
| 66 | - w1 = w1_q.weight.bfloat16() * w1_q.scale.unsqueeze(-1) | |
| 67 | - w3 = w3_q.weight.bfloat16() * w3_q.scale.unsqueeze(-1) | |
| 68 | - w2 = w2_q.weight.bfloat16() * w2_q.scale.unsqueeze(-1) | |
| 69 | - | |
| 70 | - v_ref = ref_ffn(x, w1, w3, w2) | |
| 71 | - | |
| 72 | - torch.testing.assert_close(v_ref, v, atol=4.0e-3, rtol=4.0e-3) | |
| 73 | - | |
| 74 | - | |
| 75 | -if __name__ == "__main__": | |
| 76 | - unittest.main() |
added llama_stack/scripts/__init__.py +5 −0
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. |
added llama_stack/scripts/run_tests.sh +16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | + | |
| 3 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 4 | +# All rights reserved. | |
| 5 | +# | |
| 6 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 7 | +# the root directory of this source tree. | |
| 8 | + | |
| 9 | +THIS_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" | |
| 10 | + | |
| 11 | +set -euo pipefail | |
| 12 | +set -x | |
| 13 | + | |
| 14 | +stack_dir=$(dirname $THIS_DIR) | |
| 15 | +models_dir=$(dirname $(dirname $stack_dir))/llama-models | |
| 16 | +PYTHONPATH=$models_dir:$stack_dir pytest -p no:warnings --asyncio-mode auto --tb=short |