Skip to content

autobatch

AutoBatchedPotential

Bases: Potential

AutoBatchedPotential is a wrapper around a Potential that enables automatic batching of concurrent requests.

This class collects concurrent requests to instance methods (complete, prefix, score, logw_next) and batches them together before delegating to the corresponding batch methods of the underlying potential (batch_complete, batch_prefix, batch_score, batch_logw_next).

This class inherits all methods from Potential.

Attributes:

Name Type Description
potential Potential

The underlying potential instance that is being wrapped.

Source code in genlm/control/potential/autobatch.py
class AutoBatchedPotential(Potential):
    """
    AutoBatchedPotential is a wrapper around a Potential that enables automatic batching of concurrent requests.

    This class collects concurrent requests to instance methods
    (`complete`, `prefix`, `score`, `logw_next`) and batches them together before
    delegating to the corresponding batch methods of the underlying potential
    (`batch_complete`, `batch_prefix`, `batch_score`, `batch_logw_next`).

    This class inherits all methods from [`Potential`][genlm.control.potential.base.Potential].

    Attributes:
        potential (Potential): The underlying potential instance that is being wrapped.
    """

    def __init__(self, potential):
        self.potential = potential
        self._batches = weakref.WeakKeyDictionary()  # event loop -> _Batch
        super().__init__(potential.vocab, tables=potential.tables)

    async def _queued(self, batch_method_name, context):
        future = asyncio.get_running_loop().create_future()
        batch = await join_batch(self._batches, (batch_method_name, context, future))
        if batch is not None:
            await self._flush(batch)
        return await future

    async def _flush(self, queue):
        """Run each batch method once over its queued requests and resolve every future."""
        groups = defaultdict(list)
        for method_name, context, future in queue:
            groups[method_name].append((context, future))
        for method_name, requests in groups.items():
            try:
                results = await getattr(self.potential, method_name)(
                    [context for context, _ in requests]
                )
                # `batch_logw_next` answers with a single batched LazyWeights [N, V+1],
                # unlike the other batch methods' [N] arrays of results.
                if isinstance(results, LazyWeights):
                    results = [
                        results.spawn(results.weights[i])
                        for i in range(len(requests))
                    ]
                assert len(results) == len(requests)
                for (_, future), result in zip(requests, results):
                    if not future.done():
                        future.set_result(result)
            except Exception as exc:
                fail_futures(requests, exc)
            except BaseException as exc:
                # Unwinding: nothing else will resolve the futures still pending.
                for rest in groups.values():
                    fail_futures(rest, batch_abandoned(exc))
                raise

    async def complete(self, context):
        return await self._queued("batch_complete", context)

    async def prefix(self, context):
        return await self._queued("batch_prefix", context)

    async def score(self, context):
        return await self._queued("batch_score", context)

    async def logw_next(self, context):
        return await self._queued("batch_logw_next", context)

    async def logw_eos(self, context):
        return await self.potential.logw_eos(context)

    async def batch_complete(self, contexts):
        return await self.potential.batch_complete(contexts)

    async def batch_prefix(self, contexts):
        return await self.potential.batch_prefix(contexts)

    async def batch_score(self, contexts):
        return await self.potential.batch_score(contexts)

    async def batch_logw_next(self, contexts):
        return await self.potential.batch_logw_next(contexts)

    def is_terminal_only(self):
        return self.potential.is_terminal_only()

    async def sparse_logw_next(self, context):
        return await self.potential.sparse_logw_next(context)

    def alloc_rows(self, n, default=float("-inf")):
        return self.potential.alloc_rows(n, default)

    def spawn(self, *args, **kwargs):
        return autobatched(self.potential.spawn(*args, **kwargs))

    def __repr__(self):
        return f"{self.__class__.__name__}({self.potential!r})"

    async def cleanup(self):
        """Async cleanup of the wrapped potential."""
        await self.potential.cleanup()

cleanup() async

Async cleanup of the wrapped potential.

Source code in genlm/control/potential/autobatch.py
async def cleanup(self):
    """Async cleanup of the wrapped potential."""
    await self.potential.cleanup()

autobatched(potential)

Return the autobatched view of a potential.

Memoized on the potential, so every call site shares one wrapper and one batch.

Parameters:

Name Type Description Default
potential Potential

The potential to wrap. None passes through, as does an already-wrapped potential.

required

Returns:

Type Description
AutoBatchedPotential

The potential's autobatched wrapper.

Source code in genlm/control/potential/autobatch.py
def autobatched(potential):
    """
    Return the autobatched view of a potential.

    Memoized on the potential, so every call site shares one wrapper and one batch.

    Args:
        potential (Potential): The potential to wrap. `None` passes through, as does
            an already-wrapped potential.

    Returns:
        (AutoBatchedPotential): The potential's autobatched wrapper.
    """
    if potential is None or isinstance(potential, AutoBatchedPotential):
        return potential
    wrapper = potential.__dict__.get("_autobatched")
    if wrapper is None:
        wrapper = potential._autobatched = AutoBatchedPotential(potential)
    return wrapper