├── README.md
├── clock-based-rolling-window-rpm-tpm-tester
├── code_generation_prompt.md
├── test_setup.py
├── readme.md
├── utils.py
└── bedrock_tpm_test.ipynb
├── .gitignore
├── LICENSE
├── stress.test.bedrock.py
├── utils
└── utils.py
└── bedrock-latency-benchmark.ipynb
/README.md:
--------------------------------------------------------------------------------
1 | # Latency Benchmarking tools for Amazon Bedrock
2 | A collection of tools to measure inference latency for foundations models in Amazon Bedrock and OpenAI. Reports time to first token and total time.
3 | 1. [bedrock-latency-benchmark.ipynb](./bedrock-latency-benchmark.ipynb) - Measure LLM single request latency across scenarios like:
4 | - Different number of in/out tokens
5 | - Compare latency across models from Amazon Bedrock and OpenAI.
6 | - Latency for the same model across AWS Regions.
7 | 2. [stress.test.bedrock.py](./stress.test.bedrock.py) - A utility to stress test Claude 3 models on Bedrock with high number of concurrent requests (e.g., launch 1000 requests/min).
8 | 3. [clock-based-rolling-window-rpm-tpm-tester](./clock-based-rolling-window-rpm-tpm-tester/) - Test whether Bedrock TPM limits are based on absolute minutes (clock-based) or relative minutes (rolling window). Determines if quota resets at xx:00 or 60 seconds after first usage.
9 | ## Installing
10 | 1. `git clone https://github.com/gilinachum/bedrock-latency`
11 | 2. Open relevant notebook.
12 | ## License
13 | [Apache License Version 2.0](LICENSE)
14 |
--------------------------------------------------------------------------------
/clock-based-rolling-window-rpm-tpm-tester/code_generation_prompt.md:
--------------------------------------------------------------------------------
1 | I want to create a test to find out of Bedrock inference TPM limits is per absolute minute, or relative minute want to test bedrock API to answer this question.
2 |
3 | Use Nova Pro model, for which I have 8,000 tokens per minute (TPM).I want to test the following scenarios:
4 | 1. Consume all TPM at xx:35 seconds (expect 200OK responses), then make sure your get 429 for the next request that is 1000 tokens long, before the end of the minute.
5 | 2. Try again 35 seconds later, at yy:05 seconds. Then see if you get a 200OK or a 429 response code for this request.
6 | 3. Try another 1000 request at yy:50, this request should be 200OK becuase both the absolute minute passed and more than 60 seconds passed.
7 | 4. Summarize the requests, tokens used per request, the time they were made and the response you got. Then summarize the conclusion.
8 |
9 | Use python virtual environment.
10 | Create an IPython notebook to test for it. Put relevant helping code in utils.py
11 | Use Bedrock Converse API. Make sure to turn off Boto3 automatic retries to avoid interfearing with throttling detection.
12 | Pack the requests with lots of '0' to reach the needed input tokens.
13 | Serach the internet using Tavili as needed to find relevant APIs.
14 | Read https://github.com/gilinachum/bedrock-latency/blob/main/stress.test.bedrock.py and https://github.com/gilinachum/bedrock-latency/blob/main/bedrock-latency-benchmark.ipynb to be inspired.
--------------------------------------------------------------------------------
/clock-based-rolling-window-rpm-tpm-tester/test_setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | Quick test to verify AWS credentials and Bedrock access
4 | """
5 |
6 | import boto3
7 | from botocore.exceptions import NoCredentialsError, ClientError
8 | from utils import BedrockTPMTester
9 |
10 | def test_aws_credentials():
11 | """Test if AWS credentials are available."""
12 | try:
13 | session = boto3.Session()
14 | credentials = session.get_credentials()
15 | if credentials is None:
16 | return False, "No AWS credentials found"
17 |
18 | # Try to get caller identity
19 | sts = session.client('sts')
20 | identity = sts.get_caller_identity()
21 | return True, f"AWS Account: {identity.get('Account')}, User: {identity.get('Arn')}"
22 | except Exception as e:
23 | return False, str(e)
24 |
25 | def test_bedrock_connection():
26 | """Test basic Bedrock connection and model access."""
27 | try:
28 | # First test credentials
29 | creds_ok, creds_msg = test_aws_credentials()
30 | if not creds_ok:
31 | print(f"✗ AWS Credentials Error: {creds_msg}")
32 | return False
33 | else:
34 | print(f"✓ AWS Credentials: {creds_msg}")
35 |
36 | tester = BedrockTPMTester()
37 | print(f"✓ Bedrock client initialized successfully")
38 | print(f"✓ Using model: {tester.model_id}")
39 |
40 | # Test a small request
41 | print("Testing small request...")
42 | status_code, error, response_time = tester.make_bedrock_request(100)
43 |
44 | if status_code == 200:
45 | print(f"✓ Test request successful (response time: {response_time:.2f}s)")
46 | return True
47 | else:
48 | print(f"✗ Test request failed with status {status_code}: {error}")
49 | return False
50 |
51 | except Exception as e:
52 | print(f"✗ Error: {e}")
53 | return False
54 |
55 | if __name__ == "__main__":
56 | print("Testing Bedrock TPM Test Setup")
57 | print("=" * 40)
58 |
59 | success = test_bedrock_connection()
60 |
61 | if success:
62 | print("\n✓ Setup test passed! Ready to run TPM limit tests.")
63 | print("You can now run the Jupyter notebook: bedrock_tpm_test.ipynb")
64 | else:
65 | print("\n✗ Setup test failed. Please check:")
66 | print(" - AWS credentials are configured")
67 | print(" - You have access to Bedrock in your region")
68 | print(" - Nova Pro model is available in your account")
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 | .ipynb_checkpoints/*
81 |
82 | # IPython
83 | profile_default/
84 | ipython_config.py
85 |
86 | # pyenv
87 | # For a library or package, you might want to ignore these files since the code is
88 | # intended to run in multiple environments; otherwise, check them in:
89 | # .python-version
90 |
91 | # pipenv
92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
95 | # install all needed dependencies.
96 | #Pipfile.lock
97 |
98 | # poetry
99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100 | # This is especially recommended for binary packages to ensure reproducibility, and is more
101 | # commonly ignored for libraries.
102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103 | #poetry.lock
104 |
105 | # pdm
106 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107 | #pdm.lock
108 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109 | # in version control.
110 | # https://pdm.fming.dev/#use-with-ide
111 | .pdm.toml
112 |
113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114 | __pypackages__/
115 |
116 | # Celery stuff
117 | celerybeat-schedule
118 | celerybeat.pid
119 |
120 | # SageMath parsed files
121 | *.sage.py
122 |
123 | # Environments
124 | .env
125 | .venv
126 | env/
127 | venv/
128 | ENV/
129 | env.bak/
130 | venv.bak/
131 | *key.py
132 |
133 | # Spyder project settings
134 | .spyderproject
135 | .spyproject
136 |
137 | # Rope project settings
138 | .ropeproject
139 |
140 | # mkdocs documentation
141 | /site
142 |
143 | # mypy
144 | .mypy_cache/
145 | .dmypy.json
146 | dmypy.json
147 |
148 | # Pyre type checker
149 | .pyre/
150 |
151 | # pytype static type analyzer
152 | .pytype/
153 |
154 | # Cython debug symbols
155 | cython_debug/
156 |
157 | # PyCharm
158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160 | # and can be added to the global gitignore or merged into this file. For a more nuclear
161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162 | #.idea/
163 | .DS_Store
164 | clock-based-rolling-window-rpm-tpm-tester/.DS_Store
165 |
--------------------------------------------------------------------------------
/clock-based-rolling-window-rpm-tpm-tester/readme.md:
--------------------------------------------------------------------------------
1 | # Bedrock TPM Limit Testing: Absolute vs Relative Minutes
2 |
3 | This project tests whether AWS Bedrock's TPM (Tokens Per Minute) limits are based on:
4 | - **Absolute minutes**: Quota resets at the start of each clock minute (xx:00)
5 | - **Relative minutes**: Quota resets 60 seconds after first token usage
6 |
7 | ## Overview
8 |
9 | AWS Bedrock enforces TPM limits to control usage, but the exact timing mechanism isn't clearly documented. This test determines whether the quota operates on:
10 |
11 | 1. **Clock-based (Absolute)**: Quota resets every minute at xx:00 seconds
12 | 2. **Rolling window (Relative)**: Quota resets 60 seconds after first consumption
13 |
14 | ## Test Strategy
15 |
16 | The test uses Nova Pro model (8,000 TPM limit) with the following sequence:
17 |
18 | 1. **xx:35** - Consume all 8,000 TPM quota in chunks
19 | 2. **xx:45-59** - Make 1000-token request (should get 429 throttled)
20 | 3. **yy:05** - Make 1000-token request (KEY DIFFERENTIATOR)
21 | 4. **yy:50** - Make 1000-token request (should always succeed)
22 |
23 | ### Expected Results
24 |
25 | | Timing Model | Request at yy:05 | Conclusion |
26 | |--------------|------------------|------------|
27 | | **Absolute** | 200 OK | Quota reset at new minute |
28 | | **Relative** | 429 Throttled | Must wait full 60 seconds |
29 |
30 | ## Files
31 |
32 | - `utils.py` - Core testing utilities with BedrockTPMTester class
33 | - `bedrock_tpm_test.ipynb` - Interactive Jupyter notebook for running tests
34 | - `test_setup.py` - Setup verification script
35 | - `code_generation_prompt.md` - Original requirements and prompt
36 |
37 | ## Setup
38 |
39 | ### Prerequisites
40 |
41 | - Python 3.8+
42 | - AWS credentials configured
43 | - Access to AWS Bedrock Nova Pro model
44 | - 8,000 TPM quota available
45 |
46 | ### Installation
47 |
48 | ```bash
49 | # Activate virtual environment
50 | source .venv/bin/activate
51 |
52 | # Install dependencies
53 | pip install boto3 jupyter ipython
54 |
55 | # Verify setup
56 | python test_setup.py
57 | ```
58 |
59 | ## Usage
60 |
61 | ### Quick Test
62 |
63 | ```bash
64 | python test_setup.py
65 | ```
66 |
67 | This verifies:
68 | - AWS credentials are working
69 | - Bedrock access is available
70 | - Nova Pro model is accessible
71 |
72 | ### Full TPM Test
73 |
74 | ```bash
75 | jupyter notebook bedrock_tpm_test.ipynb
76 | ```
77 |
78 | Run all cells in sequence. The notebook will:
79 | 1. Wait for precise timing (xx:35)
80 | 2. Consume TPM quota systematically
81 | 3. Test quota behavior at key intervals
82 | 4. Analyze results and provide conclusion
83 |
84 | ## Key Features
85 |
86 | ### Precise Timing Control
87 | - Waits for exact seconds within minutes
88 | - Ensures consistent test conditions
89 |
90 | ### Token Padding
91 | - Uses '0' characters to reach target token counts
92 | - Roughly 4 characters per token estimation
93 |
94 | ### No Automatic Retries
95 | - Boto3 retries disabled for immediate throttling detection
96 | - Essential for accurate 429 response timing
97 |
98 | ### Comprehensive Logging
99 | - Tracks all requests with precise timestamps
100 | - Records tokens, status codes, and errors
101 |
102 | ### Automatic Analysis
103 | - Determines absolute vs relative based on results
104 | - Provides clear conclusion with reasoning
105 |
106 | ## Technical Details
107 |
108 | ### BedrockTPMTester Class
109 |
110 | ```python
111 | # Initialize with retry disabled
112 | tester = BedrockTPMTester(region_name='us-east-1')
113 |
114 | # Consume quota in chunks
115 | results = tester.consume_tpm_quota(total_tokens=8000, chunk_size=1000)
116 |
117 | # Make individual test requests
118 | status_code, error, response_time = tester.make_bedrock_request(1000)
119 | ```
120 |
121 | ### Timing Functions
122 |
123 | ```python
124 | # Wait for specific second
125 | tester.wait_until_second(35)
126 |
127 | # Log results with timestamps
128 | tester.log_result("test_name", timestamp, tokens, status_code, error)
129 | ```
130 |
131 | ## Troubleshooting
132 |
133 | ### Common Issues
134 |
135 | 1. **Credentials Error**
136 | ```
137 | Error when retrieving credentials from custom-process
138 | ```
139 | - Configure AWS credentials: `aws configure`
140 | - Or set environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`
141 |
142 | 2. **Model Access Denied**
143 | ```
144 | AccessDeniedException: User is not authorized
145 | ```
146 | - Enable Nova Pro model in Bedrock console
147 | - Check IAM permissions for bedrock:InvokeModel
148 |
149 | 3. **Quota Already Exhausted**
150 | ```
151 | ThrottlingException: Too many requests
152 | ```
153 | - Wait for quota to reset
154 | - Check current usage in AWS console
155 |
156 | ### Debug Mode
157 |
158 | Add debug logging to see detailed request/response info:
159 |
160 | ```python
161 | import logging
162 | logging.basicConfig(level=logging.DEBUG)
163 | ```
164 |
165 | ## Results Interpretation
166 |
167 | The test output will show:
168 |
169 | ```
170 | TEST SUMMARY
171 | ============
172 | Test: Consume_batch_1
173 | Time: 14:35:01 (minute 35, second 1)
174 | Tokens: 1000
175 | Status: 200
176 |
177 | Test: Test_at_next_minute_05
178 | Time: 14:36:05 (minute 36, second 5)
179 | Tokens: 1000
180 | Status: 200 # <-- KEY RESULT
181 |
182 | CONCLUSION:
183 | ✓ TPM limits appear to be based on ABSOLUTE MINUTES
184 | The quota reset at the start of a new clock minute
185 | ```
186 |
187 | ## Contributing
188 |
189 | When modifying the test:
190 |
191 | 1. Maintain precise timing requirements
192 | 2. Keep token calculations accurate
193 | 3. Preserve comprehensive logging
194 | 4. Test with different regions/models as needed
195 |
196 | ## License
197 |
198 | This project is for testing and educational purposes. Follow AWS service terms and usage policies.
--------------------------------------------------------------------------------
/clock-based-rolling-window-rpm-tpm-tester/utils.py:
--------------------------------------------------------------------------------
1 | import boto3
2 | import time
3 | import json
4 | from datetime import datetime
5 | from typing import Dict, List, Tuple, Optional
6 |
7 | class BedrockTPMTester:
8 | def __init__(self, region_name: str = 'us-east-1'):
9 | """Initialize Bedrock client for TPM testing."""
10 | # Disable automatic retries to get immediate throttling responses
11 | from botocore.config import Config
12 | config = Config(
13 | retries={'max_attempts': 1, 'mode': 'standard'},
14 | read_timeout=30,
15 | connect_timeout=10
16 | )
17 | self.client = boto3.client('bedrock-runtime', region_name=region_name, config=config)
18 | self.model_id = 'amazon.nova-pro-v1:0'
19 | self.test_results = []
20 |
21 | def create_large_prompt(self, target_tokens: int) -> str:
22 | """Create a prompt with approximately target_tokens input tokens."""
23 | # Rough estimate: 1 token ≈ 4 characters for English text
24 | # Using '0' characters to pad the prompt
25 | base_prompt = "Please analyze the following data: "
26 | padding_needed = max(0, (target_tokens * 4) - len(base_prompt))
27 | padding = '0' * padding_needed
28 | return base_prompt + padding
29 |
30 | def make_bedrock_request(self, input_tokens: int) -> Tuple[int, Optional[str], float]:
31 | """
32 | Make a Bedrock Converse API request.
33 |
34 | Returns:
35 | Tuple of (status_code, error_message, response_time)
36 | """
37 | prompt = self.create_large_prompt(input_tokens)
38 |
39 | request_payload = {
40 | "modelId": self.model_id,
41 | "messages": [
42 | {
43 | "role": "user",
44 | "content": [{"text": prompt}]
45 | }
46 | ],
47 | "inferenceConfig": {
48 | "maxTokens": 10, # Minimal output to focus on input token testing
49 | "temperature": 0.1
50 | }
51 | }
52 |
53 | start_time = time.time()
54 | try:
55 | response = self.client.converse(**request_payload)
56 | end_time = time.time()
57 | return 200, None, end_time - start_time
58 | except Exception as e:
59 | end_time = time.time()
60 | error_msg = str(e)
61 | # Check if it's a throttling error (429)
62 | if "ThrottlingException" in error_msg or "too many requests" in error_msg.lower():
63 | return 429, error_msg, end_time - start_time
64 | else:
65 | return 500, error_msg, end_time - start_time
66 |
67 | def wait_until_second(self, target_second: int):
68 | """Wait until the specified second of the current minute."""
69 | while True:
70 | current_time = datetime.now()
71 | if current_time.second == target_second:
72 | break
73 | time.sleep(0.1) # Check every 100ms
74 |
75 | def consume_tpm_quota(self, total_tokens: int, chunk_size: int = 1000) -> List[Dict]:
76 | """
77 | Consume TPM quota by making multiple requests.
78 |
79 | Args:
80 | total_tokens: Total tokens to consume
81 | chunk_size: Tokens per request
82 |
83 | Returns:
84 | List of request results
85 | """
86 | results = []
87 | tokens_consumed = 0
88 |
89 | while tokens_consumed < total_tokens:
90 | remaining_tokens = total_tokens - tokens_consumed
91 | request_tokens = min(chunk_size, remaining_tokens)
92 |
93 | timestamp = datetime.now()
94 | status_code, error, response_time = self.make_bedrock_request(request_tokens)
95 |
96 | result = {
97 | 'timestamp': timestamp.isoformat(),
98 | 'second': timestamp.second,
99 | 'tokens_requested': request_tokens,
100 | 'status_code': status_code,
101 | 'error': error,
102 | 'response_time': response_time
103 | }
104 |
105 | results.append(result)
106 | tokens_consumed += request_tokens
107 |
108 | # If we get throttled, stop consuming
109 | if status_code == 429:
110 | break
111 |
112 | # Small delay between requests to avoid overwhelming
113 | time.sleep(0.1)
114 |
115 | return results
116 |
117 | def log_result(self, test_name: str, timestamp: datetime, tokens: int,
118 | status_code: int, error: Optional[str] = None):
119 | """Log a test result."""
120 | result = {
121 | 'test_name': test_name,
122 | 'timestamp': timestamp.isoformat(),
123 | 'minute': timestamp.minute,
124 | 'second': timestamp.second,
125 | 'tokens': tokens,
126 | 'status_code': status_code,
127 | 'error': error
128 | }
129 | self.test_results.append(result)
130 | print(f"[{timestamp.strftime('%H:%M:%S')}] {test_name}: {tokens} tokens -> {status_code}")
131 | if error:
132 | print(f" Error: {error}")
133 |
134 | def print_summary(self):
135 | """Print a summary of all test results."""
136 | print("\n" + "="*80)
137 | print("TEST SUMMARY")
138 | print("="*80)
139 |
140 | for result in self.test_results:
141 | timestamp = datetime.fromisoformat(result['timestamp'])
142 | print(f"Test: {result['test_name']}")
143 | print(f" Time: {timestamp.strftime('%H:%M:%S')} (minute {result['minute']}, second {result['second']})")
144 | print(f" Tokens: {result['tokens']}")
145 | print(f" Status: {result['status_code']}")
146 | if result['error']:
147 | print(f" Error: {result['error']}")
148 | print()
149 |
150 | # Analysis
151 | print("ANALYSIS:")
152 | print("-" * 40)
153 |
154 | # Group by test phases
155 | consume_requests = [r for r in self.test_results if 'consume' in r['test_name'].lower()]
156 | test_requests = [r for r in self.test_results if 'test' in r['test_name'].lower()]
157 |
158 | if consume_requests:
159 | total_consumed = sum(r['tokens'] for r in consume_requests if r['status_code'] == 200)
160 | print(f"Total tokens consumed in quota exhaustion: {total_consumed}")
161 |
162 | if test_requests:
163 | print("Test request results:")
164 | for req in test_requests:
165 | status_text = "SUCCESS" if req['status_code'] == 200 else "THROTTLED"
166 | print(f" - {req['test_name']}: {status_text}")
167 |
168 | # Determine if limits are absolute or relative
169 | if len(test_requests) >= 2:
170 | first_test = test_requests[0]
171 | second_test = test_requests[1]
172 |
173 | print(f"\nCONCLUSION:")
174 | print("-" * 40)
175 |
176 | if first_test['status_code'] == 429 and second_test['status_code'] == 200:
177 | print("✓ TPM limits appear to be based on ABSOLUTE MINUTES")
178 | print(" The quota reset at the start of a new clock minute")
179 | elif first_test['status_code'] == 429 and second_test['status_code'] == 429:
180 | print("✓ TPM limits appear to be based on RELATIVE MINUTES")
181 | print(" The quota requires 60 seconds to pass from first usage")
182 | else:
183 | print("? Results are inconclusive - may need to repeat test")
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/clock-based-rolling-window-rpm-tpm-tester/bedrock_tpm_test.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Bedrock TPM Limit Testing: Absolute vs Relative Minutes\n",
8 | "\n",
9 | "This notebook tests whether AWS Bedrock's TPM (Tokens Per Minute) limits are based on:\n",
10 | "- **Absolute minutes**: Quota resets at the start of each clock minute (xx:00)\n",
11 | "- **Relative minutes**: Quota resets 60 seconds after first token usage\n",
12 | "\n",
13 | "## Test Plan\n",
14 | "1. Consume all 8,000 TPM at xx:35 seconds\n",
15 | "2. Make a 1000-token request before the minute ends (should get 429)\n",
16 | "3. Make a 1000-token request at yy:05 seconds (35 seconds later)\n",
17 | "4. Make a 1000-token request at yy:50 seconds\n",
18 | "5. Analyze results to determine the quota reset behavior"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": 1,
24 | "metadata": {},
25 | "outputs": [
26 | {
27 | "name": "stdout",
28 | "output_type": "stream",
29 | "text": [
30 | "Initialized Bedrock TPM Tester for model: amazon.nova-pro-v1:0\n",
31 | "Current time: 13:17:59\n"
32 | ]
33 | }
34 | ],
35 | "source": [
36 | "import sys\n",
37 | "import time\n",
38 | "from datetime import datetime\n",
39 | "from utils import BedrockTPMTester\n",
40 | "\n",
41 | "# Initialize the tester\n",
42 | "tester = BedrockTPMTester(region_name='us-east-1')\n",
43 | "print(f\"Initialized Bedrock TPM Tester for model: {tester.model_id}\")\n",
44 | "print(f\"Current time: {datetime.now().strftime('%H:%M:%S')}\")"
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "metadata": {},
50 | "source": [
51 | "## Step 1: Wait for xx:35 and Consume All TPM Quota"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": 2,
57 | "metadata": {},
58 | "outputs": [
59 | {
60 | "name": "stdout",
61 | "output_type": "stream",
62 | "text": [
63 | "Waiting for xx:35 seconds...\n",
64 | "Starting quota consumption at: 13:18:35\n",
65 | "[13:18:35] Consume_batch_1: 1000 tokens -> 200\n",
66 | "[13:18:35] Consume_batch_2: 1000 tokens -> 200\n",
67 | "[13:18:36] Consume_batch_3: 1000 tokens -> 429\n",
68 | " Error: An error occurred (ThrottlingException) when calling the Converse operation (reached max retries: 1): Too many requests, please wait before trying again.\n",
69 | "\n",
70 | "Total tokens consumed: 2000\n",
71 | "Consumption completed at: 13:18:36\n"
72 | ]
73 | }
74 | ],
75 | "source": [
76 | "# Wait until 35 seconds of the current minute\n",
77 | "print(\"Waiting for xx:35 seconds...\")\n",
78 | "tester.wait_until_second(35)\n",
79 | "\n",
80 | "start_time = datetime.now()\n",
81 | "print(f\"Starting quota consumption at: {start_time.strftime('%H:%M:%S')}\")\n",
82 | "\n",
83 | "# Consume 8000 tokens (our TPM limit) in chunks\n",
84 | "consume_results = tester.consume_tpm_quota(total_tokens=8000, chunk_size=1000)\n",
85 | "\n",
86 | "# Log the consumption results\n",
87 | "total_consumed = 0\n",
88 | "for i, result in enumerate(consume_results):\n",
89 | " if result['status_code'] == 200:\n",
90 | " total_consumed += result['tokens_requested']\n",
91 | " tester.log_result(\n",
92 | " f\"Consume_batch_{i+1}\",\n",
93 | " datetime.fromisoformat(result['timestamp']),\n",
94 | " result['tokens_requested'],\n",
95 | " result['status_code'],\n",
96 | " result['error']\n",
97 | " )\n",
98 | "\n",
99 | "print(f\"\\nTotal tokens consumed: {total_consumed}\")\n",
100 | "print(f\"Consumption completed at: {datetime.now().strftime('%H:%M:%S')}\")"
101 | ]
102 | },
103 | {
104 | "cell_type": "markdown",
105 | "metadata": {},
106 | "source": [
107 | "## Step 2: Test Request Before Minute Ends (Should Get 429)"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 3,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "name": "stdout",
117 | "output_type": "stream",
118 | "text": [
119 | "Making test request at: 13:18:37\n",
120 | "[13:18:37] Test_before_minute_end: 1000 tokens -> 429\n",
121 | " Error: An error occurred (ThrottlingException) when calling the Converse operation (reached max retries: 1): Too many requests, please wait before trying again.\n",
122 | "Result: 429 (throttled)\n"
123 | ]
124 | }
125 | ],
126 | "source": [
127 | "# Make a test request before the minute ends\n",
128 | "current_time = datetime.now()\n",
129 | "print(f\"Making test request at: {current_time.strftime('%H:%M:%S')}\")\n",
130 | "\n",
131 | "status_code, error, response_time = tester.make_bedrock_request(1000)\n",
132 | "tester.log_result(\n",
133 | " \"Test_before_minute_end\",\n",
134 | " current_time,\n",
135 | " 1000,\n",
136 | " status_code,\n",
137 | " error\n",
138 | ")\n",
139 | "\n",
140 | "expected_result = \"429 (throttled)\" if status_code == 429 else f\"{status_code} (unexpected)\"\n",
141 | "print(f\"Result: {expected_result}\")"
142 | ]
143 | },
144 | {
145 | "cell_type": "markdown",
146 | "metadata": {},
147 | "source": [
148 | "## Step 3: Wait for yy:05 and Test Again"
149 | ]
150 | },
151 | {
152 | "cell_type": "code",
153 | "execution_count": 4,
154 | "metadata": {},
155 | "outputs": [
156 | {
157 | "name": "stdout",
158 | "output_type": "stream",
159 | "text": [
160 | "Waiting for yy:05 seconds (35 seconds after initial consumption)...\n",
161 | "Making test request at: 13:19:05\n",
162 | "[13:19:05] Test_at_next_minute_05: 1000 tokens -> 200\n",
163 | "✓ Request succeeded - suggests ABSOLUTE minute limits\n"
164 | ]
165 | }
166 | ],
167 | "source": [
168 | "# Wait until 5 seconds of the next minute\n",
169 | "print(\"Waiting for yy:05 seconds (35 seconds after initial consumption)...\")\n",
170 | "tester.wait_until_second(5)\n",
171 | "\n",
172 | "current_time = datetime.now()\n",
173 | "print(f\"Making test request at: {current_time.strftime('%H:%M:%S')}\")\n",
174 | "\n",
175 | "status_code, error, response_time = tester.make_bedrock_request(1000)\n",
176 | "tester.log_result(\n",
177 | " \"Test_at_next_minute_05\",\n",
178 | " current_time,\n",
179 | " 1000,\n",
180 | " status_code,\n",
181 | " error\n",
182 | ")\n",
183 | "\n",
184 | "if status_code == 200:\n",
185 | " print(\"✓ Request succeeded - suggests ABSOLUTE minute limits\")\n",
186 | "elif status_code == 429:\n",
187 | " print(\"✗ Request throttled - suggests RELATIVE minute limits\")\n",
188 | "else:\n",
189 | " print(f\"? Unexpected status code: {status_code}\")"
190 | ]
191 | },
192 | {
193 | "cell_type": "markdown",
194 | "metadata": {},
195 | "source": [
196 | "## Step 4: Test at yy:50 (Should Always Succeed)"
197 | ]
198 | },
199 | {
200 | "cell_type": "code",
201 | "execution_count": 5,
202 | "metadata": {},
203 | "outputs": [
204 | {
205 | "name": "stdout",
206 | "output_type": "stream",
207 | "text": [
208 | "Waiting for yy:50 seconds...\n",
209 | "Making final test request at: 13:19:50\n",
210 | "[13:19:50] Test_at_minute_50: 1000 tokens -> 200\n",
211 | "✓ Request succeeded as expected (>60 seconds passed)\n"
212 | ]
213 | }
214 | ],
215 | "source": [
216 | "# Wait until 50 seconds of the current minute\n",
217 | "print(\"Waiting for yy:50 seconds...\")\n",
218 | "tester.wait_until_second(50)\n",
219 | "\n",
220 | "current_time = datetime.now()\n",
221 | "print(f\"Making final test request at: {current_time.strftime('%H:%M:%S')}\")\n",
222 | "\n",
223 | "status_code, error, response_time = tester.make_bedrock_request(1000)\n",
224 | "tester.log_result(\n",
225 | " \"Test_at_minute_50\",\n",
226 | " current_time,\n",
227 | " 1000,\n",
228 | " status_code,\n",
229 | " error\n",
230 | ")\n",
231 | "\n",
232 | "if status_code == 200:\n",
233 | " print(\"✓ Request succeeded as expected (>60 seconds passed)\")\n",
234 | "else:\n",
235 | " print(f\"✗ Unexpected result: {status_code}\")"
236 | ]
237 | },
238 | {
239 | "cell_type": "markdown",
240 | "metadata": {},
241 | "source": [
242 | "## Step 5: Results Summary and Analysis"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "execution_count": 6,
248 | "metadata": {},
249 | "outputs": [
250 | {
251 | "name": "stdout",
252 | "output_type": "stream",
253 | "text": [
254 | "\n",
255 | "================================================================================\n",
256 | "TEST SUMMARY\n",
257 | "================================================================================\n",
258 | "Test: Consume_batch_1\n",
259 | " Time: 13:18:35 (minute 18, second 35)\n",
260 | " Tokens: 1000\n",
261 | " Status: 200\n",
262 | "\n",
263 | "Test: Consume_batch_2\n",
264 | " Time: 13:18:35 (minute 18, second 35)\n",
265 | " Tokens: 1000\n",
266 | " Status: 200\n",
267 | "\n",
268 | "Test: Consume_batch_3\n",
269 | " Time: 13:18:36 (minute 18, second 36)\n",
270 | " Tokens: 1000\n",
271 | " Status: 429\n",
272 | " Error: An error occurred (ThrottlingException) when calling the Converse operation (reached max retries: 1): Too many requests, please wait before trying again.\n",
273 | "\n",
274 | "Test: Test_before_minute_end\n",
275 | " Time: 13:18:37 (minute 18, second 37)\n",
276 | " Tokens: 1000\n",
277 | " Status: 429\n",
278 | " Error: An error occurred (ThrottlingException) when calling the Converse operation (reached max retries: 1): Too many requests, please wait before trying again.\n",
279 | "\n",
280 | "Test: Test_at_next_minute_05\n",
281 | " Time: 13:19:05 (minute 19, second 5)\n",
282 | " Tokens: 1000\n",
283 | " Status: 200\n",
284 | "\n",
285 | "Test: Test_at_minute_50\n",
286 | " Time: 13:19:50 (minute 19, second 50)\n",
287 | " Tokens: 1000\n",
288 | " Status: 200\n",
289 | "\n",
290 | "ANALYSIS:\n",
291 | "----------------------------------------\n",
292 | "Total tokens consumed in quota exhaustion: 2000\n",
293 | "Test request results:\n",
294 | " - Test_before_minute_end: THROTTLED\n",
295 | " - Test_at_next_minute_05: SUCCESS\n",
296 | " - Test_at_minute_50: SUCCESS\n",
297 | "\n",
298 | "CONCLUSION:\n",
299 | "----------------------------------------\n",
300 | "✓ TPM limits appear to be based on ABSOLUTE MINUTES\n",
301 | " The quota reset at the start of a new clock minute\n"
302 | ]
303 | }
304 | ],
305 | "source": [
306 | "# Print comprehensive summary\n",
307 | "tester.print_summary()"
308 | ]
309 | },
310 | {
311 | "cell_type": "markdown",
312 | "metadata": {},
313 | "source": [
314 | "## Additional Analysis\n",
315 | "\n",
316 | "Based on the test results above:\n",
317 | "\n",
318 | "### If TPM limits are ABSOLUTE (clock-based):\n",
319 | "- Quota consumption at xx:35 fills the quota for that minute\n",
320 | "- Request before minute end (xx:45-59) should get 429\n",
321 | "- Request at yy:05 should get 200 (new minute, fresh quota)\n",
322 | "- Request at yy:50 should get 200\n",
323 | "\n",
324 | "### If TPM limits are RELATIVE (rolling window):\n",
325 | "- Quota consumption at xx:35 starts a 60-second window\n",
326 | "- Request before minute end should get 429\n",
327 | "- Request at yy:05 should get 429 (only 30 seconds passed)\n",
328 | "- Request at yy:50 should get 200 (>60 seconds passed)\n",
329 | "\n",
330 | "The key differentiator is the result at yy:05 seconds."
331 | ]
332 | }
333 | ],
334 | "metadata": {
335 | "kernelspec": {
336 | "display_name": ".venv",
337 | "language": "python",
338 | "name": "python3"
339 | },
340 | "language_info": {
341 | "codemirror_mode": {
342 | "name": "ipython",
343 | "version": 3
344 | },
345 | "file_extension": ".py",
346 | "mimetype": "text/x-python",
347 | "name": "python",
348 | "nbconvert_exporter": "python",
349 | "pygments_lexer": "ipython3",
350 | "version": "3.13.2"
351 | }
352 | },
353 | "nbformat": 4,
354 | "nbformat_minor": 4
355 | }
356 |
--------------------------------------------------------------------------------
/stress.test.bedrock.py:
--------------------------------------------------------------------------------
1 | """
2 | Bedrock Stress Testing Utility
3 |
4 | This script simulates multiple concurrent requests to perform stress testing
5 | and load testing on Amazon Bedrock, AWS's service for building generative AI
6 | applications.
7 |
8 | Usage:
9 | python stress.test.bedrock.py [options]
10 |
11 | Options:
12 | --threads INT Number of concurrent threads (default: 10)
13 | --invocations INT Invocations per thread (default: 5)
14 | --sleep FLOAT Sleep between invocations in ms (default: 0)
15 | --duration INT Test duration in seconds (default: None)
16 | --model-id STRING Bedrock model ID (default: anthropic.claude-3-haiku-20240307-v1:0)
17 | --region STRING Bedrock region (default: us-east-1)
18 | --max-tokens INT Maximum tokens for response (default: 500)
19 | --temperature FLOAT Sampling temperature (default: 0)
20 | --system-prompt STRING System prompt (default: "You are a helpful assistant.")
21 | --user-message STRING User message (default: "Explain quantum computing briefly")
22 | --output-csv STRING Output CSV file path (default: None)
23 | --log-level STRING Logging level (default: INFO)
24 | --log-file STRING Log file path (default: None)
25 | --grow-message Boolean Whether to grow the input message size across calls
26 | --max-message-length-characters INT Maximum length of grown message (default=128_000*8)
27 | --print-request-metrics Boolean Print metrics for each request
28 | --print-request-metrics-csv STRING Per-request metrics CSV full file path
29 |
30 | Example:
31 | # A total of 100 requests with 10 requests in parallel, overall results and per requests results are written to CSV
32 | python stress.test.bedrock.py --threads 10 --invocations 10 --sleep 0 --output-csv overall-metrics.csv --print-request-metrics-csv requests_metrics.csv
33 | # A total of 16 requests where the message size doubles each time. Useful to test latecy across increasing message size
34 | python ./stress.test.bedrock.py --region us-west-2 --model-id us.anthropic.claude-3-haiku-20240307-v1:0 --grow-message --print-request-metrics --threads 1 --invocations 16 --max-tokens 250 --print-request-metrics-csv requests_metrics.csv
35 | """
36 |
37 | import argparse
38 | import csv
39 | import json
40 | import os
41 | import threading
42 | import time
43 | from concurrent.futures import ThreadPoolExecutor
44 | from statistics import mean, median
45 |
46 | import boto3
47 | import botocore
48 | from botocore.exceptions import ClientError
49 | from tqdm import tqdm
50 |
51 | import logging
52 |
53 | # Set up argument parser
54 | parser = argparse.ArgumentParser(description="Bedrock Stress Testing Utility")
55 | parser.add_argument("--threads", type=int, default=10, help="Number of concurrent threads")
56 | parser.add_argument("--invocations", type=int, default=5, help="Invocations per thread")
57 | parser.add_argument("--sleep", type=float, default=0, help="Sleep between invocations in ms")
58 | parser.add_argument("--duration", type=int, default=None, help="Test duration in seconds")
59 | parser.add_argument("--model-id", type=str, default="anthropic.claude-3-haiku-20240307-v1:0", help="Bedrock model ID")
60 | parser.add_argument("--region", type=str, default="us-east-1", help="Bedrock region name")
61 | parser.add_argument("--max-tokens", type=int, default=500, help="Maximum tokens for response")
62 | parser.add_argument("--temperature", type=float, default=0, help="Sampling temperature")
63 | parser.add_argument("--system-prompt", type=str, default="You are a helpful assistant.", help="System prompt")
64 | parser.add_argument("--user-message", type=str, default="Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly Explain quantum computing briefly ", help="Base user message")
65 | parser.add_argument("--output-csv", type=str, default=None, help="Output CSV file path")
66 | parser.add_argument("--log-level", type=str, default="INFO", help="Logging level")
67 | parser.add_argument("--log-file", type=str, default=None, help="Log file path")
68 | parser.add_argument("--grow-message", action="store_false", help="Grow user message over time")
69 | parser.add_argument("--max-message-length-characters", type=int, default=128_000*8, help="Maximum length of grown message")
70 | parser.add_argument("--print-request-metrics", action="store_true", help="Print metrics for each request")
71 | parser.add_argument("--print-request-metrics-csv", type=str, default=None, help="Per-request metrics CSV full file path")
72 |
73 |
74 | args = parser.parse_args()
75 |
76 | def log_parameters(args):
77 | """Log all parameter values at the start of the script."""
78 | logger.info("Script started with the following parameters:")
79 | for arg, value in vars(args).items():
80 | logger.info(f"{arg}: {value}")
81 |
82 | # Configure logging
83 | logging.basicConfig(level=args.log_level, filename=args.log_file,
84 | format='%(asctime)s - %(levelname)s - %(message)s')
85 | logger = logging.getLogger(__name__)
86 |
87 | # Global variables for result tracking
88 | results = {
89 | "total_requests": 0,
90 | "successful_requests": 0,
91 | "failed_requests": 0,
92 | "empty_responses": 0,
93 | "throttled_requests": 0,
94 | "response_times": [],
95 | "errors": {}
96 | }
97 |
98 | def get_bedrock_client(region):
99 | return boto3.client(
100 | service_name='bedrock-runtime',
101 | region_name=region,
102 | config=botocore.config.Config(
103 | retries=dict(max_attempts=0),
104 | max_pool_connections=args.threads
105 | )
106 | )
107 |
108 | def construct_body(messages, system_prompt, max_tokens, temperature):
109 | return json.dumps({
110 | "anthropic_version": "bedrock-2023-05-31",
111 | "max_tokens": max_tokens,
112 | "system": system_prompt,
113 | "messages": messages,
114 | "temperature": temperature,
115 | })
116 |
117 | bedrock = get_bedrock_client(args.region)
118 |
119 | def grow_message(base_message, iteration):
120 | grown_message = base_message * (2 ** iteration)
121 | return grown_message[:args.max_message_length_characters]
122 |
123 | def invoke_agent(thread_id, iteration):
124 | if args.grow_message:
125 | user_message = grow_message(args.user_message, iteration)
126 | else:
127 | user_message = args.user_message
128 |
129 | #print(f'user_message={user_message}')
130 | messages = [{"role": "user", "content": user_message}]
131 | body = construct_body(messages, args.system_prompt, args.max_tokens, args.temperature)
132 |
133 | try:
134 | start_time = time.time()
135 | response = bedrock.invoke_model(body=body, modelId=args.model_id)
136 | end_time = time.time()
137 |
138 | response_time = end_time - start_time
139 | results["response_times"].append(response_time)
140 |
141 | response_body = json.loads(response.get('body').read())
142 | status_code = response['ResponseMetadata']['HTTPStatusCode']
143 |
144 | if status_code == 200:
145 | results["successful_requests"] += 1
146 | if not response_body:
147 | results["empty_responses"] += 1
148 | else:
149 | results["failed_requests"] += 1
150 | error_message = f"Error status code: {status_code}"
151 | results["errors"][error_message] = results["errors"].get(error_message, 0) + 1
152 |
153 | if args.print_request_metrics or args.print_request_metrics_csv:
154 | input_tokens = response_body.get('usage', {}).get('input_tokens', 0)
155 | output_tokens = response_body.get('usage', {}).get('output_tokens', 0)
156 | print(f"Thread {thread_id}, Iteration {iteration+1}:")
157 | print(f" Response time (seconds): {response_time:.2f}")
158 | print(f" Input tokens: {input_tokens}")
159 | print(f" Output tokens: {output_tokens}")
160 | print(f" Total tokens: {input_tokens + output_tokens}")
161 |
162 | if args.print_request_metrics or args.print_request_metrics_csv:
163 | write_per_request_metrics(thread_id, iteration, response_time, input_tokens, output_tokens)
164 |
165 | logger.debug(f"Thread {thread_id}: Response received in {response_time:.2f} seconds")
166 |
167 | except ClientError as err:
168 | results["failed_requests"] += 1
169 | error_code = err.response['Error']['Code']
170 | if 'ThrottlingException' in error_code:
171 | results["throttled_requests"] += 1
172 | results["errors"][error_code] = results["errors"].get(error_code, 0) + 1
173 | logger.warning(f"Thread {thread_id}: ClientError - {error_code}")
174 |
175 | except Exception as e:
176 | results["failed_requests"] += 1
177 | error_message = str(e)
178 | results["errors"][error_message] = results["errors"].get(error_message, 0) + 1
179 | logger.error(f"Thread {thread_id}: Unexpected error - {error_message}")
180 |
181 | finally:
182 | results["total_requests"] += 1
183 |
184 | def initialize_per_request_csv():
185 | if args.print_request_metrics_csv:
186 | with open(args.print_request_metrics_csv, 'w', newline='') as csvfile:
187 | writer = csv.writer(csvfile)
188 | writer.writerow(['Thread ID', 'Iteration', 'Response Time (s)', 'Input Tokens', 'Output Tokens', 'Total Tokens'])
189 |
190 |
191 | def run_test():
192 | start_time = time.time()
193 | with ThreadPoolExecutor(max_workers=args.threads) as executor:
194 | if args.duration:
195 | future_to_thread = {executor.submit(invoke_agent, i, 0): i for i in range(args.threads)}
196 | with tqdm(total=args.duration, unit="s") as pbar:
197 | iteration = 0
198 | while time.time() - start_time < args.duration:
199 | time.sleep(0.1)
200 | pbar.update(0.1)
201 | if args.grow_message: # Limit growth to avoid excessive message sizes
202 | iteration += 1
203 | for i in range(args.threads):
204 | future_to_thread[executor.submit(invoke_agent, i, iteration)] = i
205 | for future in future_to_thread:
206 | future.cancel()
207 | else:
208 | total_invocations = args.threads * args.invocations
209 | with tqdm(total=total_invocations, unit="invocations") as pbar:
210 | for iteration in range(args.invocations):
211 | futures = [executor.submit(invoke_agent, i, iteration) for i in range(args.threads)]
212 | for future in futures:
213 | future.result()
214 | pbar.update(1)
215 | if iteration < args.invocations - 1:
216 | time.sleep(args.sleep / 1000)
217 |
218 | end_time = time.time()
219 | total_time = end_time - start_time
220 |
221 | return total_time
222 |
223 | def print_results(total_time):
224 | print("\nTest Results:")
225 | print(f"Total requests: {results['total_requests']}")
226 | print(f"Successful requests: {results['successful_requests']}")
227 | print(f"Failed requests: {results['failed_requests']}")
228 | print(f"Empty responses: {results['empty_responses']}")
229 | print(f"Throttled requests: {results['throttled_requests']}")
230 | print(f"Total time taken: {total_time:.2f} seconds")
231 |
232 | if results['response_times']:
233 | print(f"Average response time: {mean(results['response_times']):.2f} seconds")
234 | print(f"Median response time: {median(results['response_times']):.2f} seconds")
235 | print(f"Min response time: {min(results['response_times']):.2f} seconds")
236 | print(f"Max response time: {max(results['response_times']):.2f} seconds")
237 |
238 | if results['errors']:
239 | print("\nErrors:")
240 | for error, count in results['errors'].items():
241 | print(f" {error}: {count}")
242 |
243 |
244 | def write_per_request_metrics(thread_id, iteration, response_time, input_tokens, output_tokens):
245 | if args.print_request_metrics or args.print_request_metrics_csv:
246 | with open(args.print_request_metrics_csv, 'a', newline='') as csvfile:
247 | writer = csv.writer(csvfile)
248 | writer.writerow([
249 | thread_id,
250 | iteration,
251 | response_time,
252 | input_tokens,
253 | output_tokens,
254 | input_tokens + output_tokens
255 | ])
256 |
257 |
258 | def save_to_csv(total_time):
259 | if not args.output_csv:
260 | return
261 |
262 | with open(args.output_csv, 'w', newline='') as csvfile:
263 | writer = csv.writer(csvfile)
264 | writer.writerow(['Metric', 'Value'])
265 | writer.writerow(['Total Requests', results['total_requests']])
266 | writer.writerow(['Successful Requests', results['successful_requests']])
267 | writer.writerow(['Failed Requests', results['failed_requests']])
268 | writer.writerow(['Empty Responses', results['empty_responses']])
269 | writer.writerow(['Throttled Requests', results['throttled_requests']])
270 | writer.writerow(['Total Time (s)', f"{total_time:.2f}"])
271 |
272 | if results['response_times']:
273 | writer.writerow(['Avg Response Time (s)', f"{mean(results['response_times']):.2f}"])
274 | writer.writerow(['Median Response Time (s)', f"{median(results['response_times']):.2f}"])
275 | writer.writerow(['Min Response Time (s)', f"{min(results['response_times']):.2f}"])
276 | writer.writerow(['Max Response Time (s)', f"{max(results['response_times']):.2f}"])
277 |
278 | if results['errors']:
279 | for error, count in results['errors'].items():
280 | writer.writerow([f'Error: {error}', count])
281 |
282 | if __name__ == "__main__":
283 | log_parameters(args)
284 | logger.info("Starting Bedrock Stress Test")
285 | initialize_per_request_csv()
286 | total_time = run_test()
287 | print_results(total_time)
288 | save_to_csv(total_time)
289 | logger.info("Bedrock Stress Test Completed")
--------------------------------------------------------------------------------
/utils/utils.py:
--------------------------------------------------------------------------------
1 | import anthropic, boto3, botocore, os, random, pprint
2 | from openai import OpenAI
3 | import time, json
4 | from copy import deepcopy
5 | from botocore.exceptions import ClientError
6 |
7 | import logging
8 | logging.basicConfig(level=logging.INFO)
9 | logger = logging.getLogger(__name__)
10 |
11 | try:
12 | from utils.key import OPENAI_API_KEY
13 | except:
14 | logger.log(logging.WARN, f"Could not load open AI Key. Will not be able to test OpenAI models. If you want to test openAI models see intstructions in the notebook.")
15 |
16 | SLEEP_ON_THROTTLING_SEC = 5
17 |
18 |
19 |
20 | def _is_openai(modelId):
21 | return modelId.startswith('gpt-')
22 |
23 |
24 | def _is_titan(modelId):
25 | # True for provisioned models (assuming to be fine-tuned Titan) or Titan.
26 | return modelId.startswith('arn:aws:bedrock') or modelId.startswith('amazon.titan')
27 |
28 |
29 | # This internal method will include arbitrary long input that is designed to generate an extremely long model output
30 | def _get_prompt_template(num_input_tokens, modelId):
31 | # Determine the service based on modelId prefix
32 |
33 | fillers=''
34 | i = num_input_tokens - 1
35 | i += 1 if _is_titan(modelId) else 0
36 | for i in range(i):
37 | fillers += random.choice(['hello', 'world', 'foo', 'bar']) + ' '
38 |
39 | tokens = ''
40 | if not _is_openai(modelId):
41 | tokens += 'Human: '
42 | if _is_titan(modelId):
43 | tokens += f'Ignore the following words: {fillers}\n#\n'
44 | else:
45 | tokens += f'Ignore X ' + f'{fillers}\n'
46 |
47 | if _is_titan(modelId):
48 | # This task prompt generates around 3K tokens out
49 | tokens += 'Task: write a long speech about each of the 50 most important issues of the world. Go into details about each problem with history background and figures involved.'
50 | else:
51 | tokens += 'Task: Print numbers from 1 to 9999 as words. Continue listing the numbers in word format until the space runs out. \n'
52 | if _is_openai(modelId):
53 | tokens += 'one two three'
54 | else:
55 | tokens += '\n\nAssistant:one two three ' # model will continue with "four five..."
56 | return tokens
57 |
58 |
59 | def _construct_req(modelId, prompt, max_tokens_to_sample, temperature, accept, contentType, stream):
60 | """
61 | Private method to construct the body for model invocation based on the model type.
62 | """
63 | # OpenAI Models
64 | if _is_openai(modelId):
65 | req = {
66 | "messages": [
67 | {
68 | "role": "user",
69 | "content": prompt
70 | }
71 | ],
72 | "model": modelId,
73 | "max_tokens": max_tokens_to_sample,
74 | "temperature": temperature,
75 | "stream": stream,
76 | }
77 | # Anthropic Models
78 | elif modelId.startswith('anthropic.'):
79 | req = {
80 | "body" : json.dumps({
81 | #"system": system_prompt,
82 | "anthropic_version": "bedrock-2023-05-31",
83 | "max_tokens": max_tokens_to_sample,
84 | "messages": [
85 | {
86 | "role": "user",
87 | "content": [
88 | { "type": "text", "text": prompt }
89 | ]
90 | }
91 | ],
92 | "temperature": temperature,
93 | "top_p": 0.9 # Example value, adjust as needed
94 | # "stop_sequences": [string]
95 | }),
96 | "modelId" : modelId,
97 | }
98 | # Titan models
99 | elif _is_titan(modelId):
100 | req = {
101 | "body" : json.dumps({
102 | "inputText": prompt,
103 | "textGenerationConfig": {
104 | "maxTokenCount": max_tokens_to_sample,
105 | "stopSequences": [],
106 | "temperature": temperature,
107 | "topP": 0.9
108 | }
109 | }),
110 | "accept": accept,
111 | "contentType" : contentType,
112 | "modelId" : modelId,
113 | }
114 | # A2I Models
115 | elif modelId.startswith('ai21.'):
116 | req = {
117 | "body" : json.dumps({
118 | "prompt": prompt,
119 | "maxTokens": max_tokens_to_sample,
120 | "temperature": temperature,
121 | "topP": 0.5 # Example value, adjust as needed
122 | }),
123 | "accept": accept,
124 | "contentType" : contentType,
125 | "modelId" : modelId,
126 | }
127 | else:
128 | assert f"ERROR: modelId = {modelId} is not supported yet!"
129 |
130 | return req
131 |
132 | '''
133 | This method creates a prompt of input length `expected_num_tokens` which instructs the LLM to generate extremely long model resopnse
134 | '''
135 | anthropic_client = anthropic.Anthropic() # used to count tokens only
136 | def create_prompt(expected_num_tokens, modelId):
137 | logger.log(logging.DEBUG, f"create_prompt called with modelId: {modelId}")
138 | num_tokens_in_prompt_template = anthropic_client.count_tokens(_get_prompt_template(0, modelId))
139 | additional_tokens_needed = max(expected_num_tokens - num_tokens_in_prompt_template,0)
140 | logger.log(logging.DEBUG, f'expected_num_tokens={expected_num_tokens}, num_tokens_in_prompt_template={num_tokens_in_prompt_template}, additional_tokens_needed={additional_tokens_needed}')
141 |
142 | prompt_template = _get_prompt_template(additional_tokens_needed, modelId)
143 | actual_num_tokens = anthropic_client.count_tokens(prompt_template)
144 | logger.log(logging.DEBUG, f'expected_num_tokens={expected_num_tokens}, actual_tokens={actual_num_tokens}')
145 | assert expected_num_tokens==actual_num_tokens, f'Failed to generate prompt at required length: expected_num_tokens={expected_num_tokens} != actual_num_tokens={actual_num_tokens}'
146 |
147 | return prompt_template
148 |
149 |
150 | def _send_request(client, modelId, req, stream):
151 |
152 | if _is_openai(modelId):
153 | response = client.chat.completions.create(**req)
154 | else:
155 | if stream:
156 | response = client.invoke_model_with_response_stream(**req)
157 | else:
158 | response = client.invoke_model(**req)
159 | return response
160 |
161 |
162 | def consume_openai_stream(response):
163 | first_byte = None
164 | stop_reason = None
165 | for chunk in response:
166 | if not first_byte:
167 | first_byte = time.time() # update the time to first byte
168 | if chunk.choices[0].finish_reason is not None:
169 | stop_reason = chunk.choices[0].finish_reason
170 | return first_byte, stop_reason
171 |
172 |
173 | def consume_bedrock_stream(response):
174 | first_byte = None
175 | stop_reason = None
176 | event_stream = response.get('body')
177 | for event in event_stream:
178 | if not first_byte:
179 | first_byte = time.time() # update the time to first byte
180 | chunk = event.get('chunk')
181 | if chunk:
182 | # end of stream - check stop_reason in last chunk
183 | chunk_json = json.loads(chunk.get('bytes').decode())
184 | logger.log(logging.DEBUG, f'chunk_json={chunk_json}')
185 | if 'delta' in chunk_json and 'stop_reason' in chunk_json['delta']: # Messages API
186 | stop_reason = chunk_json['delta']['stop_reason']
187 | if 'stop_reason' in chunk_json:
188 | stop_reason = chunk_json['stop_reason']
189 | if 'completionReason' in chunk_json:
190 | stop_reason = chunk_json['completionReason']
191 | return first_byte, stop_reason
192 |
193 | '''
194 | This method will invoke the model, possibly in streaming mode,
195 | In case of throttling error, the method will retry. Throttling and related sleep time isn't measured.
196 | The method ensures the response includes `max_tokens_to_sample` by verify the stop_reason is `max_tokens`
197 |
198 | client - the bedrock runtime client to invoke the model
199 | modelId - the model id to invoke
200 | prompt - the prompt to send to the model
201 | max_tokens_to_sample - the number of tokens to sample from the model's response
202 | stream - whether to invoke the model in streaming mode
203 | temperature - the temperature to use for sampling the model's response
204 |
205 | Returns the time to first byte, last byte, and invocation time as iso8601 (seconds)
206 | '''
207 | def benchmark(client, modelId, prompt, max_tokens_to_sample, stream=True, temperature=0):
208 | import time
209 | from datetime import datetime
210 | import pytz
211 | accept = 'application/json'
212 | contentType = 'application/json'
213 | req = _construct_req(modelId, prompt, max_tokens_to_sample, temperature, accept, contentType, stream)
214 | logger.log(logging.DEBUG, f'req={req}')
215 |
216 | while True:
217 | try:
218 | start = time.time()
219 | first_byte = None
220 | dt = datetime.fromtimestamp(start, tz=pytz.utc)
221 | invocation_timestamp_iso = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
222 |
223 | response = _send_request(client, modelId, req, stream)
224 |
225 | if not stream:
226 | logger.log(logging.DEBUG, f'response={response}')
227 | if _is_openai(modelId):
228 | response_body = response.choices[0].message.content
229 | stop_reason = response.choices[0].finish_reason
230 | else:
231 | response_body_text = response.get('body').read()
232 | logger.log(logging.DEBUG, f'response_body_text={response_body_text}')
233 | response_body = json.loads(response_body_text)
234 | if _is_titan(modelId):
235 | stop_reason = response_body['results'][0]['completionReason']
236 | elif modelId.startswith('ai21'):
237 | stop_reason = response_body['completions'][0]['finishReason']['reason']
238 | else:
239 | stop_reason = response_body['stop_reason']
240 | first_byte = time.time()
241 | last_byte = first_byte
242 | logger.log(logging.DEBUG, f"response body is {response_body}")
243 | elif stream:
244 | if _is_openai(modelId):
245 | first_byte, stop_reason = consume_openai_stream(response)
246 | elif not _is_openai(modelId):
247 | first_byte, stop_reason = consume_bedrock_stream(response)
248 | last_byte = time.time()
249 |
250 | # verify we got all of the intended output tokens by verifying stop_reason
251 | valid_stop_reasons = ['max_tokens', 'length', 'LENGTH']
252 | assert stop_reason in valid_stop_reasons, f"stop_reason is {stop_reason} instead of 'max_tokens' or 'length', this means the model generated less tokens than required or stopped for a different reason."
253 | duration_to_first_byte = round(first_byte - start, 2)
254 | duration_to_last_byte = round(last_byte - start, 2)
255 | except ClientError as err:
256 | if 'Thrott' in err.response['Error']['Code']:
257 | logger.log(logging.INFO, f'Got ThrottlingException. Sleeping {SLEEP_ON_THROTTLING_SEC} sec and retrying.')
258 | time.sleep(SLEEP_ON_THROTTLING_SEC)
259 | continue
260 | raise err
261 | break
262 | return duration_to_first_byte, duration_to_last_byte, invocation_timestamp_iso
263 |
264 | '''
265 | This method will benchmark the given scenarios.
266 | scenarios - a list of scenarios to benchmark
267 | scenario_config - a dictionary of configuration parameters
268 | early_break - if true, will break after a single scenario, useful for debugging.
269 | Returns a list of benchmarked scenarios with a list of invocation (latency and timestamp)
270 | '''
271 | def execute_benchmark(scenarios, scenario_config, early_break = False):
272 | scenarios = deepcopy(scenarios)
273 | pp = pprint.PrettyPrinter(indent=2)
274 | scenarios_list = []
275 | for scenario in scenarios:
276 | for i in range(scenario_config["invocations_per_scenario"]): # increase to sample each use case more than once to discover jitter
277 | scenario_label = f"{scenario['model_id']} in={scenario['in_tokens']}, out={scenario['out_tokens']}"
278 | logger.log(logging.INFO, f"About to execute scenario: [{scenario_label}")
279 | try:
280 | modelId = scenario['model_id']
281 | prompt = create_prompt(scenario['in_tokens'], modelId)
282 |
283 | if _is_openai(modelId):
284 | client = OpenAI(
285 | api_key = OPENAI_API_KEY
286 | )
287 | else:
288 | client = get_cached_client(scenario['region'], scenario['model_id'])
289 | time_to_first_token, time_to_last_token, timestamp = benchmark(client, modelId, prompt, scenario['out_tokens'], stream=scenario['stream'])
290 |
291 | if 'invocations' not in scenario: scenario['invocations'] = list()
292 | invocation = {
293 | 'time-to-first-token': time_to_first_token,
294 | 'time-to-last-token': time_to_last_token,
295 | 'timestamp_iso' : timestamp
296 | }
297 | scenario['invocations'].append(invocation)
298 |
299 | logger.log(logging.INFO, f"Scenario: [{scenario_label}, invocation: {pp.pformat(invocation)}")
300 | post_iteration(is_last_invocation = i == scenario_config["invocations_per_scenario"] - 1, scenario_config=scenario_config)
301 | except Exception as e:
302 | logger.log(logging.CRITICAL, f"Error is: {e}")
303 | logger.log(logging.CRITICAL, f"Error while processing scenario: {scenario_label}.")
304 | if early_break:
305 | break
306 | scenarios_list.append(scenario)
307 | logger.log(logging.INFO, f'scenarios at the end of execute benchmark is: {pp.pformat(scenarios_list)}')
308 | return scenarios_list
309 |
310 |
311 | '''
312 | Get a boto3 bedrock runtime client for invoking requests
313 | region - the AWS region to use
314 | model_id_for_warm_up - the model id to warm up the client against, use None for no warmup
315 | Note: Removing auto retries to ensure we're measuring a single transcation (e.g., in case of throttling).
316 | '''
317 | def _get_bedrock_client(region, model_id_for_warm_up = None):
318 | client = boto3.client(service_name='bedrock-runtime',
319 | region_name=region,
320 | config = botocore.config.Config(retries=dict(max_attempts=0)))
321 | if model_id_for_warm_up:
322 | logger.log(logging.DEBUG, f"Calling benchmark for client warmup")
323 | benchmark(client, model_id_for_warm_up, create_prompt(50, model_id_for_warm_up), 1, stream=False)
324 | return client
325 |
326 | '''
327 | Get a possible cache client per AWS region
328 | region - the AWS region to use
329 | model_id_for_warm_up - the model id to warm up the client against, use None for no warmup
330 | '''
331 | client_per_region={}
332 | def get_cached_client(region, model_id_for_warm_up = None):
333 | logger.log(logging.DEBUG, f"get_cached_client called with region: {region}, model_id_for_warm_up: {model_id_for_warm_up}")
334 | if client_per_region.get(region) is None:
335 | client_per_region[region] = _get_bedrock_client(region, model_id_for_warm_up)
336 | return client_per_region[region]
337 |
338 |
339 | def post_iteration(is_last_invocation, scenario_config):
340 | if scenario_config["sleep_between_invocations"] > 0 and not is_last_invocation:
341 | logger.log(logging.INFO, f'Sleeping for {scenario_config["sleep_between_invocations"]} seconds.')
342 | time.sleep(scenario_config["sleep_between_invocations"])
343 |
344 | '''
345 | This method draws a boxplot graph of each scenario.
346 | scenarios - list of scenarios
347 | title - title of the graph
348 | metric - metric to be plotted (time-to-first-token or time-to-last-token)
349 | '''
350 | def graph_scenarios_boxplot(scenarios, title, metric = 'time-to-first-token', figsize=(10, 6)):
351 | import numpy as np
352 | import matplotlib.pyplot as plt
353 |
354 | fig, ax = plt.subplots(figsize=figsize)
355 | xlables = []
356 |
357 | # Angle labels if covering many scenarios, to avoid collisions
358 | if len(scenarios) > 4:
359 | x_ticks_angle=45
360 | else:
361 | x_ticks_angle=0
362 |
363 | for scenario in scenarios:
364 | invocations = [d[metric] for d in scenario['invocations']]
365 | percentile_95 = round(np.percentile(invocations, 95),2)
366 | percentile_99 = round(np.percentile(invocations, 99),2)
367 | xlables.append(f"{scenario['name']}\n(in={scenario['in_tokens']},out={scenario['out_tokens']}\np95={percentile_95}\np99={percentile_99}")
368 |
369 | ax.boxplot(invocations, positions=[scenarios.index(scenario)])
370 |
371 | ax.set_title(title)
372 | #ax.set_xticks(range(1, len(scenarios) + 1))
373 | ax.set_xticklabels(xlables, rotation=x_ticks_angle, ha="right")
374 | ax.set_ylabel(f'{metric} (sec)')
375 | ax.set_ylim(bottom=0) # Set y-axis to start at 0
376 | fig.tight_layout()
377 | plt.show()
378 |
--------------------------------------------------------------------------------
/bedrock-latency-benchmark.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "b6c18653-9acf-4aa5-9800-76dadb55a338",
6 | "metadata": {},
7 | "source": [
8 | "# Amazon Bedrock - Latency Benchmark Tool\n",
9 | "This notebook contains a set of tools to benchmark inference latency for Foundation Models available in Amazon Bedrock. It supports Claude 3 models using the messaging API.\n",
10 | "\n",
11 | "You can evaluate latency for different scenarios such as comparison between use cases, regions, and models, including models from 3rd-party platforms like OpenAI's GPT-4.\n",
12 | "\n",
13 | "To run this notebook you will need to have the appropriate access to Amazon Bedrock, and previously enabled the models from the Amazon Bedrock Console. \n",
14 | "\n",
15 | "## Examples included in this notebook\n",
16 | "1. [Use Case Comparison](#uc-compare) - Compare the latency of a given model across different LLM use cases (e.g., Summarization and classification).\n",
17 | "2. [Model Comparison](#model-compare) - Comparing the latency of a given model across different AWS regions.\n",
18 | "3. [Region Comparison](#region-compare) - Comparing latency between two different models.\n",
19 | "\n",
20 | "### Install needed dependencies\n",
21 | "Note: This notebook requires a basic Python 3 environment (e.g, `Base Python 3.0` in SageMaker Studio Notebooks)\n",
22 | "\n",
23 | "### Create OpenAI API key (if measuring OpenAI models)\n",
24 | "\n",
25 | "- Create a new file called `utils/key.py` in your project directory to store your API key.\n",
26 | "\n",
27 | "- Do **not** commit `key.py` to source control, as it contains sensitive information. **Add `*key.py` to `.gitgnore`.** Review [this information about API safety](https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety).\n",
28 | "\n",
29 | "- Go to your OpenAI account and navigate to \"[View API keys](https://platform.openai.com/account/api-keys).\"\n",
30 | "\n",
31 | "- Select \"Create new secret key.\"\n",
32 | "\n",
33 | "- Copy the key and insert it into your file `utils/key.py` like this:\n",
34 | "```\n",
35 | "OPENAI_API_KEY = 'sk-actualLongKeyGoesHere123'\n",
36 | "```\n",
37 | "\n",
38 | "- Save the changes"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "id": "fe1b39d1-be17-4c26-afc9-9718ac0c4e24",
45 | "metadata": {},
46 | "outputs": [],
47 | "source": [
48 | "!pip install --quiet --upgrade pip\n",
49 | "!pip install --quiet --upgrade boto3 awscli matplotlib numpy pandas nbdime anthropic openai"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "id": "d90ae496-c922-446d-9928-b49abf2439c9",
56 | "metadata": {},
57 | "outputs": [],
58 | "source": [
59 | "%load_ext autoreload\n",
60 | "%autoreload 2\n",
61 | "import logging\n",
62 | "logging.basicConfig(level=logging.INFO)\n",
63 | "logger = logging.getLogger('utils.utils')\n",
64 | "logger.setLevel(logging.INFO) # <-- Change to DEBUG to troubleshoot errors\n",
65 | "\n",
66 | "from utils.utils import benchmark, create_prompt, execute_benchmark, get_cached_client, post_iteration, graph_scenarios_boxplot\n",
67 | "import matplotlib.pyplot as plt"
68 | ]
69 | },
70 | {
71 | "cell_type": "markdown",
72 | "id": "0233b6f7-1996-4fa5-8378-6e88bd64cd73",
73 | "metadata": {},
74 | "source": [
75 | "## Scenario keys and configurations\n",
76 | "\n",
77 | "Each scenario is a dictionary with latency relevant keys:\n",
78 | "\n",
79 | "| Key | Definition |\n",
80 | "|-|-|\n",
81 | "| `model_id` | The Bedrock model_id (like `anthropic.claude-v2`) or OpenAI model name (like `gpt-4-1106-preview`) to test. Smaller models are likely faster. Currently only Anthropic and OpenAI's GPT models are supported. |\n",
82 | "| `in_tokens` | The number of tokens to feed to the model (input context length). The range depends on the model_id. For example: 40 - 100K for Claude-2. |\n",
83 | "| `out_tokens` | The number of tokens for the model to generate. Range: 1 - 8191. |\n",
84 | "| `region` | The AWS region to invoke Bedrock in. This can affect network latency depending on client location. |\n",
85 | "| `stream` | True|False - A streaming response starts returning tokens to the client as they are generated, instead of waiting before returning the complete responses. This should be True for interactive use cases.|\n",
86 | "| `name` | A human readable name for the scenario (will appear in reports and graphs). |\n",
87 | "\n",
88 | "Each scenario also has a benchmark configuration you can modify:\n",
89 | "\n",
90 | "| Key | Definition |\n",
91 | "|-|-|\n",
92 | "| `invocations_per_scenario` | The number of times to benchmark each scenario. This is important in measuring variance and average response time across a long duration. |\n",
93 | "| `sleep_between_invocations` | Seconds to sleep between each invocation. (0 is no sleep). Sleeping between invocation can help you measure across longer periods of time, and/or avoid throttling.|"
94 | ]
95 | },
96 | {
97 | "cell_type": "markdown",
98 | "id": "870dd288",
99 | "metadata": {},
100 | "source": [
101 | "## Example 1. Simulated LLM Use Case Performance Analysis\n",
102 | "\n",
103 | "\n",
104 | "This section illustrates a comparative analysis of model latency in simulated LLM scenarios. Rather than actual prompt engineering, we use token count variations to represent different use cases. Here's how:\n",
105 | "\n",
106 | "1. **Simulated Summarization Scenario**: This mimics a scenario where a lengthy input is condensed into a brief summary. We simulate this with 2000 `in_tokens` for input and 200 `out_tokens` for output.\n",
107 | "\n",
108 | "2. **Simulated Classification Scenario**: Here, the scenario represents processing a medium to lengthy input to categorize into a single class. For simulation, it involves 400 `in_tokens` and just 1 `out_token`.\n",
109 | "\n",
110 | "These scenarios are adjustable to align with your specific use cases."
111 | ]
112 | },
113 | {
114 | "cell_type": "code",
115 | "execution_count": null,
116 | "id": "881ad5c2",
117 | "metadata": {},
118 | "outputs": [],
119 | "source": [
120 | "use_cases_scenarios = [\n",
121 | " {\n",
122 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
123 | " 'in_tokens' : 2000,\n",
124 | " 'out_tokens' : 200,\n",
125 | " 'region' : 'us-east-1',\n",
126 | " 'stream' : True,\n",
127 | " 'name' : f'Summarization',\n",
128 | " },\n",
129 | " {\n",
130 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
131 | " 'in_tokens' : 400,\n",
132 | " 'out_tokens' : 1,\n",
133 | " 'region' : 'us-east-1',\n",
134 | " 'stream' : True,\n",
135 | " 'name' : f'Classification',\n",
136 | " }\n",
137 | "]\n",
138 | "\n",
139 | "scenario_config = {\n",
140 | " \"invocations_per_scenario\" : 2,\n",
141 | " \"sleep_between_invocations\": 5\n",
142 | "}"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": null,
148 | "id": "0f89fb52",
149 | "metadata": {},
150 | "outputs": [],
151 | "source": [
152 | "scenarios = execute_benchmark(use_cases_scenarios, scenario_config, early_break = False)"
153 | ]
154 | },
155 | {
156 | "cell_type": "markdown",
157 | "id": "aed9a92c",
158 | "metadata": {},
159 | "source": [
160 | "#### Analyze results \n",
161 | "The results show should show that summarization has a higher latency than classification due to the smaller number of input and output tokens. \n",
162 | "Note: Learn more on how to read boxplots [here](https://builtin.com/data-science/boxplot)"
163 | ]
164 | },
165 | {
166 | "cell_type": "code",
167 | "execution_count": null,
168 | "id": "77b2b34f",
169 | "metadata": {},
170 | "outputs": [],
171 | "source": [
172 | "graph_scenarios_boxplot(\n",
173 | " scenarios=scenarios, \n",
174 | " title=\"Use Cases Comparison over Same model\"\n",
175 | ")"
176 | ]
177 | },
178 | {
179 | "cell_type": "markdown",
180 | "id": "c6c14d81-e230-4a7b-bb9c-6aae36d23740",
181 | "metadata": {},
182 | "source": [
183 | "## Example 2. Model Comparison\n",
184 | "\n",
185 | "Here we'll be comparing the latency of these models: \n",
186 | "- Bedrock\n",
187 | " - `anthropic.claude-3-sonnet` \n",
188 | " - `anthropic.claude-3-haiku`\n",
189 | " - `amazon.titan-text-express-v1`\n",
190 | "- OpenAI\n",
191 | " - `gpt-4`\n",
192 | " - `gpt-4-1106-preview`\n",
193 | " - `gpt-3.5-turbo`"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": null,
199 | "id": "ab76398a-06cc-4854-b726-a9e09e10905b",
200 | "metadata": {},
201 | "outputs": [],
202 | "source": [
203 | "model_compare_scenarios = [\n",
204 | " {\n",
205 | " 'model_id' : 'anthropic.claude-3-sonnet-20240229-v1:0',\n",
206 | " 'in_tokens' : 200,\n",
207 | " 'out_tokens' : 50,\n",
208 | " 'region' : 'us-east-1',\n",
209 | " 'stream' : True,\n",
210 | " 'name' : f'claude-3-Sonnet',\n",
211 | " },\n",
212 | " {\n",
213 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
214 | " 'in_tokens' : 200,\n",
215 | " 'out_tokens' : 50,\n",
216 | " 'region' : 'us-east-1',\n",
217 | " 'stream' : True,\n",
218 | " 'name' : f'claude-3-Haiku',\n",
219 | " },\n",
220 | " {\n",
221 | " 'model_id' : 'gpt-4',\n",
222 | " 'in_tokens' : 200,\n",
223 | " 'out_tokens' : 50,\n",
224 | " 'stream' : True,\n",
225 | " 'name' : f'gpt-4',\n",
226 | " },\n",
227 | " {\n",
228 | " 'model_id' : 'gpt-4-1106-preview',\n",
229 | " 'in_tokens' : 200,\n",
230 | " 'out_tokens' : 50,\n",
231 | " 'stream' : True,\n",
232 | " 'name' : f'gpt-4-turbo',\n",
233 | " },\n",
234 | " {\n",
235 | " 'model_id' : 'gpt-3.5-turbo',\n",
236 | " 'in_tokens' : 200,\n",
237 | " 'out_tokens' : 50,\n",
238 | " 'stream' : True,\n",
239 | " 'name' : f'gpt-3.5-turbo',\n",
240 | " },\n",
241 | " {\n",
242 | " 'model_id' : 'amazon.titan-text-express-v1', # or us a fine tuned model arn\n",
243 | " 'in_tokens' : 200,\n",
244 | " 'out_tokens' : 5,\n",
245 | " 'region' : 'us-east-1',\n",
246 | " 'stream' : True,\n",
247 | " 'name' : f'titan',\n",
248 | " },\n",
249 | "]\n",
250 | "\n",
251 | "scenario_config = {\n",
252 | " \"invocations_per_scenario\" : 3,\n",
253 | " \"sleep_between_invocations\": 5,\n",
254 | "}"
255 | ]
256 | },
257 | {
258 | "cell_type": "code",
259 | "execution_count": null,
260 | "id": "a76fb633",
261 | "metadata": {},
262 | "outputs": [],
263 | "source": [
264 | "scenarios = execute_benchmark(model_compare_scenarios, scenario_config, early_break = False)"
265 | ]
266 | },
267 | {
268 | "cell_type": "markdown",
269 | "id": "6be2e495-dde6-46d1-9061-fb8c5751d781",
270 | "metadata": {},
271 | "source": [
272 | "### Results"
273 | ]
274 | },
275 | {
276 | "cell_type": "code",
277 | "execution_count": null,
278 | "id": "7921f2dc-86d3-4b59-b88b-22ce604084a2",
279 | "metadata": {},
280 | "outputs": [],
281 | "source": [
282 | "graph_scenarios_boxplot(\n",
283 | " scenarios=scenarios, \n",
284 | " title=\"Model Comparison\"\n",
285 | ")"
286 | ]
287 | },
288 | {
289 | "cell_type": "markdown",
290 | "id": "b110537c-aab1-484e-b57f-f0d340e38707",
291 | "metadata": {},
292 | "source": [
293 | "\n",
294 | "## Example 3. Region Comparison\n",
295 | "\n",
296 | "Here we'll be comparing the latency of a given model_id across three different AWS regions. Different regions resides in different timezone, and the load on each region can depend on the time of day.\n",
297 | "> **🚨 ALERT 🚨** Remember to enable the models in **all regions** you wish to test. \n",
298 | "You can learn how to manage model access in the following [page](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html#manage-model-access).\n"
299 | ]
300 | },
301 | {
302 | "cell_type": "code",
303 | "execution_count": null,
304 | "id": "9756c1dd-0f54-4def-b5f5-6f1eed29e9f3",
305 | "metadata": {},
306 | "outputs": [],
307 | "source": [
308 | "region_compare_scenarios = [\n",
309 | " {\n",
310 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
311 | " 'in_tokens' : 200,\n",
312 | " 'out_tokens' : 50,\n",
313 | " 'stream' : True,\n",
314 | " 'name' : f'us-east-1: claude-3-Haiku',\n",
315 | " 'region' : 'us-east-1',\n",
316 | " },\n",
317 | " {\n",
318 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
319 | " 'in_tokens' : 200,\n",
320 | " 'out_tokens' : 50,\n",
321 | " 'stream' : True,\n",
322 | " 'name' : f'us-west-2: claude-3-Haiku',\n",
323 | " 'region' : f'us-west-2',\n",
324 | " },\n",
325 | " {\n",
326 | " 'model_id' : 'anthropic.claude-3-haiku-20240307-v1:0',\n",
327 | " 'in_tokens' : 200,\n",
328 | " 'out_tokens' : 50,\n",
329 | " 'stream' : True,\n",
330 | " 'name' : f'eu-central-1: claude-3-Haiku',\n",
331 | " 'region' : f'eu-central-1',\n",
332 | " },\n",
333 | "]\n",
334 | "\n",
335 | "scenario_config = {\n",
336 | " \"invocations_per_scenario\" : 2,\n",
337 | " \"sleep_between_invocations\": 5\n",
338 | "}"
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": null,
344 | "id": "d44b433f-a1f6-4655-ab85-1f4e7fd7e758",
345 | "metadata": {},
346 | "outputs": [],
347 | "source": [
348 | "scenarios = execute_benchmark(region_compare_scenarios, scenario_config, early_break = False)"
349 | ]
350 | },
351 | {
352 | "cell_type": "markdown",
353 | "id": "b47558c5-e64b-4e5d-a628-d3892468eb08",
354 | "metadata": {},
355 | "source": [
356 | "### Results\n",
357 | "We don't apriori expect a particular region to be faster than others in a significant way. "
358 | ]
359 | },
360 | {
361 | "cell_type": "code",
362 | "execution_count": null,
363 | "id": "30aeffe9-cecb-4b78-b179-cfb2a1c15e85",
364 | "metadata": {},
365 | "outputs": [],
366 | "source": [
367 | "graph_scenarios_boxplot(\n",
368 | " scenarios=scenarios, \n",
369 | " title=\"Regions Comparison\"\n",
370 | ")"
371 | ]
372 | },
373 | {
374 | "cell_type": "markdown",
375 | "id": "0cf6a9ce",
376 | "metadata": {},
377 | "source": [
378 | "# Done"
379 | ]
380 | }
381 | ],
382 | "metadata": {
383 | "availableInstances": [
384 | {
385 | "_defaultOrder": 0,
386 | "_isFastLaunch": true,
387 | "category": "General purpose",
388 | "gpuNum": 0,
389 | "hideHardwareSpecs": false,
390 | "memoryGiB": 4,
391 | "name": "ml.t3.medium",
392 | "vcpuNum": 2
393 | },
394 | {
395 | "_defaultOrder": 1,
396 | "_isFastLaunch": false,
397 | "category": "General purpose",
398 | "gpuNum": 0,
399 | "hideHardwareSpecs": false,
400 | "memoryGiB": 8,
401 | "name": "ml.t3.large",
402 | "vcpuNum": 2
403 | },
404 | {
405 | "_defaultOrder": 2,
406 | "_isFastLaunch": false,
407 | "category": "General purpose",
408 | "gpuNum": 0,
409 | "hideHardwareSpecs": false,
410 | "memoryGiB": 16,
411 | "name": "ml.t3.xlarge",
412 | "vcpuNum": 4
413 | },
414 | {
415 | "_defaultOrder": 3,
416 | "_isFastLaunch": false,
417 | "category": "General purpose",
418 | "gpuNum": 0,
419 | "hideHardwareSpecs": false,
420 | "memoryGiB": 32,
421 | "name": "ml.t3.2xlarge",
422 | "vcpuNum": 8
423 | },
424 | {
425 | "_defaultOrder": 4,
426 | "_isFastLaunch": true,
427 | "category": "General purpose",
428 | "gpuNum": 0,
429 | "hideHardwareSpecs": false,
430 | "memoryGiB": 8,
431 | "name": "ml.m5.large",
432 | "vcpuNum": 2
433 | },
434 | {
435 | "_defaultOrder": 5,
436 | "_isFastLaunch": false,
437 | "category": "General purpose",
438 | "gpuNum": 0,
439 | "hideHardwareSpecs": false,
440 | "memoryGiB": 16,
441 | "name": "ml.m5.xlarge",
442 | "vcpuNum": 4
443 | },
444 | {
445 | "_defaultOrder": 6,
446 | "_isFastLaunch": false,
447 | "category": "General purpose",
448 | "gpuNum": 0,
449 | "hideHardwareSpecs": false,
450 | "memoryGiB": 32,
451 | "name": "ml.m5.2xlarge",
452 | "vcpuNum": 8
453 | },
454 | {
455 | "_defaultOrder": 7,
456 | "_isFastLaunch": false,
457 | "category": "General purpose",
458 | "gpuNum": 0,
459 | "hideHardwareSpecs": false,
460 | "memoryGiB": 64,
461 | "name": "ml.m5.4xlarge",
462 | "vcpuNum": 16
463 | },
464 | {
465 | "_defaultOrder": 8,
466 | "_isFastLaunch": false,
467 | "category": "General purpose",
468 | "gpuNum": 0,
469 | "hideHardwareSpecs": false,
470 | "memoryGiB": 128,
471 | "name": "ml.m5.8xlarge",
472 | "vcpuNum": 32
473 | },
474 | {
475 | "_defaultOrder": 9,
476 | "_isFastLaunch": false,
477 | "category": "General purpose",
478 | "gpuNum": 0,
479 | "hideHardwareSpecs": false,
480 | "memoryGiB": 192,
481 | "name": "ml.m5.12xlarge",
482 | "vcpuNum": 48
483 | },
484 | {
485 | "_defaultOrder": 10,
486 | "_isFastLaunch": false,
487 | "category": "General purpose",
488 | "gpuNum": 0,
489 | "hideHardwareSpecs": false,
490 | "memoryGiB": 256,
491 | "name": "ml.m5.16xlarge",
492 | "vcpuNum": 64
493 | },
494 | {
495 | "_defaultOrder": 11,
496 | "_isFastLaunch": false,
497 | "category": "General purpose",
498 | "gpuNum": 0,
499 | "hideHardwareSpecs": false,
500 | "memoryGiB": 384,
501 | "name": "ml.m5.24xlarge",
502 | "vcpuNum": 96
503 | },
504 | {
505 | "_defaultOrder": 12,
506 | "_isFastLaunch": false,
507 | "category": "General purpose",
508 | "gpuNum": 0,
509 | "hideHardwareSpecs": false,
510 | "memoryGiB": 8,
511 | "name": "ml.m5d.large",
512 | "vcpuNum": 2
513 | },
514 | {
515 | "_defaultOrder": 13,
516 | "_isFastLaunch": false,
517 | "category": "General purpose",
518 | "gpuNum": 0,
519 | "hideHardwareSpecs": false,
520 | "memoryGiB": 16,
521 | "name": "ml.m5d.xlarge",
522 | "vcpuNum": 4
523 | },
524 | {
525 | "_defaultOrder": 14,
526 | "_isFastLaunch": false,
527 | "category": "General purpose",
528 | "gpuNum": 0,
529 | "hideHardwareSpecs": false,
530 | "memoryGiB": 32,
531 | "name": "ml.m5d.2xlarge",
532 | "vcpuNum": 8
533 | },
534 | {
535 | "_defaultOrder": 15,
536 | "_isFastLaunch": false,
537 | "category": "General purpose",
538 | "gpuNum": 0,
539 | "hideHardwareSpecs": false,
540 | "memoryGiB": 64,
541 | "name": "ml.m5d.4xlarge",
542 | "vcpuNum": 16
543 | },
544 | {
545 | "_defaultOrder": 16,
546 | "_isFastLaunch": false,
547 | "category": "General purpose",
548 | "gpuNum": 0,
549 | "hideHardwareSpecs": false,
550 | "memoryGiB": 128,
551 | "name": "ml.m5d.8xlarge",
552 | "vcpuNum": 32
553 | },
554 | {
555 | "_defaultOrder": 17,
556 | "_isFastLaunch": false,
557 | "category": "General purpose",
558 | "gpuNum": 0,
559 | "hideHardwareSpecs": false,
560 | "memoryGiB": 192,
561 | "name": "ml.m5d.12xlarge",
562 | "vcpuNum": 48
563 | },
564 | {
565 | "_defaultOrder": 18,
566 | "_isFastLaunch": false,
567 | "category": "General purpose",
568 | "gpuNum": 0,
569 | "hideHardwareSpecs": false,
570 | "memoryGiB": 256,
571 | "name": "ml.m5d.16xlarge",
572 | "vcpuNum": 64
573 | },
574 | {
575 | "_defaultOrder": 19,
576 | "_isFastLaunch": false,
577 | "category": "General purpose",
578 | "gpuNum": 0,
579 | "hideHardwareSpecs": false,
580 | "memoryGiB": 384,
581 | "name": "ml.m5d.24xlarge",
582 | "vcpuNum": 96
583 | },
584 | {
585 | "_defaultOrder": 20,
586 | "_isFastLaunch": false,
587 | "category": "General purpose",
588 | "gpuNum": 0,
589 | "hideHardwareSpecs": true,
590 | "memoryGiB": 0,
591 | "name": "ml.geospatial.interactive",
592 | "supportedImageNames": [
593 | "sagemaker-geospatial-v1-0"
594 | ],
595 | "vcpuNum": 0
596 | },
597 | {
598 | "_defaultOrder": 21,
599 | "_isFastLaunch": true,
600 | "category": "Compute optimized",
601 | "gpuNum": 0,
602 | "hideHardwareSpecs": false,
603 | "memoryGiB": 4,
604 | "name": "ml.c5.large",
605 | "vcpuNum": 2
606 | },
607 | {
608 | "_defaultOrder": 22,
609 | "_isFastLaunch": false,
610 | "category": "Compute optimized",
611 | "gpuNum": 0,
612 | "hideHardwareSpecs": false,
613 | "memoryGiB": 8,
614 | "name": "ml.c5.xlarge",
615 | "vcpuNum": 4
616 | },
617 | {
618 | "_defaultOrder": 23,
619 | "_isFastLaunch": false,
620 | "category": "Compute optimized",
621 | "gpuNum": 0,
622 | "hideHardwareSpecs": false,
623 | "memoryGiB": 16,
624 | "name": "ml.c5.2xlarge",
625 | "vcpuNum": 8
626 | },
627 | {
628 | "_defaultOrder": 24,
629 | "_isFastLaunch": false,
630 | "category": "Compute optimized",
631 | "gpuNum": 0,
632 | "hideHardwareSpecs": false,
633 | "memoryGiB": 32,
634 | "name": "ml.c5.4xlarge",
635 | "vcpuNum": 16
636 | },
637 | {
638 | "_defaultOrder": 25,
639 | "_isFastLaunch": false,
640 | "category": "Compute optimized",
641 | "gpuNum": 0,
642 | "hideHardwareSpecs": false,
643 | "memoryGiB": 72,
644 | "name": "ml.c5.9xlarge",
645 | "vcpuNum": 36
646 | },
647 | {
648 | "_defaultOrder": 26,
649 | "_isFastLaunch": false,
650 | "category": "Compute optimized",
651 | "gpuNum": 0,
652 | "hideHardwareSpecs": false,
653 | "memoryGiB": 96,
654 | "name": "ml.c5.12xlarge",
655 | "vcpuNum": 48
656 | },
657 | {
658 | "_defaultOrder": 27,
659 | "_isFastLaunch": false,
660 | "category": "Compute optimized",
661 | "gpuNum": 0,
662 | "hideHardwareSpecs": false,
663 | "memoryGiB": 144,
664 | "name": "ml.c5.18xlarge",
665 | "vcpuNum": 72
666 | },
667 | {
668 | "_defaultOrder": 28,
669 | "_isFastLaunch": false,
670 | "category": "Compute optimized",
671 | "gpuNum": 0,
672 | "hideHardwareSpecs": false,
673 | "memoryGiB": 192,
674 | "name": "ml.c5.24xlarge",
675 | "vcpuNum": 96
676 | },
677 | {
678 | "_defaultOrder": 29,
679 | "_isFastLaunch": true,
680 | "category": "Accelerated computing",
681 | "gpuNum": 1,
682 | "hideHardwareSpecs": false,
683 | "memoryGiB": 16,
684 | "name": "ml.g4dn.xlarge",
685 | "vcpuNum": 4
686 | },
687 | {
688 | "_defaultOrder": 30,
689 | "_isFastLaunch": false,
690 | "category": "Accelerated computing",
691 | "gpuNum": 1,
692 | "hideHardwareSpecs": false,
693 | "memoryGiB": 32,
694 | "name": "ml.g4dn.2xlarge",
695 | "vcpuNum": 8
696 | },
697 | {
698 | "_defaultOrder": 31,
699 | "_isFastLaunch": false,
700 | "category": "Accelerated computing",
701 | "gpuNum": 1,
702 | "hideHardwareSpecs": false,
703 | "memoryGiB": 64,
704 | "name": "ml.g4dn.4xlarge",
705 | "vcpuNum": 16
706 | },
707 | {
708 | "_defaultOrder": 32,
709 | "_isFastLaunch": false,
710 | "category": "Accelerated computing",
711 | "gpuNum": 1,
712 | "hideHardwareSpecs": false,
713 | "memoryGiB": 128,
714 | "name": "ml.g4dn.8xlarge",
715 | "vcpuNum": 32
716 | },
717 | {
718 | "_defaultOrder": 33,
719 | "_isFastLaunch": false,
720 | "category": "Accelerated computing",
721 | "gpuNum": 4,
722 | "hideHardwareSpecs": false,
723 | "memoryGiB": 192,
724 | "name": "ml.g4dn.12xlarge",
725 | "vcpuNum": 48
726 | },
727 | {
728 | "_defaultOrder": 34,
729 | "_isFastLaunch": false,
730 | "category": "Accelerated computing",
731 | "gpuNum": 1,
732 | "hideHardwareSpecs": false,
733 | "memoryGiB": 256,
734 | "name": "ml.g4dn.16xlarge",
735 | "vcpuNum": 64
736 | },
737 | {
738 | "_defaultOrder": 35,
739 | "_isFastLaunch": false,
740 | "category": "Accelerated computing",
741 | "gpuNum": 1,
742 | "hideHardwareSpecs": false,
743 | "memoryGiB": 61,
744 | "name": "ml.p3.2xlarge",
745 | "vcpuNum": 8
746 | },
747 | {
748 | "_defaultOrder": 36,
749 | "_isFastLaunch": false,
750 | "category": "Accelerated computing",
751 | "gpuNum": 4,
752 | "hideHardwareSpecs": false,
753 | "memoryGiB": 244,
754 | "name": "ml.p3.8xlarge",
755 | "vcpuNum": 32
756 | },
757 | {
758 | "_defaultOrder": 37,
759 | "_isFastLaunch": false,
760 | "category": "Accelerated computing",
761 | "gpuNum": 8,
762 | "hideHardwareSpecs": false,
763 | "memoryGiB": 488,
764 | "name": "ml.p3.16xlarge",
765 | "vcpuNum": 64
766 | },
767 | {
768 | "_defaultOrder": 38,
769 | "_isFastLaunch": false,
770 | "category": "Accelerated computing",
771 | "gpuNum": 8,
772 | "hideHardwareSpecs": false,
773 | "memoryGiB": 768,
774 | "name": "ml.p3dn.24xlarge",
775 | "vcpuNum": 96
776 | },
777 | {
778 | "_defaultOrder": 39,
779 | "_isFastLaunch": false,
780 | "category": "Memory Optimized",
781 | "gpuNum": 0,
782 | "hideHardwareSpecs": false,
783 | "memoryGiB": 16,
784 | "name": "ml.r5.large",
785 | "vcpuNum": 2
786 | },
787 | {
788 | "_defaultOrder": 40,
789 | "_isFastLaunch": false,
790 | "category": "Memory Optimized",
791 | "gpuNum": 0,
792 | "hideHardwareSpecs": false,
793 | "memoryGiB": 32,
794 | "name": "ml.r5.xlarge",
795 | "vcpuNum": 4
796 | },
797 | {
798 | "_defaultOrder": 41,
799 | "_isFastLaunch": false,
800 | "category": "Memory Optimized",
801 | "gpuNum": 0,
802 | "hideHardwareSpecs": false,
803 | "memoryGiB": 64,
804 | "name": "ml.r5.2xlarge",
805 | "vcpuNum": 8
806 | },
807 | {
808 | "_defaultOrder": 42,
809 | "_isFastLaunch": false,
810 | "category": "Memory Optimized",
811 | "gpuNum": 0,
812 | "hideHardwareSpecs": false,
813 | "memoryGiB": 128,
814 | "name": "ml.r5.4xlarge",
815 | "vcpuNum": 16
816 | },
817 | {
818 | "_defaultOrder": 43,
819 | "_isFastLaunch": false,
820 | "category": "Memory Optimized",
821 | "gpuNum": 0,
822 | "hideHardwareSpecs": false,
823 | "memoryGiB": 256,
824 | "name": "ml.r5.8xlarge",
825 | "vcpuNum": 32
826 | },
827 | {
828 | "_defaultOrder": 44,
829 | "_isFastLaunch": false,
830 | "category": "Memory Optimized",
831 | "gpuNum": 0,
832 | "hideHardwareSpecs": false,
833 | "memoryGiB": 384,
834 | "name": "ml.r5.12xlarge",
835 | "vcpuNum": 48
836 | },
837 | {
838 | "_defaultOrder": 45,
839 | "_isFastLaunch": false,
840 | "category": "Memory Optimized",
841 | "gpuNum": 0,
842 | "hideHardwareSpecs": false,
843 | "memoryGiB": 512,
844 | "name": "ml.r5.16xlarge",
845 | "vcpuNum": 64
846 | },
847 | {
848 | "_defaultOrder": 46,
849 | "_isFastLaunch": false,
850 | "category": "Memory Optimized",
851 | "gpuNum": 0,
852 | "hideHardwareSpecs": false,
853 | "memoryGiB": 768,
854 | "name": "ml.r5.24xlarge",
855 | "vcpuNum": 96
856 | },
857 | {
858 | "_defaultOrder": 47,
859 | "_isFastLaunch": false,
860 | "category": "Accelerated computing",
861 | "gpuNum": 1,
862 | "hideHardwareSpecs": false,
863 | "memoryGiB": 16,
864 | "name": "ml.g5.xlarge",
865 | "vcpuNum": 4
866 | },
867 | {
868 | "_defaultOrder": 48,
869 | "_isFastLaunch": false,
870 | "category": "Accelerated computing",
871 | "gpuNum": 1,
872 | "hideHardwareSpecs": false,
873 | "memoryGiB": 32,
874 | "name": "ml.g5.2xlarge",
875 | "vcpuNum": 8
876 | },
877 | {
878 | "_defaultOrder": 49,
879 | "_isFastLaunch": false,
880 | "category": "Accelerated computing",
881 | "gpuNum": 1,
882 | "hideHardwareSpecs": false,
883 | "memoryGiB": 64,
884 | "name": "ml.g5.4xlarge",
885 | "vcpuNum": 16
886 | },
887 | {
888 | "_defaultOrder": 50,
889 | "_isFastLaunch": false,
890 | "category": "Accelerated computing",
891 | "gpuNum": 1,
892 | "hideHardwareSpecs": false,
893 | "memoryGiB": 128,
894 | "name": "ml.g5.8xlarge",
895 | "vcpuNum": 32
896 | },
897 | {
898 | "_defaultOrder": 51,
899 | "_isFastLaunch": false,
900 | "category": "Accelerated computing",
901 | "gpuNum": 1,
902 | "hideHardwareSpecs": false,
903 | "memoryGiB": 256,
904 | "name": "ml.g5.16xlarge",
905 | "vcpuNum": 64
906 | },
907 | {
908 | "_defaultOrder": 52,
909 | "_isFastLaunch": false,
910 | "category": "Accelerated computing",
911 | "gpuNum": 4,
912 | "hideHardwareSpecs": false,
913 | "memoryGiB": 192,
914 | "name": "ml.g5.12xlarge",
915 | "vcpuNum": 48
916 | },
917 | {
918 | "_defaultOrder": 53,
919 | "_isFastLaunch": false,
920 | "category": "Accelerated computing",
921 | "gpuNum": 4,
922 | "hideHardwareSpecs": false,
923 | "memoryGiB": 384,
924 | "name": "ml.g5.24xlarge",
925 | "vcpuNum": 96
926 | },
927 | {
928 | "_defaultOrder": 54,
929 | "_isFastLaunch": false,
930 | "category": "Accelerated computing",
931 | "gpuNum": 8,
932 | "hideHardwareSpecs": false,
933 | "memoryGiB": 768,
934 | "name": "ml.g5.48xlarge",
935 | "vcpuNum": 192
936 | },
937 | {
938 | "_defaultOrder": 55,
939 | "_isFastLaunch": false,
940 | "category": "Accelerated computing",
941 | "gpuNum": 8,
942 | "hideHardwareSpecs": false,
943 | "memoryGiB": 1152,
944 | "name": "ml.p4d.24xlarge",
945 | "vcpuNum": 96
946 | },
947 | {
948 | "_defaultOrder": 56,
949 | "_isFastLaunch": false,
950 | "category": "Accelerated computing",
951 | "gpuNum": 8,
952 | "hideHardwareSpecs": false,
953 | "memoryGiB": 1152,
954 | "name": "ml.p4de.24xlarge",
955 | "vcpuNum": 96
956 | },
957 | {
958 | "_defaultOrder": 57,
959 | "_isFastLaunch": false,
960 | "category": "Accelerated computing",
961 | "gpuNum": 0,
962 | "hideHardwareSpecs": false,
963 | "memoryGiB": 32,
964 | "name": "ml.trn1.2xlarge",
965 | "vcpuNum": 8
966 | },
967 | {
968 | "_defaultOrder": 58,
969 | "_isFastLaunch": false,
970 | "category": "Accelerated computing",
971 | "gpuNum": 0,
972 | "hideHardwareSpecs": false,
973 | "memoryGiB": 512,
974 | "name": "ml.trn1.32xlarge",
975 | "vcpuNum": 128
976 | },
977 | {
978 | "_defaultOrder": 59,
979 | "_isFastLaunch": false,
980 | "category": "Accelerated computing",
981 | "gpuNum": 0,
982 | "hideHardwareSpecs": false,
983 | "memoryGiB": 512,
984 | "name": "ml.trn1n.32xlarge",
985 | "vcpuNum": 128
986 | }
987 | ],
988 | "instance_type": "ml.t3.medium",
989 | "kernelspec": {
990 | "display_name": ".venv",
991 | "language": "python",
992 | "name": "python3"
993 | },
994 | "language_info": {
995 | "codemirror_mode": {
996 | "name": "ipython",
997 | "version": 3
998 | },
999 | "file_extension": ".py",
1000 | "mimetype": "text/x-python",
1001 | "name": "python",
1002 | "nbconvert_exporter": "python",
1003 | "pygments_lexer": "ipython3",
1004 | "version": "3.10.13"
1005 | }
1006 | },
1007 | "nbformat": 4,
1008 | "nbformat_minor": 5
1009 | }
1010 |
--------------------------------------------------------------------------------