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 test_with_shell_env_value(self): """ Given values for the variables from shell environment """ expected = { "AWS_SAM_LOCAL": "true", "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", "AWS_LAMBDA_FUNCTION_...
Given values for the variables from shell environment
test_with_shell_env_value
python
aws/aws-sam-cli
tests/unit/local/lambdafn/test_env_vars.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/lambdafn/test_env_vars.py
Apache-2.0
def test_with_overrides_value(self): """ Given values for the variables from user specified overrides """ expected = { "AWS_SAM_LOCAL": "true", "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", "AWS_LAMBDA_FU...
Given values for the variables from user specified overrides
test_with_overrides_value
python
aws/aws-sam-cli
tests/unit/local/lambdafn/test_env_vars.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/lambdafn/test_env_vars.py
Apache-2.0
def test_verify_signal_handler(self, SignalMock, ThreadingMock): """ Verify the internal implementation of the Signal Handler """ is_debugging = True # We are debugging. So setup signal SignalMock.SIGTERM = "sigterm" # Fake the real method with a Lambda. Also run the ha...
Verify the internal implementation of the Signal Handler
test_verify_signal_handler
python
aws/aws-sam-cli
tests/unit/local/lambdafn/test_runtime.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/lambdafn/test_runtime.py
Apache-2.0
def test_verify_timer_handler(self, SignalMock, ThreadingMock): """ Verify the internal implementation of the Signal Handler """ is_debugging = False def fake_timer(timeout, handler, args): handler() return Mock() # Fake the real method with a La...
Verify the internal implementation of the Signal Handler
test_verify_timer_handler
python
aws/aws-sam-cli
tests/unit/local/lambdafn/test_runtime.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/lambdafn/test_runtime.py
Apache-2.0
def test_must_return_a_valid_file(self, unzip_file_mock, shutil_mock, os_mock): """ Input is a file that exists, but is not a zip/jar file """ code_path = "foo.exe" os_mock.path.isfile.return_value = True result = self.runtime._get_code_dir(code_path) # code pat...
Input is a file that exists, but is not a zip/jar file
test_must_return_a_valid_file
python
aws/aws-sam-cli
tests/unit/local/lambdafn/test_runtime.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/lambdafn/test_runtime.py
Apache-2.0
def test_download_layer_that_was_template_defined(self, create_cache_patch, resolve_code_path_patch): """ when the template is not lcoated in working directory, layer's codeuri needs to be adjusted """ stack_path_mock = Mock() stack_template_location = "./some/path/template.yaml"...
when the template is not lcoated in working directory, layer's codeuri needs to be adjusted
test_download_layer_that_was_template_defined
python
aws/aws-sam-cli
tests/unit/local/layers/test_download_layers.py
https://github.com/aws/aws-sam-cli/blob/master/tests/unit/local/layers/test_download_layers.py
Apache-2.0
def patched_get_checkpoint_shard_files( pretrained_model_name_or_path, index_filename, *args, **kwargs ) -> Tuple[List[str], dict]: """Same as modeling_utils.get_checkpoint_shard_files(), but does not download shards for the ignored keys.""" should_ignore_keys = _ignored_keys.get() is not None tempdir_...
Same as modeling_utils.get_checkpoint_shard_files(), but does not download shards for the ignored keys.
patched_get_checkpoint_shard_files
python
bigscience-workshop/petals
src/petals/client/from_pretrained.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/from_pretrained.py
MIT
async def create( cls, config: ClientConfig, p2p: P2P, span: RemoteSpanInfo, uid: ModuleUID, rpc_info: RPCInfo, **metadata, ) -> _ServerInferenceSession: """Create a new session for a given remote module. This code is meant to be run inside RemoteExper...
Create a new session for a given remote module. This code is meant to be run inside RemoteExpertWorker
create
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
def step( self, inputs: torch.Tensor, prompts: torch.Tensor, hypo_ids: torch.LongTensor, *, step_id: str, ) -> torch.Tensor: """ Inference step: send a chunk of input tensors and receive a chunk of outputs :prompts: optional DEEP prompts, added...
Inference step: send a chunk of input tensors and receive a chunk of outputs :prompts: optional DEEP prompts, added to a prefix of each layer's outputs, if specified, deep prompts should have shape [num_layers, batch_size, prefix_len, hid_size]
step
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
async def _step(self, inputs_serialized: runtime_pb2.ExpertRequest) -> runtime_pb2.ExpertResponse: """Inference step on serialized data. This code is meant to be run inside RemoteExpertWorker""" await self._inputs_queue.put(inputs_serialized) self.stepped = True return await asyncio.wait...
Inference step on serialized data. This code is meant to be run inside RemoteExpertWorker
_step
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
def close(self): """Finish a given inference session, close the underlying connection""" if self._outputs_stream is None: return # already closed RemoteExpertWorker.run_coroutine(self._aclose_stream()) self._outputs_stream = self._inputs_queue = None self.closed = Tr...
Finish a given inference session, close the underlying connection
close
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
async def _aclose_stream(self): """Close the inference session. This code is meant to be run inside RemoteExpertWorker""" if self._outputs_stream is None: return # already closed if self.stepped: await self._inputs_queue.put(runtime_pb2.ExpertRequest()) # empty request ...
Close the inference session. This code is meant to be run inside RemoteExpertWorker
_aclose_stream
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
def close(self, *exc_details): """Finish a given inference session, close the underlying connection""" if not self._closed: self._exit_server_sessions(self._server_sessions) self._server_sessions.clear() self._closed = True
Finish a given inference session, close the underlying connection
close
python
bigscience-workshop/petals
src/petals/client/inference_session.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/inference_session.py
MIT
def chunked_forward(self, hidden_states): """Splits word embeddings on chunks and iteratively casts them into fp32 to perform matmul more efficiently on CPU. chunked_forward_step: provides trade-off between efficiency and extra memory consumption. """ assert self.chunked_forward_step > 0...
Splits word embeddings on chunks and iteratively casts them into fp32 to perform matmul more efficiently on CPU. chunked_forward_step: provides trade-off between efficiency and extra memory consumption.
chunked_forward
python
bigscience-workshop/petals
src/petals/client/lm_head.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/lm_head.py
MIT
def force_non_empty_weights(): """ This context manager allows to bypass the accelerate.init_empty_weights() context manager (that forces all nn.Parameters to be PyTorch's meta tensors) used when low_cpu_mem_usage=True. The transformers library should replace all meta tensors by empty tensors by itself ...
This context manager allows to bypass the accelerate.init_empty_weights() context manager (that forces all nn.Parameters to be PyTorch's meta tensors) used when low_cpu_mem_usage=True. The transformers library should replace all meta tensors by empty tensors by itself but this feature does not work due...
force_non_empty_weights
python
bigscience-workshop/petals
src/petals/client/ptune.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/ptune.py
MIT
async def run_remote_forward( uid: ModuleUID, stub: StubBase, rpc_info: RPCInfo, *inputs: torch.Tensor, config: ClientConfig, metadata: Optional[bytes] = None, **kwargs, ) -> Tuple[torch.Tensor, ...]: """ Serializes input tensors and calls "rpc_forward" on a remote server. Mostly...
Serializes input tensors and calls "rpc_forward" on a remote server. Mostly adapted from https://github.com/learning-at-home/hivemind/blob/7a7c93aefffc9494c39e7b170c07cb06d8c09c4c/hivemind/moe/client/expert.py#L198 but without RemoteExpertWorker.run_coroutine() call that leads to deadlock here.
run_remote_forward
python
bigscience-workshop/petals
src/petals/client/remote_forward_backward.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/remote_forward_backward.py
MIT
async def run_remote_backward( uid: ModuleUID, stub: StubBase, rpc_info: RPCInfo, *inputs_and_grad_outputs: torch.Tensor, config: ClientConfig, metadata: Optional[bytes] = None, **kwargs, ) -> Sequence[torch.Tensor]: """ Serializes grad outputs and calls "rpc_backward" on a remote se...
Serializes grad outputs and calls "rpc_backward" on a remote server. Mostly adapted from https://github.com/learning-at-home/hivemind/blob/7a7c93aefffc9494c39e7b170c07cb06d8c09c4c/hivemind/moe/client/expert.py#L221 but without RemoteExpertWorker.run_coroutine() call that leads to deadlock here.
run_remote_backward
python
bigscience-workshop/petals
src/petals/client/remote_forward_backward.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/remote_forward_backward.py
MIT
def use_session(self, session: Optional[InferenceSession]) -> InferenceSession: """Inside this context, forward() will use an _existing_ InferenceSession provided as the argument.""" token = self._active_session.set(session) try: yield session finally: self._acti...
Inside this context, forward() will use an _existing_ InferenceSession provided as the argument.
use_session
python
bigscience-workshop/petals
src/petals/client/remote_sequential.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/remote_sequential.py
MIT
async def sequential_forward( inputs: torch.Tensor, prompts: torch.Tensor, sequence_manager: RemoteSequenceManager, start_index: int = 0, end_index: Optional[int] = None, ) -> Tuple[torch.Tensor, Sequence[torch.Tensor], Sequence[RemoteSpanInfo]]: """ Constructs a routing path from <start_ind...
Constructs a routing path from <start_index> to <end_index>. Performs chained forward for each subsequence of blocks on the path. If some subsequence fails, reconstructs the remaining path and tries to finish the forward.
sequential_forward
python
bigscience-workshop/petals
src/petals/client/sequential_autograd.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/sequential_autograd.py
MIT
async def sequential_backward( grad_outputs: Sequence[torch.Tensor], intermediate_inputs: List[torch.Tensor], prompts: torch.Tensor, forward_sequences: List[RemoteSpanInfo], sequence_manager: RemoteSequenceManager, ) -> Tuple[Sequence[torch.Tensor], torch.Tensor]: """ Performs chained backwa...
Performs chained backward for each forward subsequence. If some subsequence fails, reconstructs the particular sub-path and recovers the backward.
sequential_backward
python
bigscience-workshop/petals
src/petals/client/sequential_autograd.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/sequential_autograd.py
MIT
async def _gather_forward(input_batches, prompt_batches, sequence_manager): """Wrapper for asyncio.gather to perform parallel sequential forwards""" return await asyncio.gather( *[ sequential_forward(input_batch, prompt_batch, sequence_manager) for input_batch, prompt_batch in zi...
Wrapper for asyncio.gather to perform parallel sequential forwards
_gather_forward
python
bigscience-workshop/petals
src/petals/client/sequential_autograd.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/sequential_autograd.py
MIT
async def _gather_backward( grad_output_batches, intermediate_input_batches, prompt_batches, forward_sequences, sequence_manager ): """Wrapper for asyncio.gather to perform parallel sequential backwards""" return await asyncio.gather( *[ sequential_backward((grad_output,), input_batch, p...
Wrapper for asyncio.gather to perform parallel sequential backwards
_gather_backward
python
bigscience-workshop/petals
src/petals/client/sequential_autograd.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/sequential_autograd.py
MIT
def __getitem__(self, ix: Union[int, slice]) -> RemoteSequenceManager: """Get a RemoteSequenceManager for a sub-sequence of blocks""" assert isinstance(ix, (int, slice)) if not isinstance(ix, slice): ix = slice(int(ix), int(ix) + 1, 1) return type(self)(self.config, self.bloc...
Get a RemoteSequenceManager for a sub-sequence of blocks
__getitem__
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def update(self, *, wait: bool): """Run an asynchronous update in background as soon as possible""" self.ready.clear() self._thread.trigger.set() if wait: self.ready.wait()
Run an asynchronous update in background as soon as possible
update
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def _update(self): """Perform an immediate and synchronous refresh, may take time""" new_block_infos = get_remote_module_infos( self.dht, self.block_uids, active_adapter=self.config.active_adapter, latest=True ) for block_info in new_block_infos: # Apply allow a...
Perform an immediate and synchronous refresh, may take time
_update
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def on_request_failure(self, peer_id: Optional[PeerID]): """remove a given peer from the routing table. If the routing is no longer possible, trigger an update""" if peer_id is not None: logger.debug(f"Peer {peer_id} did not respond, banning it temporarily") self.state.banned_pee...
remove a given peer from the routing table. If the routing is no longer possible, trigger an update
on_request_failure
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def rpc_info(self): """Return the rpc_info queried from one of the servers that hold the first block""" if self.state.rpc_info is not None: return self.state.rpc_info with self._thread_start_lock: if not self.is_alive(): self._thread.start() for ...
Return the rpc_info queried from one of the servers that hold the first block
rpc_info
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def get_request_metadata( self, protocol: str, args_structure: Any = None, *args, **kwargs ) -> Optional[Dict[str, Any]]: """ :param protocol: one of "rpc_forward", "rpc_backward" or "rpc_inference" :param args_structure: the structure of flattened tensors from pack_args_kwargs in pe...
:param protocol: one of "rpc_forward", "rpc_backward" or "rpc_inference" :param args_structure: the structure of flattened tensors from pack_args_kwargs in petals.utils.packaging :param args: request-specific inputs, typically block uids and input tensors :param kwargs: additional reque...
get_request_metadata
python
bigscience-workshop/petals
src/petals/client/routing/sequence_manager.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/client/routing/sequence_manager.py
MIT
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[boo...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values...
forward
python
bigscience-workshop/petals
src/petals/models/llama/block.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/models/llama/block.py
MIT
def get_inference_cache_descriptors(self, batch_size: int, max_length: int) -> Sequence[TensorDescriptor]: """Create tensor descriptors for attention cache tensors used during inference_step""" head_dim = self.config.hidden_size // self.config.num_attention_heads cache_tensors = [] for d...
Create tensor descriptors for attention cache tensors used during inference_step
get_inference_cache_descriptors
python
bigscience-workshop/petals
src/petals/server/backend.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/backend.py
MIT
def _reorder_cache_inplace(self, cache_tensors: torch.Tensor, hypo_ids: torch.Tensor): """If hypo_ids is specified, reorder elements of each cache tensor in-place by taking indices from hypo_ids""" if not is_dummy(hypo_ids): for cache_tensor in cache_tensors: cache_tensor[......
If hypo_ids is specified, reorder elements of each cache tensor in-place by taking indices from hypo_ids
_reorder_cache_inplace
python
bigscience-workshop/petals
src/petals/server/backend.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/backend.py
MIT
def _select_layer_past(self, cache_tensors: Sequence[torch.Tensor], prefix_length: int) -> Sequence[torch.Tensor]: """Extract first {prefix_length} tokens and reshape them such that they can be used as layer_past""" key_cache, value_cache = list(cache_tensors[0::2]), list(cache_tensors[1::2]) fo...
Extract first {prefix_length} tokens and reshape them such that they can be used as layer_past
_select_layer_past
python
bigscience-workshop/petals
src/petals/server/backend.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/backend.py
MIT
def _update_cache_inplace( self, cache_tensors: Sequence[torch.Tensor], new_kvs: Sequence[torch.Tensor], prefix_length: int ): """Writes new key/value tensors back into cache, works in-place""" _batch_size_times_num_kv_heads, head_dim, new_length = new_kvs[0].shape for cache_key, new...
Writes new key/value tensors back into cache, works in-place
_update_cache_inplace
python
bigscience-workshop/petals
src/petals/server/backend.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/backend.py
MIT
def merge_inference_pools_inplace(backends: Dict[ExpertUID, TransformerBackend]): """Replace each backend's rpc_inference pools with a combined pool runs multiple blocks in one call""" assert len(backends) != 0 and all(isinstance(b, TransformerBackend) for b in backends.values()) first_pool = next(iter(back...
Replace each backend's rpc_inference pools with a combined pool runs multiple blocks in one call
merge_inference_pools_inplace
python
bigscience-workshop/petals
src/petals/server/backend.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/backend.py
MIT
async def run_rpc_forward( *flat_tensors: torch.Tensor, requested_backends: Sequence[TransformerBackend], active_adapter: str = "", prioritizer: TaskPrioritizerBase, points: int = 0, args_structure: Any = None, ) -> torch.Tensor: """ Run forward pass on deserialized inputs and prompts, u...
Run forward pass on deserialized inputs and prompts, used by rpc_forward and rpc_forward_stream :param flat_tensors: a list of tensors that includes first layer inputs, optional prompts and extra tensors :note: some input tensors can be missing, in which case they will be replaced with dummy tensors (see ...
run_rpc_forward
python
bigscience-workshop/petals
src/petals/server/block_functions.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/block_functions.py
MIT
def resolve_block_dtype(config: PretrainedConfig, dtype: Union[str, torch.dtype]) -> torch.dtype: """If dtype is "auto", resolves it using BloomConfig. Returns `dtype` intact otherwise.""" if dtype not in ("auto", None): return dtype if config.torch_dtype not in ("auto", None, torch.float32): ...
If dtype is "auto", resolves it using BloomConfig. Returns `dtype` intact otherwise.
resolve_block_dtype
python
bigscience-workshop/petals
src/petals/server/block_utils.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/block_utils.py
MIT
def get_model_block(config, layer_idx: int = 0): """ The function to create a model block based on the block class kwargs argument **only** is necessary for specific classes, like Mixtral. They will not be passed to other block constructors. """ if config.block_class == WrappedMixtralBlock: ...
The function to create a model block based on the block class kwargs argument **only** is necessary for specific classes, like Mixtral. They will not be passed to other block constructors.
get_model_block
python
bigscience-workshop/petals
src/petals/server/block_utils.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/block_utils.py
MIT
async def rpc_inference( self, requests: AsyncIterator[runtime_pb2.ExpertRequest], context: P2PContext, ) -> AsyncIterator[runtime_pb2.ExpertResponse]: """Compute a single step of inference using attention cache; update attention cache accordingly.""" async with timeout(self....
Compute a single step of inference using attention cache; update attention cache accordingly.
rpc_inference
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
async def rpc_push(self, request: runtime_pb2.ExpertRequest, context: P2PContext) -> runtime_pb2.ExpertResponse: """Directly push activation tensors from one server to another""" requested_uids = self._check_uids(request.uid) metadata = MSGPackSerializer.loads(request.metadata) session_...
Directly push activation tensors from one server to another
rpc_push
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
def _serialize_outputs( self, hidden_states: torch.Tensor, requested_backends: Sequence[TransformerBackend], metadata: Dict[str, Any], ) -> Sequence[runtime_pb2.Tensor]: """Serialize forward outputs using either outputs_schema or custom user-specified schema""" assert...
Serialize forward outputs using either outputs_schema or custom user-specified schema
_serialize_outputs
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
def _serialize_grads( self, grads: Sequence[torch.Tensor], requested_backends: Sequence[TransformerBackend], metadata: Dict[str, Any], ) -> Sequence[runtime_pb2.Tensor]: """Serialize backward gradients w.r.t. inputs using either default schema or custom user-specified schema"...
Serialize backward gradients w.r.t. inputs using either default schema or custom user-specified schema
_serialize_grads
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
def _check_uids(self, uids: str) -> Tuple[ModuleUID, ...]: """Check that the first request to rpc_inference is valid""" uids = (uids or "").split(CHAIN_DELIMITER) if not uids: raise RuntimeError("User did not provide any uids") for uid in uids: if uid not in self....
Check that the first request to rpc_inference is valid
_check_uids
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
async def _allocate_cache( self, backends: Sequence[TransformerBackend], *, batch_size: int, max_length: int, timeout: Optional[float], ) -> Sequence[Sequence[Handle]]: """ Allocate memory cache for all transformer blocks, return cache handle :...
Allocate memory cache for all transformer blocks, return cache handle :returns: a list of {len(backends)} elements, where i-th element is a tuple of cache handles for i-th backend
_allocate_cache
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
async def rpc_info(self, request: runtime_pb2.ExpertUID, context: P2PContext) -> runtime_pb2.ExpertInfo: """Return metadata about stored block uids and current load""" backend = self.module_backends[request.uid] if request.uid else next(iter(self.module_backends.values())) result = { ...
Return metadata about stored block uids and current load
rpc_info
python
bigscience-workshop/petals
src/petals/server/handler.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/handler.py
MIT
def get_allocation_size(*descriptors: TensorDescriptor) -> int: """Return the memory size (bytes) to be allocated on a device. If there are many devices, return maximum""" alloc_size_by_device = {} for descr in descriptors: tensor_size = descr.numel() * get_size_in_bytes(descr.dtype)...
Return the memory size (bytes) to be allocated on a device. If there are many devices, return maximum
get_allocation_size
python
bigscience-workshop/petals
src/petals/server/memory_cache.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/memory_cache.py
MIT
async def _schedule_alloc( self, alloc_size: int, *descriptors: TensorDescriptor, timeout: Optional[float] ) -> Sequence[Handle]: """ This method should be called inside asyncio.shield() because: - hivemind.utils.enter_asynchronously() does not always release the lock on cancella...
This method should be called inside asyncio.shield() because: - hivemind.utils.enter_asynchronously() does not always release the lock on cancellation
_schedule_alloc
python
bigscience-workshop/petals
src/petals/server/memory_cache.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/memory_cache.py
MIT
def use_cache(self, *handles: Handle) -> Sequence[torch.Tensor]: """ Return one or more tensors previously allocated with allocate_cache, :note: This method is called by ModuleBackend in runtime: a single process with NO process parallelism. However, runtime may call use_cache concurren...
Return one or more tensors previously allocated with allocate_cache, :note: This method is called by ModuleBackend in runtime: a single process with NO process parallelism. However, runtime may call use_cache concurrently with one or more connection handlers calling allocate_cache
use_cache
python
bigscience-workshop/petals
src/petals/server/memory_cache.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/memory_cache.py
MIT
def validate_reachability(peer_id, wait_time: float = 7 * 60, retry_delay: float = 15) -> None: """verify that your peer is reachable from a (centralized) validator, whether directly or through a relay""" for attempt_no in range(math.floor(wait_time / retry_delay) + 1): try: r = requests.get...
verify that your peer is reachable from a (centralized) validator, whether directly or through a relay
validate_reachability
python
bigscience-workshop/petals
src/petals/server/reachability.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/reachability.py
MIT
def check_direct_reachability(max_peers: int = 5, threshold: float = 0.5, **kwargs) -> Optional[bool]: """test if your peer is accessible by others in the swarm with the specified network options in **kwargs""" async def _check_direct_reachability(): target_dht = await DHTNode.create(client_mode=True, ...
test if your peer is accessible by others in the swarm with the specified network options in **kwargs
check_direct_reachability
python
bigscience-workshop/petals
src/petals/server/reachability.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/reachability.py
MIT
async def call_check(self, remote_peer: PeerID, *, check_peer: PeerID) -> Optional[bool]: """Returns True if remote_peer can reach check_peer, False if it cannot, None if it did not respond""" try: request = dht_pb2.PingRequest(peer=dht_pb2.NodeInfo(node_id=check_peer.to_bytes())) ...
Returns True if remote_peer can reach check_peer, False if it cannot, None if it did not respond
call_check
python
bigscience-workshop/petals
src/petals/server/reachability.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/reachability.py
MIT
async def rpc_check(self, request: dht_pb2.PingRequest, context: P2PContext) -> dht_pb2.PingResponse: """Help another peer to check its reachability""" response = dht_pb2.PingResponse(available=True) check_peer = PeerID(request.peer.node_id) if check_peer != context.local_id: # remote p...
Help another peer to check its reachability
rpc_check
python
bigscience-workshop/petals
src/petals/server/reachability.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/reachability.py
MIT
def __init__( self, *, initial_peers: List[str], dht_prefix: Optional[str], converted_model_name_or_path: str, public_name: Optional[str] = None, throughput: Union[float, str], num_blocks: Optional[int] = None, block_indices: Optional[str] = None, ...
Create a server with one or more bloom blocks. See run_server.py for documentation.
__init__
python
bigscience-workshop/petals
src/petals/server/server.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/server.py
MIT
def run_in_background(self, await_ready=True, timeout=None): """ Starts ModuleContainer in a background thread. if await_ready, this method will wait until the container is ready to process incoming requests or for :timeout: seconds max. """ self.start() if await_ready an...
Starts ModuleContainer in a background thread. if await_ready, this method will wait until the container is ready to process incoming requests or for :timeout: seconds max.
run_in_background
python
bigscience-workshop/petals
src/petals/server/server.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/server.py
MIT
def shutdown(self): """ Gracefully terminate the container, process-safe. Please note that terminating container otherwise (e.g. by killing processes) may result in zombie processes. If you did already cause a zombie outbreak, your only option is to kill them with -9 (SIGKILL). "...
Gracefully terminate the container, process-safe. Please note that terminating container otherwise (e.g. by killing processes) may result in zombie processes. If you did already cause a zombie outbreak, your only option is to kill them with -9 (SIGKILL).
shutdown
python
bigscience-workshop/petals
src/petals/server/server.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/server.py
MIT
def run(self): """Read tasks from incoming queue and put them into a local priority queue""" while True: task = self.submitted_tasks.get() if task is None: logger.debug("Shutting down prioritizer thread") break self._ordered_tasks.put(...
Read tasks from incoming queue and put them into a local priority queue
run
python
bigscience-workshop/petals
src/petals/server/task_pool.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/task_pool.py
MIT
def submit_task(self, *args: Any, priority: float = 0.0) -> MPFuture: """Add task to this pool's queue, return Future for its output""" future = MPFuture() # Remove shmem from MPFuture. This disables the .cancel() feature but # saves the server from "could not unlink the shared memory fi...
Add task to this pool's queue, return Future for its output
submit_task
python
bigscience-workshop/petals
src/petals/server/task_pool.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/task_pool.py
MIT
def get_task_size(self, task: Task) -> int: """compute task processing complexity; defaults to the total number of tokens""" if task.args and task.args[0].ndim >= 2: return task.args[0].shape[0] * task.args[0].shape[1] return 1
compute task processing complexity; defaults to the total number of tokens
get_task_size
python
bigscience-workshop/petals
src/petals/server/task_pool.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/task_pool.py
MIT
def send_outputs_from_runtime(self, uid: int, batch_outputs: List[torch.Tensor]): """send results for a processed batch, previously loaded through load_batch_to_runtime""" batch_outputs = [_move_to_device_if_tensor(output, device="cpu", share_memory=True) for output in batch_outputs] task = self...
send results for a processed batch, previously loaded through load_batch_to_runtime
send_outputs_from_runtime
python
bigscience-workshop/petals
src/petals/server/task_pool.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/server/task_pool.py
MIT
async def shield_and_wait(task): """ Works like asyncio.shield(), but waits for the task to finish before raising CancelledError to the caller. """ if not isinstance(task, asyncio.Task): task = asyncio.create_task(task) cancel_exc = None while True: try: result = aw...
Works like asyncio.shield(), but waits for the task to finish before raising CancelledError to the caller.
shield_and_wait
python
bigscience-workshop/petals
src/petals/utils/asyncio.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/asyncio.py
MIT
def make_inference_graphed_callable(callable: callable, sample_args, num_warmup_iters=3): """Similar to torch.cuda.make_graphed_callables, but takes only one function and does not build a graph for the backward pass""" assert not isinstance(callable, torch.nn.Module) if torch.is_autocast_enabled() and torch...
Similar to torch.cuda.make_graphed_callables, but takes only one function and does not build a graph for the backward pass
make_inference_graphed_callable
python
bigscience-workshop/petals
src/petals/utils/cuda_graphs.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/cuda_graphs.py
MIT
def declare_active_modules( dht: DHT, uids: Sequence[ModuleUID], server_info: ServerInfo, expiration_time: DHTExpiration, wait: bool = True, ) -> Union[Dict[ModuleUID, bool], MPFuture[Dict[ModuleUID, bool]]]: """ Declare that your node serves the specified modules; update timestamps if decla...
Declare that your node serves the specified modules; update timestamps if declared previously :param uids: a list of module ids to declare :param wait: if True, awaits for declaration to finish, otherwise runs in background :param throughput: specify your performance in terms of compute throughput ...
declare_active_modules
python
bigscience-workshop/petals
src/petals/utils/dht.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/dht.py
MIT
def initialize_logs(): """Initialize Petals logging tweaks. This function is called when you import the `petals` module.""" # Env var PETALS_LOGGING=False prohibits Petals do anything with logs if os.getenv("PETALS_LOGGING", "True").lower() in ("false", "0"): return hm_logging.use_hivemind_log...
Initialize Petals logging tweaks. This function is called when you import the `petals` module.
initialize_logs
python
bigscience-workshop/petals
src/petals/utils/logging.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/logging.py
MIT
def pack_args_kwargs(*args, **kwargs) -> Tuple[List[torch.Tensor], Any]: """ Check the function's arguments and pack all tensors into different flattened lists. :returns: a flattened list of tensors and args and kwargs, where tensors were masked """ masked_flat_values, flat_tensors, tensor_to_index ...
Check the function's arguments and pack all tensors into different flattened lists. :returns: a flattened list of tensors and args and kwargs, where tensors were masked
pack_args_kwargs
python
bigscience-workshop/petals
src/petals/utils/packaging.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/packaging.py
MIT
def unpack_args_kwargs(flat_tensors: List[torch.Tensor], args_structure: Any): """ Restore arguments after `pack_args_kwargs` function. :returns: list of args and dict of kwargs """ return nested_pack( ( value if not _is_masked_tensor(value) else flat_tensors[_get_tensor_index(va...
Restore arguments after `pack_args_kwargs` function. :returns: list of args and dict of kwargs
unpack_args_kwargs
python
bigscience-workshop/petals
src/petals/utils/packaging.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/packaging.py
MIT
def estimate_adapter_memory_per_block( block_config: transformers.PretrainedConfig, torch_dtype: Optional[torch.dtype], adapters: Sequence[str], **load_peft_kwargs, ) -> int: """Get the number of extra bytes used to store a set of adapters per given block""" with init_empty_weights(include_buffe...
Get the number of extra bytes used to store a set of adapters per given block
estimate_adapter_memory_per_block
python
bigscience-workshop/petals
src/petals/utils/peft.py
https://github.com/bigscience-workshop/petals/blob/master/src/petals/utils/peft.py
MIT
def _sift(self, fileslist, **arguments): """ a filter for time, size, name, head, tail, include, exclude, shuffle support regular expression """ # for shuffle if 's' in args.type_: random.shuffle(fileslist) return fileslist # for time ...
a filter for time, size, name, head, tail, include, exclude, shuffle support regular expression
_sift
python
PeterDing/iScript
pan.baidu.com.py
https://github.com/PeterDing/iScript/blob/master/pan.baidu.com.py
MIT
def __init__(self, config: Config) -> None: """ Initialize the API. Parameters ---------- config : Config The configuration. """ self.config = config self.stream_diffusion = StreamDiffusionWrapper( mode=config.mode, mod...
Initialize the API. Parameters ---------- config : Config The configuration.
__init__
python
cumulo-autumn/StreamDiffusion
demo/realtime-txt2img/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/demo/realtime-txt2img/main.py
Apache-2.0
async def _predict(self, inp: PredictInputModel) -> PredictResponseModel: """ Predict an image and return. Parameters ---------- inp : PredictInputModel The input. Returns ------- PredictResponseModel The prediction result. ...
Predict an image and return. Parameters ---------- inp : PredictInputModel The input. Returns ------- PredictResponseModel The prediction result.
_predict
python
cumulo-autumn/StreamDiffusion
demo/realtime-txt2img/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/demo/realtime-txt2img/main.py
Apache-2.0
def _pil_to_base64(self, image: Image.Image, format: str = "JPEG") -> bytes: """ Convert a PIL image to base64. Parameters ---------- image : Image.Image The PIL image. format : str The image format, by default "JPEG". Returns --...
Convert a PIL image to base64. Parameters ---------- image : Image.Image The PIL image. format : str The image format, by default "JPEG". Returns ------- bytes The base64 image.
_pil_to_base64
python
cumulo-autumn/StreamDiffusion
demo/realtime-txt2img/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/demo/realtime-txt2img/main.py
Apache-2.0
def _base64_to_pil(self, base64_image: str) -> Image.Image: """ Convert a base64 image to PIL. Parameters ---------- base64_image : str The base64 image. Returns ------- Image.Image The PIL image. """ if "base64," ...
Convert a base64 image to PIL. Parameters ---------- base64_image : str The base64 image. Returns ------- Image.Image The PIL image.
_base64_to_pil
python
cumulo-autumn/StreamDiffusion
demo/realtime-txt2img/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/demo/realtime-txt2img/main.py
Apache-2.0
def main( input: str, output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs", "output.mp4"), model_id: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog ears, thick frame glasses", scale: float = 1.0, acceleratio...
Process for generating images based on a prompt using a specified model. Parameters ---------- input : str, optional The input video name to load images from. output : str, optional The output video name to save images to. model_id_or_path : str The name of the model to...
main
python
cumulo-autumn/StreamDiffusion
demo/vid2vid/app.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/demo/vid2vid/app.py
Apache-2.0
def run( iterations: int = 100, model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", negative_prompt: str = "bad image , bad quality", use_lcm_lora: bool = True, use_tiny_vae: bool = ...
Initializes the StreamDiffusionWrapper. Parameters ---------- iterations : int, optional The number of iterations to run, by default 100. model_id_or_path : str The model id or path to load. lora_dict : Optional[Dict[str, float]], optional The lora_dict to load, by defa...
run
python
cumulo-autumn/StreamDiffusion
examples/benchmark/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/benchmark/multi.py
Apache-2.0
def run( iterations: int = 100, model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", negative_prompt: str = "bad image , bad quality", use_lcm_lora: bool = True, use_tiny_vae: bool = ...
Initializes the StreamDiffusionWrapper. Parameters ---------- iterations : int, optional The number of iterations to run, by default 100. model_id_or_path : str The model id or path to load. lora_dict : Optional[Dict[str, float]], optional The lora_dict to load, by defa...
run
python
cumulo-autumn/StreamDiffusion
examples/benchmark/single.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/benchmark/single.py
Apache-2.0
def main( input: str = os.path.join(CURRENT_DIR, "..", "..", "images", "inputs"), output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs"), model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick g...
Initializes the StreamDiffusionWrapper. Parameters ---------- input : str, optional The input directory to load images from. output : str, optional The output directory to save images to. model_id_or_path : str The model id or path to load. lora_dict : Optional[Dict...
main
python
cumulo-autumn/StreamDiffusion
examples/img2img/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/img2img/multi.py
Apache-2.0
def main( input: str = os.path.join(CURRENT_DIR, "..", "..", "images", "inputs", "input.png"), output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs", "output.png"), model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl w...
Initializes the StreamDiffusionWrapper. Parameters ---------- input : str, optional The input image file to load images from. output : str, optional The output image file to save images to. model_id_or_path : str The model id or path to load. lora_dict : Optional[Di...
main
python
cumulo-autumn/StreamDiffusion
examples/img2img/single.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/img2img/single.py
Apache-2.0
def update_image(image_data: Image.Image, labels: List[tk.Label]) -> None: """ Update the image displayed on a Tkinter label. Parameters ---------- image_data : Image.Image The image to be displayed. labels : List[tk.Label] The list of labels where the image will be updated. ...
Update the image displayed on a Tkinter label. Parameters ---------- image_data : Image.Image The image to be displayed. labels : List[tk.Label] The list of labels where the image will be updated.
update_image
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/multi.py
Apache-2.0
def image_generation_process( queue: Queue, fps_queue: Queue, prompt: str, model_id_or_path: str, batch_size: int = 10, acceleration: Literal["none", "xformers", "tensorrt"] = "tensorrt", ) -> None: """ Process for generating images based on a prompt using a specified model. Paramet...
Process for generating images based on a prompt using a specified model. Parameters ---------- queue : Queue The queue to put the generated images in. fps_queue : Queue The queue to put the calculated fps. prompt : str The prompt to generate images from. model_id_or...
image_generation_process
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/multi.py
Apache-2.0
def _receive_images( queue: Queue, fps_queue: Queue, labels: List[tk.Label], fps_label: tk.Label ) -> None: """ Continuously receive images from a queue and update the labels. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue t...
Continuously receive images from a queue and update the labels. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps. labels : List[tk.Label] The list of labels to update with images. fps_label :...
_receive_images
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/multi.py
Apache-2.0
def receive_images(queue: Queue, fps_queue: Queue) -> None: """ Setup the Tkinter window and start the thread to receive images. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps. """ root = tk.Tk(...
Setup the Tkinter window and start the thread to receive images. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps.
receive_images
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/multi.py
Apache-2.0
def main( prompt: str = "cat with sunglasses and a hat, photoreal, 8K", model_id_or_path: str = "stabilityai/sd-turbo", batch_size: int = 12, acceleration: Literal["none", "xformers", "tensorrt"] = "tensorrt", ) -> None: """ Main function to start the image generation and viewer processes. "...
Main function to start the image generation and viewer processes.
main
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/multi.py
Apache-2.0
def image_generation_process( queue: Queue, fps_queue: Queue, prompt: str, model_id_or_path: str, acceleration: Literal["none", "xformers", "tensorrt"] = "tensorrt", ) -> None: """ Process for generating images based on a prompt using a specified model. Parameters ---------- que...
Process for generating images based on a prompt using a specified model. Parameters ---------- queue : Queue The queue to put the generated images in. fps_queue : Queue The queue to put the calculated fps. prompt : str The prompt to generate images from. model_id_or...
image_generation_process
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/single.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/single.py
Apache-2.0
def main( prompt: str = "cat with sunglasses and a hat, photoreal, 8K", model_id_or_path: str = "stabilityai/sd-turbo", acceleration: Literal["none", "xformers", "tensorrt"] = "tensorrt", ) -> None: """ Main function to start the image generation and viewer processes. """ ctx = get_context('...
Main function to start the image generation and viewer processes.
main
python
cumulo-autumn/StreamDiffusion
examples/optimal-performance/single.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/optimal-performance/single.py
Apache-2.0
def image_generation_process( queue: Queue, fps_queue: Queue, close_queue: Queue, model_id_or_path: str, lora_dict: Optional[Dict[str, float]], prompt: str, negative_prompt: str, frame_buffer_size: int, width: int, height: int, acceleration: Literal["none", "xformers", "tenso...
Process for generating images based on a prompt using a specified model. Parameters ---------- queue : Queue The queue to put the generated images in. fps_queue : Queue The queue to put the calculated fps. model_id_or_path : str The name of the model to use for image ge...
image_generation_process
python
cumulo-autumn/StreamDiffusion
examples/screen/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/screen/main.py
Apache-2.0
def main( model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", negative_prompt: str = "low quality, bad quality, blurry, low resolution", frame_buffer_size: int = 1, width: int = 512, ...
Main function to start the image generation and viewer processes.
main
python
cumulo-autumn/StreamDiffusion
examples/screen/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/screen/main.py
Apache-2.0
def main( output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs",), model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", width: int = 512, height: int = 512, frame_bu...
Process for generating images based on a prompt using a specified model. Parameters ---------- output : str, optional The output image file to save images to. model_id_or_path : str The name of the model to use for image generation. lora_dict : Optional[Dict[str, float]], optio...
main
python
cumulo-autumn/StreamDiffusion
examples/txt2img/multi.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/txt2img/multi.py
Apache-2.0
def main( output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs", "output.png"), model_id_or_path: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog hair, thick glasses, smiling", width: int = 512, height: int = 512,...
Process for generating images based on a prompt using a specified model. Parameters ---------- output : str, optional The output image file to save images to. model_id_or_path : str The name of the model to use for image generation. lora_dict : Optional[Dict[str, float]], optio...
main
python
cumulo-autumn/StreamDiffusion
examples/txt2img/single.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/txt2img/single.py
Apache-2.0
def main( input: str, output: str = os.path.join(CURRENT_DIR, "..", "..", "images", "outputs", "output.mp4"), model_id: str = "KBlueLeaf/kohaku-v2.1", lora_dict: Optional[Dict[str, float]] = None, prompt: str = "1girl with brown dog ears, thick frame glasses", scale: float = 1.0, acceleratio...
Process for generating images based on a prompt using a specified model. Parameters ---------- input : str, optional The input video name to load images from. output : str, optional The output video name to save images to. model_id_or_path : str The name of the model to...
main
python
cumulo-autumn/StreamDiffusion
examples/vid2vid/main.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/examples/vid2vid/main.py
Apache-2.0
def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image: """ Convert a NumPy image or a batch of images to a PIL image. """ if images.ndim == 3: images = images[None, ...] images = (images * 255).round().astype("uint8") if images.shape[-1] == 1: # special case for grayscale (sing...
Convert a NumPy image or a batch of images to a PIL image.
numpy_to_pil
python
cumulo-autumn/StreamDiffusion
src/streamdiffusion/image_utils.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/src/streamdiffusion/image_utils.py
Apache-2.0
def update_image(image_data: Image.Image, label: tk.Label) -> None: """ Update the image displayed on a Tkinter label. Parameters ---------- image_data : Image.Image The image to be displayed. label : tk.Label The labels where the image will be updated. """ width = 512 ...
Update the image displayed on a Tkinter label. Parameters ---------- image_data : Image.Image The image to be displayed. label : tk.Label The labels where the image will be updated.
update_image
python
cumulo-autumn/StreamDiffusion
utils/viewer.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/viewer.py
Apache-2.0
def _receive_images( queue: Queue, fps_queue: Queue, label: tk.Label, fps_label: tk.Label ) -> None: """ Continuously receive images from a queue and update the labels. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put t...
Continuously receive images from a queue and update the labels. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps. label : tk.Label The label to update with images. fps_label : tk.Label ...
_receive_images
python
cumulo-autumn/StreamDiffusion
utils/viewer.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/viewer.py
Apache-2.0
def receive_images(queue: Queue, fps_queue: Queue) -> None: """ Setup the Tkinter window and start the thread to receive images. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps. """ root = tk.Tk(...
Setup the Tkinter window and start the thread to receive images. Parameters ---------- queue : Queue The queue to receive images from. fps_queue : Queue The queue to put the calculated fps.
receive_images
python
cumulo-autumn/StreamDiffusion
utils/viewer.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/viewer.py
Apache-2.0
def __init__( self, model_id_or_path: str, t_index_list: List[int], lora_dict: Optional[Dict[str, float]] = None, mode: Literal["img2img", "txt2img"] = "img2img", output_type: Literal["pil", "pt", "np", "latent"] = "pil", lcm_lora_id: Optional[str] = None, ...
Initializes the StreamDiffusionWrapper. Parameters ---------- model_id_or_path : str The model id or path to load. t_index_list : List[int] The t_index_list to use for inference. lora_dict : Optional[Dict[str, float]], optional The lo...
__init__
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def prepare( self, prompt: str, negative_prompt: str = "", num_inference_steps: int = 50, guidance_scale: float = 1.2, delta: float = 1.0, ) -> None: """ Prepares the model for inference. Parameters ---------- prompt : str ...
Prepares the model for inference. Parameters ---------- prompt : str The prompt to generate images from. num_inference_steps : int, optional The number of inference steps to perform, by default 50. guidance_scale : float, optional The...
prepare
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def __call__( self, image: Optional[Union[str, Image.Image, torch.Tensor]] = None, prompt: Optional[str] = None, ) -> Union[Image.Image, List[Image.Image]]: """ Performs img2img or txt2img based on the mode. Parameters ---------- image : Optional[Unio...
Performs img2img or txt2img based on the mode. Parameters ---------- image : Optional[Union[str, Image.Image, torch.Tensor]] The image to generate from. prompt : Optional[str] The prompt to generate images from. Returns ------- U...
__call__
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def txt2img( self, prompt: Optional[str] = None ) -> Union[Image.Image, List[Image.Image], torch.Tensor, np.ndarray]: """ Performs txt2img. Parameters ---------- prompt : Optional[str] The prompt to generate images from. Returns ------- ...
Performs txt2img. Parameters ---------- prompt : Optional[str] The prompt to generate images from. Returns ------- Union[Image.Image, List[Image.Image]] The generated image.
txt2img
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def img2img( self, image: Union[str, Image.Image, torch.Tensor], prompt: Optional[str] = None ) -> Union[Image.Image, List[Image.Image], torch.Tensor, np.ndarray]: """ Performs img2img. Parameters ---------- image : Union[str, Image.Image, torch.Tensor] T...
Performs img2img. Parameters ---------- image : Union[str, Image.Image, torch.Tensor] The image to generate from. Returns ------- Image.Image The generated image.
img2img
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def preprocess_image(self, image: Union[str, Image.Image]) -> torch.Tensor: """ Preprocesses the image. Parameters ---------- image : Union[str, Image.Image, torch.Tensor] The image to preprocess. Returns ------- torch.Tensor The ...
Preprocesses the image. Parameters ---------- image : Union[str, Image.Image, torch.Tensor] The image to preprocess. Returns ------- torch.Tensor The preprocessed image.
preprocess_image
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def postprocess_image( self, image_tensor: torch.Tensor, output_type: str = "pil" ) -> Union[Image.Image, List[Image.Image], torch.Tensor, np.ndarray]: """ Postprocesses the image. Parameters ---------- image_tensor : torch.Tensor The image tensor to post...
Postprocesses the image. Parameters ---------- image_tensor : torch.Tensor The image tensor to postprocess. Returns ------- Union[Image.Image, List[Image.Image]] The postprocessed image.
postprocess_image
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def _load_model( self, model_id_or_path: str, t_index_list: List[int], lora_dict: Optional[Dict[str, float]] = None, lcm_lora_id: Optional[str] = None, vae_id: Optional[str] = None, acceleration: Literal["none", "xformers", "tensorrt"] = "tensorrt", warmup...
Loads the model. This method does the following: 1. Loads the model from the model_id_or_path. 2. Loads and fuses the LCM-LoRA model from the lcm_lora_id if needed. 3. Loads the VAE model from the vae_id if needed. 4. Enables acceleration if needed. 5. Prepares...
_load_model
python
cumulo-autumn/StreamDiffusion
utils/wrapper.py
https://github.com/cumulo-autumn/StreamDiffusion/blob/master/utils/wrapper.py
Apache-2.0
def pvkblob_to_pkcs1(key): """ modified from impacket dpapi.py parse private key into pkcs#1 format :param key: :return: """ modulus = bytes_to_long(key["modulus"][::-1]) # n prime1 = bytes_to_long(key["prime1"][::-1]) # p prime2 = bytes_to_long(key["prime2"][::-1]) # q _ = by...
modified from impacket dpapi.py parse private key into pkcs#1 format :param key: :return:
pvkblob_to_pkcs1
python
zblurx/dploot
dploot/lib/crypto.py
https://github.com/zblurx/dploot/blob/master/dploot/lib/crypto.py
MIT