SqrtSpace SpaceTime for Python
Memory-efficient algorithms and data structures for Python using Williams' √n space-time tradeoffs.
Installation
pip install sqrtspace-spacetime
For ML features:
pip install sqrtspace-spacetime[ml]
For all features:
pip install sqrtspace-spacetime[all]
Core Concepts
SpaceTime implements theoretical computer science results showing that many algorithms can achieve better memory usage by accepting slightly slower runtime. The key insight is using √n memory instead of n memory, where n is the input size.
Key Features
- Memory-Efficient Collections: Arrays and dictionaries that automatically spill to disk
- External Algorithms: Sort and group large datasets using minimal memory
- Streaming Operations: Process files larger than RAM with elegant API
- Auto-Checkpointing: Resume long computations from where they left off
- Memory Profiling: Identify optimization opportunities in your code
- ML Optimizations: Reduce neural network training memory by up to 90%
Quick Start
Basic Usage
from sqrtspace_spacetime import SpaceTimeArray, external_sort, Stream
# Memory-efficient array that spills to disk
array = SpaceTimeArray(threshold=10000)
for i in range(1000000):
array.append(i)
# Sort large datasets with minimal memory
huge_list = list(range(10000000, 0, -1))
sorted_data = external_sort(huge_list) # Uses only √n memory
# Stream processing
Stream.from_csv('huge_file.csv') \
.filter(lambda row: row['value'] > 100) \
.map(lambda row: row['value'] * 1.1) \
.group_by(lambda row: row['category']) \
.to_csv('processed.csv')
Examples
Basic Examples
See examples/basic_usage.py for comprehensive examples of:
- SpaceTimeArray and SpaceTimeDict usage
- External sorting and grouping
- Stream processing
- Memory profiling
- Auto-checkpointing
FastAPI Web Application
Check out examples/fastapi-app/ for a production-ready web application featuring:
- Streaming endpoints for large datasets
- Server-Sent Events (SSE) for real-time data
- Memory-efficient CSV exports
- Checkpointed background tasks
- ML model serving with memory constraints
See the FastAPI example README for detailed documentation.
Machine Learning Pipeline
Explore examples/ml-pipeline/ for ML-specific patterns:
- Training models on datasets larger than RAM
- Memory-efficient feature extraction
- Checkpointed training loops
- Streaming predictions
- Integration with PyTorch and TensorFlow
See the ML Pipeline README for complete documentation.
Memory-Efficient Collections
from sqrtspace_spacetime import SpaceTimeArray, SpaceTimeDict
# Array that automatically manages memory
array = SpaceTimeArray(threshold=1000) # Keep 1000 items in memory
for i in range(1000000):
array.append(f"item_{i}")
# Dictionary with LRU eviction to disk
cache = SpaceTimeDict(threshold=10000)
for key, value in huge_dataset:
cache[key] = expensive_computation(value)
External Algorithms
from sqrtspace_spacetime import external_sort, external_groupby
# Sort 100M items using only ~10K memory
data = list(range(100_000_000, 0, -1))
sorted_data = external_sort(data)
# Group by with aggregation
sales = [
{'store': 'A', 'amount': 100},
{'store': 'B', 'amount': 200},
# ... millions more
]
by_store = external_groupby(
sales,
key_func=lambda x: x['store']
)
# Aggregate with minimal memory
from sqrtspace_spacetime.algorithms import groupby_sum
totals = groupby_sum(
sales,
key_func=lambda x: x['store'],
value_func=lambda x: x['amount']
)
Streaming Operations
from sqrtspace_spacetime import Stream
# Process large files efficiently
stream = Stream.from_csv('sales_2023.csv')
.filter(lambda row: row['amount'] > 0)
.map(lambda row: {
'month': row['date'][:7],
'amount': float(row['amount'])
})
.group_by(lambda row: row['month'])
.to_csv('monthly_summary.csv')
# Chain operations
top_products = Stream.from_jsonl('products.jsonl') \
.filter(lambda p: p['in_stock']) \
.sort(key=lambda p: p['revenue'], reverse=True) \
.take(100) \
.collect()
Auto-Checkpointing
from sqrtspace_spacetime.checkpoint import auto_checkpoint
@auto_checkpoint(total_iterations=1000000)
def process_large_dataset(data):
results = []
for i, item in enumerate(data):
# Process item
result = expensive_computation(item)
results.append(result)
# Yield state for checkpointing
yield {'i': i, 'results': results}
return results
# Automatically resumes from checkpoint if interrupted
results = process_large_dataset(huge_dataset)
Memory Profiling
from sqrtspace_spacetime.profiler import profile, profile_memory
@profile(output_file="profile.json")
def my_algorithm(data):
# Process data
return results
# Get detailed memory analysis
result, report = my_algorithm(data)
print(report.summary)
# Simple memory tracking
@profile_memory(threshold_mb=100)
def memory_heavy_function():
# Alerts if memory usage exceeds threshold
large_list = list(range(10000000))
return sum(large_list)
ML Memory Optimization
from sqrtspace_spacetime.ml import MLMemoryOptimizer
import torch.nn as nn
# Analyze model memory usage
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
optimizer = MLMemoryOptimizer()
profile = optimizer.analyze_model(model, input_shape=(784,), batch_size=32)
# Get optimization plan
plan = optimizer.optimize(profile, target_batch_size=128)
print(plan.explanation)
# Apply optimizations
config = optimizer.get_training_config(plan, profile)
Advanced Features
Memory Pressure Handling
from sqrtspace_spacetime.memory import MemoryMonitor, LoggingHandler
# Monitor memory pressure
monitor = MemoryMonitor()
monitor.add_handler(LoggingHandler())
# Your arrays automatically respond to memory pressure
array = SpaceTimeArray()
# Arrays spill to disk when memory is low
Configuration
from sqrtspace_spacetime import SpaceTimeConfig
# Global configuration
SpaceTimeConfig.set_defaults(
memory_limit=2 * 1024**3, # 2GB
chunk_strategy='sqrt_n',
compression='gzip',
external_storage_path='/fast/ssd/temp'
)
Parallel Processing
from sqrtspace_spacetime.batch import BatchProcessor
processor = BatchProcessor(
memory_threshold=0.8,
checkpoint_enabled=True
)
# Process in memory-efficient batches
result = processor.process(
huge_list,
lambda batch: [transform(item) for item in batch]
)
print(f"Processed {result.get_success_count()} items")
Real-World Examples
Processing Large CSV Files
from sqrtspace_spacetime import Stream
from sqrtspace_spacetime.profiler import profile_memory
@profile_memory(threshold_mb=500)
def analyze_sales_data(filename):
# Stream process to stay under memory limit
return Stream.from_csv(filename) \
.filter(lambda row: row['status'] == 'completed') \
.map(lambda row: {
'product': row['product_id'],
'revenue': float(row['price']) * int(row['quantity'])
}) \
.group_by(lambda row: row['product']) \
.sort(key=lambda group: sum(r['revenue'] for r in group[1]), reverse=True) \
.take(10) \
.collect()
top_products = analyze_sales_data('sales_2023.csv')
Training Large Neural Networks
from sqrtspace_spacetime.ml import MLMemoryOptimizer, GradientCheckpointer
import torch.nn as nn
# Memory-efficient training
def train_large_model(model, train_loader, epochs=10):
# Analyze memory requirements
optimizer = MLMemoryOptimizer()
profile = optimizer.analyze_model(model, input_shape=(3, 224, 224), batch_size=32)
# Get optimization plan
plan = optimizer.optimize(profile, target_batch_size=128)
# Apply gradient checkpointing
checkpointer = GradientCheckpointer()
model = checkpointer.apply_checkpointing(model, plan.checkpoint_layers)
# Train with optimized settings
for epoch in range(epochs):
for batch in train_loader:
# Training loop with automatic memory management
pass
Data Pipeline with Checkpoints
from sqrtspace_spacetime import Stream
from sqrtspace_spacetime.checkpoint import auto_checkpoint
@auto_checkpoint(total_iterations=1000000)
def process_user_events(event_file):
processed = 0
for event in Stream.from_jsonl(event_file):
# Complex processing
user_profile = enhance_profile(event)
recommendations = generate_recommendations(user_profile)
save_to_database(recommendations)
processed += 1
# Checkpoint state
yield {'processed': processed, 'last_event': event['id']}
return processed
# Automatically resumes if interrupted
total = process_user_events('events.jsonl')
Performance Benchmarks
| Operation | Standard Python | SpaceTime | Memory Reduction | Time Overhead |
|---|---|---|---|---|
| Sort 10M integers | 400MB | 20MB | 95% | 40% |
| Process 1GB CSV | 1GB | 32MB | 97% | 20% |
| Group by on 1M rows | 200MB | 14MB | 93% | 30% |
| Neural network training | 8GB | 2GB | 75% | 15% |
API Reference
Collections
SpaceTimeArray: Memory-efficient list with disk spilloverSpaceTimeDict: Memory-efficient dictionary with LRU eviction
Algorithms
external_sort(): Sort large datasets with √n memoryexternal_groupby(): Group large datasets with √n memoryexternal_join(): Join large datasets efficiently
Streaming
Stream: Lazy evaluation stream processingFileStream: Stream lines from filesCSVStream: Stream CSV rowsJSONLStream: Stream JSON Lines
Memory Management
MemoryMonitor: Monitor memory pressureMemoryPressureHandler: Custom pressure handlers
Checkpointing
@auto_checkpoint: Automatic checkpointing decoratorCheckpointManager: Manual checkpoint control
ML Optimization
MLMemoryOptimizer: Analyze and optimize modelsGradientCheckpointer: Apply gradient checkpointing
Profiling
@profile: Full profiling decorator@profile_memory: Memory-only profilingSpaceTimeProfiler: Programmatic profiling
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
Apache License 2.0. See LICENSE for details.
Citation
If you use SpaceTime in your research, please cite:
@software{sqrtspace_spacetime,
title = {SqrtSpace SpaceTime: Memory-Efficient Python Library},
author={Friedel Jr., David H.},
year = {2025},
url = {https://github.com/sqrtspace/sqrtspace-python}
}
Links
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2024 Ubiquity SpaceTime Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.