code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def predict(self, X): """Predict on a single input. :param X: The input to predict on. """ if isinstance(X, numpy.ndarray): X = X[None, :] if self.preprocess is not None: X = self.preprocess(X) X = self.object.predict(X, **self.predict_kwargs)[0] ...
Predict on a single input. :param X: The input to predict on.
predict
python
superduper-io/superduper
plugins/sklearn/superduper_sklearn/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/sklearn/superduper_sklearn/model.py
Apache-2.0
def watch_token_file(databackend): """Watch the Snowflake token file for changes. :param databackend: The data backend instance to reconnect. This function sets up a file system observer that watches The Snowflake token file for changes. When the token file is modified, it will trigger a reconnecti...
Watch the Snowflake token file for changes. :param databackend: The data backend instance to reconnect. This function sets up a file system observer that watches The Snowflake token file for changes. When the token file is modified, it will trigger a reconnection of the data backend.
watch_token_file
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/connect.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/connect.py
Apache-2.0
def connect(uri): """Connect to Snowflake using the Snowpark session. :param uri: The URI of the Snowflake connection. If the URI is 'snowflake://', the connection parameters are read from environment variables. - SNOWFLAKE_HOST: The Snowflake host. - SNOWFLAKE_PORT: The Snowflake port. -...
Connect to Snowflake using the Snowpark session. :param uri: The URI of the Snowflake connection. If the URI is 'snowflake://', the connection parameters are read from environment variables. - SNOWFLAKE_HOST: The Snowflake host. - SNOWFLAKE_PORT: The Snowflake port. - SNOWFLAKE_ACCOUNT: The S...
connect
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/connect.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/connect.py
Apache-2.0
def create_tables_and_schemas(self, events: t.List[CreateTable]): """Create tables and schemas in the data-backend. :param events: The events to create. """ if not events: return tables = set(self.list_tables()) events = [e for e in events if e.identifier not...
Create tables and schemas in the data-backend. :param events: The events to create.
create_tables_and_schemas
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def create_table_and_schema(self, identifier: str, schema: Schema, primary_id: str): """Create a schema in the data-backend. :param identifier: The identifier of the schema. :param schema: The schema to create. :param primary_id: The primary id of the schema. """ if iden...
Create a schema in the data-backend. :param identifier: The identifier of the schema. :param schema: The schema to create. :param primary_id: The primary id of the schema.
create_table_and_schema
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def _merge_schemas(self, tables: str): """Merge schemas. :param tables: The tables to merge. """ fields = {} for tab in tables: tab = self.get_table(tab) fields.update( { f.name.removeprefix('"').removesuffix('"'): f.da...
Merge schemas. :param tables: The tables to merge.
_merge_schemas
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def drop(self, force: bool = False): """Drop the databackend. :param force: If ``True``, don't ask for confirmation. """ if not force and not click.confirm( "Are you sure you want to drop the database?", default=False ): return for table in self.l...
Drop the databackend. :param force: If ``True``, don't ask for confirmation.
drop
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def list_tables(self): """List all tables or collections in the database.""" results_tables = self.session.sql("SHOW TABLES").collect() results_views = self.session.sql("SHOW VIEWS").collect() return [r.name for r in results_tables] + [r.name for r in results_views]
List all tables or collections in the database.
list_tables
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def insert(self, table_name, raw_documents, primary_id: str | None = None): """Insert data into the database. :param table: The table to insert into. :param raw_documents: The (encoded) documents to insert. """ if primary_id is None: primary_id = self.db.load('Table'...
Insert data into the database. :param table: The table to insert into. :param raw_documents: The (encoded) documents to insert.
insert
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def replace(self, table: str, condition: t.Dict, r: t.Dict) -> t.List[str]: """Replace data. :param table: The table to insert into. :param condition: The condition to update. :param r: The document to replace. """ t = self.get_table(table) cond = None fo...
Replace data. :param table: The table to insert into. :param condition: The condition to update. :param r: The document to replace.
replace
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def delete(self, table: str, condition: t.Dict): """Update data in the database. :param table: The table to update. :param condition: The condition to update. """ terms = [] for k, v in condition.items(): if isinstance(v, str): v = f"'{v}'" ...
Update data in the database. :param table: The table to update. :param condition: The condition to update.
delete
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def missing_outputs(self, query, predict_id): """Get missing outputs. :param query: The query to get the missing outputs of. :param predict_id: The identifier of the output destination. """ pid = self.primary_id(query.table) df = map_superduper_query_to_snowpark_query(se...
Get missing outputs. :param query: The query to get the missing outputs of. :param predict_id: The identifier of the output destination.
missing_outputs
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def select(self, query: Query, primary_id: str | None = None) -> t.List[t.Dict]: """Select data from the database. :param query: The query to perform. """ q = map_superduper_query_to_snowpark_query( self.session, query, primary_id or self.primary_id(q...
Select data from the database. :param query: The query to perform.
select
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def execute_native(self, query: str): """Execute a native query. :param query: The query to execute. """ results = self._run_query(query) out = [] for r in results: out.append(r.as_dict()) return out
Execute a native query. :param query: The query to execute.
execute_native
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/data_backend.py
Apache-2.0
def map_superduper_query_to_snowpark_query(session, query, primary_id: str = 'id'): """Map a SuperDuper query to a Snowpark query. :param session: The Snowpark session. :param query: The SuperDuper query. :param primary_id: The primary ID column. """ q = session.table(f'"{query.table}"') i...
Map a SuperDuper query to a Snowpark query. :param session: The Snowpark session. :param query: The SuperDuper query. :param primary_id: The primary ID column.
map_superduper_query_to_snowpark_query
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/query.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/query.py
Apache-2.0
def superduper_to_snowflake_schema(schema: Schema, primary_id: str): """Convert a SuperDuper schema to a Snowflake schema. :param schema: The SuperDuper schema. :param primary_id: The primary ID column. """ snowflake_schema = [] snowflake_schema.append(f'"{primary_id}" VARCHAR PRIMARY KEY') ...
Convert a SuperDuper schema to a Snowflake schema. :param schema: The SuperDuper schema. :param primary_id: The primary ID column.
superduper_to_snowflake_schema
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/schema.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/schema.py
Apache-2.0
def build_secret_status_report(db) -> SecretStatusReport: """Check if secrets are updated in Snowflake and return structured status. :param db: The database connection object. :return: SecretStatusReport with status for each secret """ result = db.databackend.execute_native("CALL v1.wrapper('SHOW S...
Check if secrets are updated in Snowflake and return structured status. :param db: The database connection object. :return: SecretStatusReport with status for each secret
build_secret_status_report
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/secrets.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/secrets.py
Apache-2.0
def raise_if_secrets_pending(report: SecretStatusReport): """Check if any secrets are pending and raise exception if so. :param report: SecretStatusReport to check :raises UpdatingSecretException: If any secrets are still updating """ pending_secrets = [ secret for secret in report.secrets ...
Check if any secrets are pending and raise exception if so. :param report: SecretStatusReport to check :raises UpdatingSecretException: If any secrets are still updating
raise_if_secrets_pending
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/secrets.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/secrets.py
Apache-2.0
def add(self, items: t.Sequence[VectorItem], cache: bool = False) -> None: """ Add items to the index. :param items: t.Sequence of VectorItems """ # NOTE: Since we will be doing vector search on tables directly # seperate vector search is not required.
Add items to the index. :param items: t.Sequence of VectorItems
add
python
superduper-io/superduper
plugins/snowflake/superduper_snowflake/vector_search.py
https://github.com/superduper-io/superduper/blob/master/plugins/snowflake/superduper_snowflake/vector_search.py
Apache-2.0
def __init__(self, uri: str, flavour: t.Optional[str] = None): """Initialize the thread-local connection manager. :param uri: URI to the database. :param flavour: Flavour of the database. """ self.uri = uri self.flavour = flavour self.local = threading.local() ...
Initialize the thread-local connection manager. :param uri: URI to the database. :param flavour: Flavour of the database.
__init__
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def _create_connection(self): """Create a new connection specifically for this thread.""" name = self.uri.split("//")[0] in_memory = False ibis_conn = ibis.connect(self.uri) return ibis_conn, name, in_memory
Create a new connection specifically for this thread.
_create_connection
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def get_connection(self): """Get a connection for the current thread, creating it if it doesn't exist.""" if not hasattr(self.local, "connection"): with self.lock: # Lock only during connection creation self.local.connection, self.local.name, self.local.in_memory = ( ...
Get a connection for the current thread, creating it if it doesn't exist.
get_connection
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def vector_impl(self): """Get the vector implementation based on the URI.""" if self.uri.startswith("snowflake"): return NativeVector return Array
Get the vector implementation based on the URI.
vector_impl
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def url(self): """Get the URL of the database.""" with self.connection_manager.get_connection() as conn: return conn.con.url + self.name
Get the URL of the database.
url
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def check_output_dest(self, predict_id) -> bool: """Check if the output destination exists. :param predict_id: The identifier of the prediction. """ with self.connection_manager.get_connection() as conn: try: conn.table(f"{CFG.output_prefix}{predict_id}") ...
Check if the output destination exists. :param predict_id: The identifier of the prediction.
check_output_dest
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def create_table_and_schema(self, identifier: str, schema: Schema, primary_id: str): """Create a schema in the data-backend. :param identifier: The identifier of the table. :param mapping: The mapping of the schema. """ with self.connection_manager.get_connection() as conn: ...
Create a schema in the data-backend. :param identifier: The identifier of the table. :param mapping: The mapping of the schema.
create_table_and_schema
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def drop(self, force: bool = False): """Drop tables or collections in the database. :param force: Whether to force the drop. """ if not force and not click.confirm("Are you sure you want to drop all tables?"): logging.info("Aborting drop tables") return ...
Drop tables or collections in the database. :param force: Whether to force the drop.
drop
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def get_table(self, identifier): """Get a table or collection from the database. :param identifier: The identifier of the table or collection. """ with self.connection_manager.get_connection() as conn: try: return conn.table(identifier) except ibi...
Get a table or collection from the database. :param identifier: The identifier of the table or collection.
get_table
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def missing_outputs(self, query, predict_id: str) -> t.List[str]: """Get missing outputs from the database.""" with self.connection_manager.get_connection() as conn: pid = self.primary_id(query.table) query = self._build_native_query(conn, query) output_table = conn.t...
Get missing outputs from the database.
missing_outputs
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def json_native(self): """Check if the database supports JSON natively.""" if self.uri.startswith("postgres"): return True return False
Check if the database supports JSON natively.
json_native
python
superduper-io/superduper
plugins/sql/superduper_sql/data_backend.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/data_backend.py
Apache-2.0
def convert_data_format(self, data): """Convert byte data to base64 format for storage in the database. :param data: The data to convert. """ if isinstance(data, bytes): return BASE64_PREFIX + base64.b64encode(data).decode("utf-8") else: return data
Convert byte data to base64 format for storage in the database. :param data: The data to convert.
convert_data_format
python
superduper-io/superduper
plugins/sql/superduper_sql/db_helper.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/db_helper.py
Apache-2.0
def recover_data_format(self, data): """Recover byte data from base64 format stored in the database. :param data: The data to recover. """ if isinstance(data, str) and data.startswith(BASE64_PREFIX): return base64.b64decode(data[len(BASE64_PREFIX) :]) else: ...
Recover byte data from base64 format stored in the database. :param data: The data to recover.
recover_data_format
python
superduper-io/superduper
plugins/sql/superduper_sql/db_helper.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/db_helper.py
Apache-2.0
def process_schema_types(self, schema_mapping): """Convert bytes to string in the schema. :param schema_mapping: The schema mapping to convert. """ for key, value in schema_mapping.items(): if value == "Bytes": schema_mapping[key] = "String" return sc...
Convert bytes to string in the schema. :param schema_mapping: The schema mapping to convert.
process_schema_types
python
superduper-io/superduper
plugins/sql/superduper_sql/db_helper.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/db_helper.py
Apache-2.0
def process_before_insert(self, table_name, datas, conn): """Convert byte data to base64 format for storage in the database. :param table_name: The name of the table. :param datas: The data to insert. """ datas = pd.DataFrame(datas) # change the order of the columns sinc...
Convert byte data to base64 format for storage in the database. :param table_name: The name of the table. :param datas: The data to insert.
process_before_insert
python
superduper-io/superduper
plugins/sql/superduper_sql/db_helper.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/db_helper.py
Apache-2.0
def get_db_helper(dialect) -> DBHelper: """Get the insert processor for the given dialect. :param dialect: The dialect of the database. """ for helper in DBHelper.__subclasses__(): if helper.match_dialect == dialect: return helper(dialect) return DBHelper(dialect)
Get the insert processor for the given dialect. :param dialect: The dialect of the database.
get_db_helper
python
superduper-io/superduper
plugins/sql/superduper_sql/db_helper.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/db_helper.py
Apache-2.0
def convert_schema_to_fields(schema: Schema, json_native: bool) -> dict: """Return the raw fields. Get a dictionary of fields as keys and datatypes as values. This is used to create ibis tables. :param schema: The schema to convert """ fields = {} for k, v in schema.fields.items(): ...
Return the raw fields. Get a dictionary of fields as keys and datatypes as values. This is used to create ibis tables. :param schema: The schema to convert
convert_schema_to_fields
python
superduper-io/superduper
plugins/sql/superduper_sql/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/sql/superduper_sql/utils.py
Apache-2.0
def torchmodel(class_obj): """A decorator to convert a `torch.nn.Module` into a `TorchModel`. Decorate a `torch.nn.Module` so that when it is invoked, the result is a `TorchModel`. :param class_obj: Class to decorate """ def factory( identifier: str, *args, preprocess:...
A decorator to convert a `torch.nn.Module` into a `TorchModel`. Decorate a `torch.nn.Module` so that when it is invoked, the result is a `TorchModel`. :param class_obj: Class to decorate
torchmodel
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def get_merkle_tree(self, breaks): """Get the merkle tree of the model.""" t = super().get_merkle_tree(breaks) self.setup() w = next(iter(self.object.state_dict().values())) model_h = hash_item(w.tolist()) t['object'] = model_h return t
Get the merkle tree of the model.
get_merkle_tree
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def train_forward_signature(self): """Infer signature of train forward pass.""" if ( self._train_forward_signature is None and self.forward_method != self.train_forward_method ): self._train_forward_signature = self._infer_signature( getattr(se...
Infer signature of train forward pass.
train_forward_signature
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def saving(self): """Context manager for saving the model. This context manager ensures that the model is in evaluation mode """ was_training = self.object.training try: self.object.eval() yield finally: if was_training: ...
Context manager for saving the model. This context manager ensures that the model is in evaluation mode
saving
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def predict(self, *args, **kwargs): """Predict on a single input. :param args: Input arguments :param kwargs: Input keyword arguments """ if self.signature == 'singleton': item = args[0] elif self.signature == '*args': item = args elif sel...
Predict on a single input. :param args: Input arguments :param kwargs: Input keyword arguments
predict
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def predict_batches(self, dataset: t.Union[t.List, QueryDataset]) -> t.List: """Predict on a dataset. :param dataset: Dataset """ with torch.no_grad(), eval(self.object): inputs = BasicDataset( items=dataset, transform=self.preprocess, ...
Predict on a dataset. :param dataset: Dataset
predict_batches
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def train_forward(self, X, y=None): """The forward method for training. :param X: Input :param y: Target """ X = X.to(self.device) if y is not None: y = y.to(self.device) method = getattr(self.object, self.train_forward_method) if hasattr(sel...
The forward method for training. :param X: Input :param y: Target
train_forward
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def unpack_batch(args): """Unpack a batch into lines of tensor output. :param args: a batch of model outputs >>> unpack_batch(torch.randn(1, 10))[0].shape torch.Size([10]) >>> out = unpack_batch([torch.randn(2, 10), torch.randn(2, 3, 5)]) >>> type(out) <class 'list'> >>> len(out) 2...
Unpack a batch into lines of tensor output. :param args: a batch of model outputs >>> unpack_batch(torch.randn(1, 10))[0].shape torch.Size([10]) >>> out = unpack_batch([torch.randn(2, 10), torch.randn(2, 3, 5)]) >>> type(out) <class 'list'> >>> len(out) 2 >>> out = unpack_batch({'a...
unpack_batch
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def create_batch(args): """Create a singleton batch in a manner similar to the PyTorch dataloader. :param args: single data point for batching >>> create_batch(3.).shape torch.Size([1]) >>> x, y = create_batch([torch.randn(5), torch.randn(3, 7)]) >>> x.shape torch.Size([1, 5]) >>> y.sh...
Create a singleton batch in a manner similar to the PyTorch dataloader. :param args: single data point for batching >>> create_batch(3.).shape torch.Size([1]) >>> x, y = create_batch([torch.randn(5), torch.randn(3, 7)]) >>> x.shape torch.Size([1, 5]) >>> y.shape torch.Size([1, 3, 7]) ...
create_batch
python
superduper-io/superduper
plugins/torch/superduper_torch/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/model.py
Apache-2.0
def get_optimizers(self, model): """Get the optimizers for the model. :param model: Model """ cls_ = getattr(torch.optim, self.optimizer_cls) optimizer = cls_(model.parameters(), **self.optimizer_kwargs) if self.optimizer_state is not None: self.optimizer.loa...
Get the optimizers for the model. :param model: Model
get_optimizers
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def take_step(self, model, batch, optimizers): """Take a step in the optimization. :param model: Model :param batch: Batch of data :param optimizers: Optimizers """ if self.signature == '*args': outputs = model.train_forward(*batch) elif self.signatur...
Take a step in the optimization. :param model: Model :param batch: Batch of data :param optimizers: Optimizers
take_step
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def compute_validation_objective(self, model, valid_dataloader): """Compute the validation objective. :param model: Model :param valid_dataloader: Validation dataloader to use """ objective_values = [] with model.evaluating(), torch.no_grad(): for batch in va...
Compute the validation objective. :param model: Model :param valid_dataloader: Validation dataloader to use
compute_validation_objective
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def append_metrics(self, d: t.Dict[str, float]) -> None: """Append metrics to the metric_values dict. :param d: Metrics to append """ if self.metric_values is not None: for k, v in d.items(): self.metric_values.setdefault(k, []).append(v)
Append metrics to the metric_values dict. :param d: Metrics to append
append_metrics
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def stopping_criterion(self, iteration): """Check if the training should stop. :param iteration: Current iteration """ max_iterations = self.max_iterations no_improve_then_stop = self.no_improve_then_stop if isinstance(max_iterations, int) and iteration >= max_iterations...
Check if the training should stop. :param iteration: Current iteration
stopping_criterion
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def saving_criterion(self): """Check if the model should be saved.""" if self.listen == 'objective': to_listen = [-x for x in self.metric_values['objective']] else: to_listen = self.metric_values[self.listen] if all([to_listen[-1] >= x for x in to_listen[:-1]]): ...
Check if the model should be saved.
saving_criterion
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def log(self, **kwargs): """Log the training progress. :param kwargs: Key-value pairs to log """ out = '' for k, v in kwargs.items(): if isinstance(v, dict): for kk, vv in v.items(): out += f'{k}/{kk}: {vv}; ' else: ...
Log the training progress. :param kwargs: Key-value pairs to log
log
python
superduper-io/superduper
plugins/torch/superduper_torch/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/training.py
Apache-2.0
def device_of(module: Module) -> t.Union[_device, str]: """ Get device of a model. :param module: PyTorch model """ try: return next(iter(module.state_dict().values())).device except StopIteration: return 'cpu'
Get device of a model. :param module: PyTorch model
device_of
python
superduper-io/superduper
plugins/torch/superduper_torch/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/utils.py
Apache-2.0
def eval(module: Module) -> t.Iterator[None]: """ Temporarily set a module to evaluation mode. :param module: PyTorch module """ was_training = module.training try: module.eval() yield finally: if was_training: module.train()
Temporarily set a module to evaluation mode. :param module: PyTorch module
eval
python
superduper-io/superduper
plugins/torch/superduper_torch/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/utils.py
Apache-2.0
def set_device(module: Module, device: _device): """ Temporarily set a device of a module. :param module: PyTorch module :param device: Device to set """ device_before = device_of(module) try: module.to(device) yield finally: module.to(device_before)
Temporarily set a device of a module. :param module: PyTorch module :param device: Device to set
set_device
python
superduper-io/superduper
plugins/torch/superduper_torch/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/utils.py
Apache-2.0
def to_device( item: t.Any, # lists or dicts of Tensors device: t.Union[str, _device], ) -> t.Any: """ Send tensor leaves of nested list/ dictionaries/ tensors to device. :param item: torch.Tensor instance :param device: device to which one would like to send """ if isinstance(item, tu...
Send tensor leaves of nested list/ dictionaries/ tensors to device. :param item: torch.Tensor instance :param device: device to which one would like to send
to_device
python
superduper-io/superduper
plugins/torch/superduper_torch/utils.py
https://github.com/superduper-io/superduper/blob/master/plugins/torch/superduper_torch/utils.py
Apache-2.0
def fit( self, model: 'TextClassificationPipeline', db: Datalayer, train_dataset: QueryDataset, valid_dataset: QueryDataset, ): """Fit the model. :param model: model :param db: Datalayer instance :param train_dataset: training dataset ...
Fit the model. :param model: model :param db: Datalayer instance :param train_dataset: training dataset :param valid_dataset: validation dataset
fit
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def from_pretrained( cls, model_name_or_path, identifier="", prompt_template="{input}", prompt_func=None, predict_kwargs=None, **kwargs, ): """A new function to create a LLM model from from_pretrained function. Allow the user to directly repla...
A new function to create a LLM model from from_pretrained function. Allow the user to directly replace: `AutoModelForCausalLM.from_pretrained` -> `LLM.from_pretrained` :param model_name_or_path: model name or path :param identifier: model identifier :param prompt_template: prom...
from_pretrained
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def init_pipeline( self, adapter_id: t.Optional[str] = None, load_adapter_directly: bool = False ): """Initialize pipeline. :param adapter_id: adapter id :param load_adapter_directly: load adapter directly """ # Do not update model state here model_kwargs = s...
Initialize pipeline. :param adapter_id: adapter id :param load_adapter_directly: load adapter directly
init_pipeline
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def setup(self, db=None): """Initialize the model. If adapter_id is provided, will load the adapter to the model. """ super().setup() real_adapter_id = None if self.adapter_id is not None: if isinstance(self.adapter_id, Checkpoint): real_adapt...
Initialize the model. If adapter_id is provided, will load the adapter to the model.
setup
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def predict(self, X, **kwargs): """Generate text from a single prompt. :param X: a prompt :param kwargs: additional keyword arguments """ X = self._process_inputs(X, **kwargs) kwargs.pop("context", None) results = self._batch_generate([X], **kwargs) retur...
Generate text from a single prompt. :param X: a prompt :param kwargs: additional keyword arguments
predict
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def predict_batches( self, dataset: t.Union[t.List, QueryDataset], **kwargs ) -> t.List: """Generate text from a list of prompts. :param dataset: a list of prompts :param kwargs: additional keyword arguments """ dataset = [ self._process_inputs(dataset[i]...
Generate text from a list of prompts. :param dataset: a list of prompts :param kwargs: additional keyword arguments
predict_batches
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def _batch_generate(self, prompts: t.List[str], **kwargs) -> t.List[str]: """Generate text. Can overwrite this method to support more inference methods. """ kwargs = {**self.predict_kwargs, **kwargs.copy()} # Set default values, if not will cause bad output outputs = se...
Generate text. Can overwrite this method to support more inference methods.
_batch_generate
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def add_adapter(self, model_id, adapter_name: str): """Add adapter to the model. :param model_id: model id :param adapter_name: adapter name """ # TODO: Support lora checkpoint from s3 try: from peft import PeftModel except Exception as e: ...
Add adapter to the model. :param model_id: model id :param adapter_name: adapter name
add_adapter
python
superduper-io/superduper
plugins/transformers/superduper_transformers/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/model.py
Apache-2.0
def on_save(self, args, state, control, **kwargs): """Event called after a checkpoint save. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other key...
Event called after a checkpoint save. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other keyword arguments from transformers.
on_save
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def on_evaluate(self, args, state, control, **kwargs): """Event called after an evaluation. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other key...
Event called after an evaluation. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other keyword arguments from transformers.
on_evaluate
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def on_train_end(self, args, state, control, **kwargs): """Event called after training ends. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other ke...
Event called after training ends. :param args: The training arguments from transformers. :param state: The training state from transformers. :param control: The training control from transformers. :param kwargs: Other keyword arguments from transformers.
on_train_end
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def check_init(self): """Check the initialization of the callback.""" # Only check this in the world_rank 0 process # Rebuild datalayer for the new process if self.db is None: self.db = build_datalayer(self.cfg) self.llm = self.db.load("model", self.identifier) ...
Check the initialization of the callback.
check_init
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def get_compute_metrics(metrics): """Get the compute metrics function. :param metrics: List of callable metric functions. Each function should take logits and labels as input and return a metric value. """ if not metrics: retu...
Get the compute metrics function. :param metrics: List of callable metric functions. Each function should take logits and labels as input and return a metric value.
get_compute_metrics
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def fit( self, model: 'LLM', db: Datalayer, train_dataset: t.Union[QueryDataset, NativeDataset], valid_dataset: t.Union[QueryDataset, NativeDataset], ): """Fit the model on the training dataset. :param model: The model to fit. :param db: The datalayer...
Fit the model on the training dataset. :param model: The model to fit. :param db: The datalayer to use. :param train_dataset: The training dataset to use. :param valid_dataset: The validation dataset to use.
fit
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def tokenize(tokenizer, example, X, y): """Function to tokenize the example. :param tokenizer: The tokenizer to use. :param example: The example to tokenize. :param X: The input key. :param y: The output key. """ prompt = example[X] prompt = prompt + tokenizer.eos_token result = to...
Function to tokenize the example. :param tokenizer: The tokenizer to use. :param example: The example to tokenize. :param X: The input key. :param y: The output key.
tokenize
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def train( training_args: LLMTrainer, train_dataset: NativeDataset, eval_datasets: t.Union[NativeDataset, t.Dict[str, NativeDataset]], model_kwargs: dict, tokenizer_kwargs: dict, db: t.Optional["Datalayer"] = None, llm: t.Optional["LLM"] = None, ray_configs: t.Optional[dict] = None, ...
Train LLM model on specified dataset. The training process can be run on these following modes: - Local node without ray, but only support single GPU - Local node with ray, support multi-nodes and multi-GPUs - Remote node with ray, support multi-nodes and multi-GPUs If run locally, will use train_...
train
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def handle_ray_results(db, llm, results): """Handle the ray results. Will save the checkpoint to db if db and llm provided. :param db: datalayer, used for saving the checkpoint :param llm: llm model, used for saving the checkpoint :param results: the ray training results, contains the checkpoint ...
Handle the ray results. Will save the checkpoint to db if db and llm provided. :param db: datalayer, used for saving the checkpoint :param llm: llm model, used for saving the checkpoint :param results: the ray training results, contains the checkpoint
handle_ray_results
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def train_func( training_args: LLMTrainer, train_dataset: "Dataset", eval_datasets: t.Union["Dataset", t.Dict[str, "Dataset"]], model_kwargs: dict, tokenizer_kwargs: dict, trainer_prepare_func: t.Optional[t.Callable] = None, callbacks=None, **kwargs, ): """Base training function for ...
Base training function for LLM model. :param training_args: training Arguments, see LLMTrainingArguments :param train_dataset: training dataset, can be huggingface datasets.Dataset or ray.data.Dataset :param eval_datasets: evaluation dataset, can be a dict of datasets :param model_kwargs: model...
train_func
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def ray_train( training_args: LLMTrainer, train_dataset, eval_datasets, ray_configs: t.Optional[t.Dict[str, t.Any]] = None, **kwargs, ): """Ray training function for LLM model. The ray train function will handle the following logic: - Prepare the datasets for ray - Build the trainin...
Ray training function for LLM model. The ray train function will handle the following logic: - Prepare the datasets for ray - Build the training_loop_func for ray - Connect to ray cluster - Make some modifications to be compatible with ray finetune llm :param training_args: training Arguments,...
ray_train
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def prepare_lora_training(model, config: LLMTrainer): """Prepare LoRA training for the model. Get the LoRA target modules and convert the model to peft model. :param model: The model to prepare for LoRA training. :param config: The configuration to use. """ try: from peft import LoraCo...
Prepare LoRA training for the model. Get the LoRA target modules and convert the model to peft model. :param model: The model to prepare for LoRA training. :param config: The configuration to use.
prepare_lora_training
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def create_quantization_config(config: LLMTrainer): """Create quantization config for LLM training. :param config: The configuration to use. """ compute_dtype = ( torch.float16 if config.fp16 else (torch.bfloat16 if config.bf16 else torch.float32) ) if config.bits is not...
Create quantization config for LLM training. :param config: The configuration to use.
create_quantization_config
python
superduper-io/superduper
plugins/transformers/superduper_transformers/training.py
https://github.com/superduper-io/superduper/blob/master/plugins/transformers/superduper_transformers/training.py
Apache-2.0
def predict( self, messages: list["ChatCompletionMessageParam"], **kwargs, ) -> t.Any: """Chat with the model. :param messages: List of messages to chat with the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for mor...
Chat with the model. :param messages: List of messages to chat with the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for more details
predict
python
superduper-io/superduper
plugins/vllm/superduper_vllm/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/vllm/superduper_vllm/model.py
Apache-2.0
async def async_predict( self, messages: list["ChatCompletionMessageParam"], *args, **kwargs, ): """Chat with the model asynchronously. :param messages: List of messages to chat with the model :param kwargs: Additional keyword arguments, ...
Chat with the model asynchronously. :param messages: List of messages to chat with the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for more details
async_predict
python
superduper-io/superduper
plugins/vllm/superduper_vllm/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/vllm/superduper_vllm/model.py
Apache-2.0
def predict( self, prompt: str, **kwargs, ) -> t.Any: """Generate completion for the given prompt. :param prompt: Prompt to generate completion for the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for more details ...
Generate completion for the given prompt. :param prompt: Prompt to generate completion for the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for more details
predict
python
superduper-io/superduper
plugins/vllm/superduper_vllm/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/vllm/superduper_vllm/model.py
Apache-2.0
async def async_predict( self, prompt: str, **kwargs, ): """Generate completion for the given prompt asynchronously. :param prompt: Prompt to generate completion for the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams...
Generate completion for the given prompt asynchronously. :param prompt: Prompt to generate completion for the model :param kwargs: Additional keyword arguments, see vllm.SamplingParams for more details
async_predict
python
superduper-io/superduper
plugins/vllm/superduper_vllm/model.py
https://github.com/superduper-io/superduper/blob/master/plugins/vllm/superduper_vllm/model.py
Apache-2.0
def initialize_with_components(self): """Initialize the backend with components. This method is executed when a cluster is initialized. """ for info in self.db.show(): obj = self.db.load(info['component'], info['identifier']) if isreallyinstance(obj, self.cls): ...
Initialize the backend with components. This method is executed when a cluster is initialized.
initialize_with_components
python
superduper-io/superduper
superduper/backends/base/backends.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/backends.py
Apache-2.0
def put_component(self, component: str, uuid: str, **kwargs): """Put a component to the backend. :param component: Component to put. :param uuid: UUID of the component. :param kwargs: Additional arguments. """ object = self.db.load(component=component, uuid=uuid) ...
Put a component to the backend. :param component: Component to put. :param uuid: UUID of the component. :param kwargs: Additional arguments.
put_component
python
superduper-io/superduper
superduper/backends/base/backends.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/backends.py
Apache-2.0
def drop_component(self, component: str, identifier: str): """Drop the component from backend. :param component: Component name. :param identifier: Component identifier. """ uuids = self.component_uuid_mapping[(component, identifier)] tool_ids = [] for uuid in uu...
Drop the component from backend. :param component: Component name. :param identifier: Component identifier.
drop_component
python
superduper-io/superduper
superduper/backends/base/backends.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/backends.py
Apache-2.0
def drop(self, component: t.Optional['Component'] = None): """Drop the backend. :param component: Component to Drop. """
Drop the backend. :param component: Component to Drop.
drop
python
superduper-io/superduper
superduper/backends/base/backends.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/backends.py
Apache-2.0
def put_component(self, component: str, uuid: str): """Add a component to the deployment. :param component: ``Component`` to put. :param uuid: UUID of the component. """
Add a component to the deployment. :param component: ``Component`` to put. :param uuid: UUID of the component.
put_component
python
superduper-io/superduper
superduper/backends/base/backends.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/backends.py
Apache-2.0
def drop(self, force: bool = False): """Drop all of the backends. :param force: Skip confirmation. """ if not force and not click.confirm( "Are you sure you want to drop the cluster?" ): return self.compute.drop() self.scheduler.drop() ...
Drop all of the backends. :param force: Skip confirmation.
drop
python
superduper-io/superduper
superduper/backends/base/cluster.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/cluster.py
Apache-2.0
def db(self, value): """Set the ``db``. :param value: ``Datalayer`` instance. """ self._db = value self.scheduler.db = value self.vector_search.db = value self.crontab.db = value if self.compute is not None: self.compute.db = value sel...
Set the ``db``. :param value: ``Datalayer`` instance.
db
python
superduper-io/superduper
superduper/backends/base/cluster.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/cluster.py
Apache-2.0
def put_component(self, component: str, uuid: str): """Create handler on component declare. :param component: Component to put. :param uuid: UUID of the component. """
Create handler on component declare. :param component: Component to put. :param uuid: UUID of the component.
put_component
python
superduper-io/superduper
superduper/backends/base/compute.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/compute.py
Apache-2.0
def drop_component(self, component: str, identifier: str): """Drop the component from compute. :param component: Component name. :param identifier: Component identifier. """
Drop the component from compute. :param component: Component name. :param identifier: Component identifier.
drop_component
python
superduper-io/superduper
superduper/backends/base/compute.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/compute.py
Apache-2.0
def drop_table(self, table: str): """Drop data from table. :param table: The table to drop. """
Drop data from table. :param table: The table to drop.
drop_table
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def create_tables_and_schemas(self, events: t.List['CreateTable']): """Create a schema in the data-backend. :param events: List of `CreateTable` events. """ from superduper.base.schema import Schema for event in events: self.create_table_and_schema( ...
Create a schema in the data-backend. :param events: List of `CreateTable` events.
create_tables_and_schemas
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def insert(self, table: str, documents: t.Sequence[t.Dict]) -> t.List[str]: """Insert data into the database. :param table: The table to insert into. :param documents: The documents to insert. """
Insert data into the database. :param table: The table to insert into. :param documents: The documents to insert.
insert
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def do_replace(self, table: str, condition: t.Dict, r: t.Dict): """Replace data in the database. This method is a wrapper around the `replace` method to ensure that the datatype is set to `None` by default. :param table: The table to insert into. :param condition: The condition...
Replace data in the database. This method is a wrapper around the `replace` method to ensure that the datatype is set to `None` by default. :param table: The table to insert into. :param condition: The condition to update. :param r: The document to replace.
do_replace
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def do_update( self, table: str, condition: t.Dict, key: str, value: t.Any, datatype: BaseDataType | None = None, ): """Update data in the database. This method is a wrapper around the `update` method to ensure that the datatype is set to `Non...
Update data in the database. This method is a wrapper around the `update` method to ensure that the datatype is set to `None` by default. :param table: The table to update. :param condition: The condition to update. :param key: The key to update. :param value: The value...
do_update
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def update(self, table: str, condition: t.Dict, key: str, value: t.Any): """Update data in the database. :param table: The table to update. :param condition: The condition to update. :param key: The key to update. :param value: The value to update. """
Update data in the database. :param table: The table to update. :param condition: The condition to update. :param key: The key to update. :param value: The value to update.
update
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def missing_outputs(self, query: Query, predict_id: str) -> t.List[str]: """Get missing outputs from an outputs query. This method will be used to perform an anti-join between the input and the outputs table, and return the missing ids. :param query: The query to perform. :para...
Get missing outputs from an outputs query. This method will be used to perform an anti-join between the input and the outputs table, and return the missing ids. :param query: The query to perform. :param predict_id: The predict id.
missing_outputs
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def get(self, query: Query, raw: bool = False): """Get a single result from a query. :param query: The query to perform. :param raw: If ``True``, return raw results. """ assert query.type == 'select' if query.decomposition.pre_like: return list(self.pre_like...
Get a single result from a query. :param query: The query to perform. :param raw: If ``True``, return raw results.
get
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def execute(self, query: Query, raw: bool = False): """Execute a query. :param query: The query to execute. :param raw: If ``True``, return raw results. """ query = query if '.outputs' not in str(query) else query.complete_uuids(self.db) schema = self.get_schema(query) ...
Execute a query. :param query: The query to execute. :param raw: If ``True``, return raw results.
execute
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0
def get_schema(self, query) -> 'Schema': """Get the schema of a query. :param query: The query to get the schema of. """ base_schema = self.db.metadata.get_schema(query.table) if query.decomposition.outputs: for predict_id in query.decomposition.outputs.args: ...
Get the schema of a query. :param query: The query to get the schema of.
get_schema
python
superduper-io/superduper
superduper/backends/base/data_backend.py
https://github.com/superduper-io/superduper/blob/master/superduper/backends/base/data_backend.py
Apache-2.0