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 listen(
target: 'IEventsTarget',
event_type: Type[_EventType],
callback: Callable[[_EventType], Coroutine[Any, Any, None]],
) -> None:
"""Registers a listener function for the given target and event type
.. code-block:: python3
async def callback(event: SomeEvent):
print(ev... | Registers a listener function for the given target and event type
.. code-block:: python3
async def callback(event: SomeEvent):
print(event.data)
listen(target, SomeEvent, callback)
| listen | python | vmagamedov/grpclib | grpclib/events.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/events.py | BSD-3-Clause |
def cert(self) -> Optional[Dict[str, Any]]:
"""Returns the peer certificate
Result of the :py:meth:`python:ssl.SSLSocket.getpeercert`
"""
ssl_object = self._transport.get_extra_info('ssl_object')
if ssl_object is not None:
return ssl_object.getpeercert() # type: ign... | Returns the peer certificate
Result of the :py:meth:`python:ssl.SSLSocket.getpeercert`
| cert | python | vmagamedov/grpclib | grpclib/protocol.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/protocol.py | BSD-3-Clause |
async def recv_message(self) -> Optional[_RecvType]:
"""Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns N... | Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns None when the client has
ended the stream. To simplify yo... | recv_message | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def send_initial_metadata(
self,
*,
metadata: Optional[_MetadataLike] = None,
) -> None:
"""Coroutine to send headers with initial metadata to the client.
In gRPC you can send initial metadata as soon as possible, because
gRPC doesn't use `:status` pseudo heade... | Coroutine to send headers with initial metadata to the client.
In gRPC you can send initial metadata as soon as possible, because
gRPC doesn't use `:status` pseudo header to indicate success or failure
of the current request. gRPC uses trailers for this purpose, and
trailers are sent du... | send_initial_metadata | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def send_message(self, message: _SendType) -> None:
"""Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:par... | Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:param message: message object
| send_message | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def send_trailing_metadata(
self,
*,
status: Status = Status.OK,
status_message: Optional[str] = None,
status_details: Any = None,
metadata: Optional[_MetadataLike] = None,
) -> None:
"""Coroutine to send trailers with trailing metadata to the client.
... | Coroutine to send trailers with trailing metadata to the client.
This coroutine allows sending trailers-only responses, in case of some
failure conditions during handling current request, i.e. when
``status is not OK``.
.. note:: This coroutine will be called implicitly at exit from
... | send_trailing_metadata | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def cancel(self) -> None:
"""Coroutine to cancel this request/stream.
Server will send RST_STREAM frame to the client, so it will be
explicitly informed that there is nothing to expect from the server
regarding this request/stream.
"""
if self._cancel_done:
... | Coroutine to cancel this request/stream.
Server will send RST_STREAM frame to the client, so it will be
explicitly informed that there is nothing to expect from the server
regarding this request/stream.
| cancel | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
def close(self) -> None:
"""Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly.
"""
if self._server is None or self._server_closed_fut is None:
raise RuntimeError('Server is n... | Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly.
| close | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def wait_closed(self) -> None:
"""Coroutine to wait until all existing request handlers will exit
properly.
"""
if self._server is None or self._server_closed_fut is None:
raise RuntimeError('Server is not started')
await self._server_closed_fut
await se... | Coroutine to wait until all existing request handlers will exit
properly.
| wait_closed | python | vmagamedov/grpclib | grpclib/server.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/server.py | BSD-3-Clause |
async def __aenter__(self) -> Channel:
"""
:return: :py:class:`~grpclib.client.Channel`
"""
self._server = Server(
self._services,
codec=self._codec,
status_details_codec=self._status_details_codec,
)
self._server._server = _Server()
... |
:return: :py:class:`~grpclib.client.Channel`
| __aenter__ | python | vmagamedov/grpclib | grpclib/testing.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/testing.py | BSD-3-Clause |
def graceful_exit(
servers: Collection['IClosable'],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
signals: Collection[int] = (signal.SIGINT, signal.SIGTERM),
) -> Iterator[None]:
"""Utility context-manager to help properly shutdown server in response to
the OS signals
By default thi... | Utility context-manager to help properly shutdown server in response to
the OS signals
By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals.
There are two stages:
1. first received signal closes servers
2. subsequent signals raise ``SystemExit`` exception
Example:
... | graceful_exit | python | vmagamedov/grpclib | grpclib/utils.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/utils.py | BSD-3-Clause |
def __init__(
self,
func: Callable[[], Awaitable[_Status]],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
check_ttl: float = DEFAULT_CHECK_TTL,
check_timeout: float = DEFAULT_CHECK_TIMEOUT,
) -> None:
"""
:param func: callable object which retur... |
:param func: callable object which returns awaitable object, where
result is one of: ``True`` (healthy), ``False`` (unhealthy), or
``None`` (unknown)
:param loop: (deprecated) asyncio-compatible event loop
:param check_ttl: how long we can cache result of the previous ch... | __init__ | python | vmagamedov/grpclib | grpclib/health/check.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/health/check.py | BSD-3-Clause |
def __init__(
self,
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
"""
:param loop: (deprecated) asyncio-compatible event loop
"""
if loop:
warnings.warn("The loop argument is deprecated and scheduled "
"f... |
:param loop: (deprecated) asyncio-compatible event loop
| __init__ | python | vmagamedov/grpclib | grpclib/health/check.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/health/check.py | BSD-3-Clause |
def set(self, value: _Status) -> None:
"""Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
"""
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all wat... | Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
| set | python | vmagamedov/grpclib | grpclib/health/check.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/health/check.py | BSD-3-Clause |
def extend(cls, services: 'Collection[IServable]') -> 'List[IServable]':
"""
Extends services list with reflection service:
.. code-block:: python3
from grpclib.reflection.service import ServerReflection
services = [Greeter()]
services = ServerReflection.ex... |
Extends services list with reflection service:
.. code-block:: python3
from grpclib.reflection.service import ServerReflection
services = [Greeter()]
services = ServerReflection.extend(services)
server = Server(services)
...
Retur... | extend | python | vmagamedov/grpclib | grpclib/reflection/service.py | https://github.com/vmagamedov/grpclib/blob/master/grpclib/reflection/service.py | BSD-3-Clause |
async def test_goaway_twice(config):
"""
We should be able to receive frames after connection close with GOAWAY frame
"""
client_h2c, server_h2c = create_connections()
to_client_transport = TransportStub(client_h2c)
server_conn = Connection(server_h2c, to_client_transport, config=config)
t... |
We should be able to receive frames after connection close with GOAWAY frame
| test_goaway_twice | python | vmagamedov/grpclib | tests/test_protocol.py | https://github.com/vmagamedov/grpclib/blob/master/tests/test_protocol.py | BSD-3-Clause |
def llm_correctness(
model: str,
additional_sampling_params: Optional[Dict[str, Any]] = None,
num_concurrent_requests: int = 1,
max_num_completed_requests: int = 500,
test_timeout_s=90,
llm_api="chat",
) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
"""Get the token throughput and latencie... | Get the token throughput and latencies for the given model.
Args:
model: The name of the model to query.
additional_sampling_params: Additional sampling parameters to send with the request.
For more information see the LLM APIs documentation for the completions
num_concurrent_re... | llm_correctness | python | ray-project/llmperf | llm_correctness.py | https://github.com/ray-project/llmperf/blob/master/llm_correctness.py | Apache-2.0 |
def run(
llm_api: str,
model: str,
test_timeout_s: int,
max_num_completed_requests: int,
num_concurrent_requests: int,
additional_sampling_params: str,
results_dir: str,
user_metadata: Dict[str, str],
):
"""
Args:
llm_api: The type of request to make. Either "chat" or "li... |
Args:
llm_api: The type of request to make. Either "chat" or "litellm".
model: The name of the model to query.
max_num_completed_requests: The number of requests to complete before finishing the test.
test_timeout_s: The amount of time to run the test for before reporting results.
... | run | python | ray-project/llmperf | llm_correctness.py | https://github.com/ray-project/llmperf/blob/master/llm_correctness.py | Apache-2.0 |
def get_token_throughput_latencies(
model: str,
mean_input_tokens: int,
stddev_input_tokens: int,
mean_output_tokens: int,
stddev_output_tokens: int,
additional_sampling_params: Optional[Dict[str, Any]] = None,
num_concurrent_requests: int = 1,
max_num_completed_requests: int = 500,
... | Get the token throughput and latencies for the given model.
Args:
model: The name of the model to query.
mean_input_tokens: The mean number of tokens to send in the prompt for the request.
stddev_input_tokens: The standard deviation of the number of tokens to send in the prompt for the requ... | get_token_throughput_latencies | python | ray-project/llmperf | token_benchmark_ray.py | https://github.com/ray-project/llmperf/blob/master/token_benchmark_ray.py | Apache-2.0 |
def metrics_summary(
metrics: List[Dict[str, Any]], start_time: int, end_time: int
) -> Dict[str, Any]:
"""Generate a summary over metrics generated from potentially multiple instances of this client.
Args:
metrics: The metrics to summarize.
start_time: The time the test started.
en... | Generate a summary over metrics generated from potentially multiple instances of this client.
Args:
metrics: The metrics to summarize.
start_time: The time the test started.
end_time: The time the test ended.
Returns:
A summary with the following information:
- Over... | metrics_summary | python | ray-project/llmperf | token_benchmark_ray.py | https://github.com/ray-project/llmperf/blob/master/token_benchmark_ray.py | Apache-2.0 |
def run_token_benchmark(
llm_api: str,
model: str,
test_timeout_s: int,
max_num_completed_requests: int,
num_concurrent_requests: int,
mean_input_tokens: int,
stddev_input_tokens: int,
mean_output_tokens: int,
stddev_output_tokens: int,
additional_sampling_params: str,
result... |
Args:
llm_api: The name of the llm api to use.
model: The name of the model to query.
max_num_completed_requests: The number of requests to complete before finishing the test.
test_timeout_s: The amount of time to run the test for before reporting results.
num_concurrent_req... | run_token_benchmark | python | ray-project/llmperf | token_benchmark_ray.py | https://github.com/ray-project/llmperf/blob/master/token_benchmark_ray.py | Apache-2.0 |
def construct_clients(llm_api: str, num_clients: int) -> List[LLMClient]:
"""Construct LLMClients that will be used to make requests to the LLM API.
Args:
llm_api: The name of the LLM API to use.
num_clients: The number of concurrent requests to make.
Returns:
The constructed LLMCL... | Construct LLMClients that will be used to make requests to the LLM API.
Args:
llm_api: The name of the LLM API to use.
num_clients: The number of concurrent requests to make.
Returns:
The constructed LLMCLients
| construct_clients | python | ray-project/llmperf | src/llmperf/common.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/common.py | Apache-2.0 |
def llm_request(
self, request_config: RequestConfig
) -> Tuple[Dict[str, Any], str, RequestConfig]:
"""Make a single completion request to a LLM API
Returns:
Metrics about the performance charateristics of the request.
The text generated by the request to the LLM AP... | Make a single completion request to a LLM API
Returns:
Metrics about the performance charateristics of the request.
The text generated by the request to the LLM API.
The request_config used to make the request. This is mainly for logging purposes.
| llm_request | python | ray-project/llmperf | src/llmperf/ray_llm_client.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/ray_llm_client.py | Apache-2.0 |
def launch_requests(self, request_config: RequestConfig) -> None:
"""Launch requests to the LLM API.
Args:
request_config: The configuration for the request.
"""
if self._llm_client_pool.has_free():
self._llm_client_pool.submit(
lambda client, _r... | Launch requests to the LLM API.
Args:
request_config: The configuration for the request.
| launch_requests | python | ray-project/llmperf | src/llmperf/requests_launcher.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/requests_launcher.py | Apache-2.0 |
def get_next_ready(self, block: bool = False) -> List[Any]:
"""Return results that are ready from completed requests.
Args:
block: Whether to block until a result is ready.
Returns:
A list of results that are ready.
"""
results = []
if not block... | Return results that are ready from completed requests.
Args:
block: Whether to block until a result is ready.
Returns:
A list of results that are ready.
| get_next_ready | python | ray-project/llmperf | src/llmperf/requests_launcher.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/requests_launcher.py | Apache-2.0 |
def upload_to_s3(results_path: str, s3_path: str) -> None:
"""Upload the results to s3.
Args:
results_path: The path to the results file.
s3_path: The s3 path to upload the results to.
"""
command = ["aws", "s3", "sync", results_path, f"{s3_path}/"]
result = subprocess.run(command... | Upload the results to s3.
Args:
results_path: The path to the results file.
s3_path: The s3 path to upload the results to.
| upload_to_s3 | python | ray-project/llmperf | src/llmperf/utils.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/utils.py | Apache-2.0 |
def randomly_sample_sonnet_lines_prompt(
prompt_tokens_mean: int = 550,
prompt_tokens_stddev: int = 250,
expect_output_tokens: int = 150,
tokenizer = LlamaTokenizerFast.from_pretrained(
"hf-internal-testing/llama-tokenizer")
) -> Tuple[str, int]:
"""Generate a prompt that randomly samples li... | Generate a prompt that randomly samples lines from a the shakespeare sonnet at sonnet.txt.
Args:
prompt_length_mean: The mean length of the prompt to generate.
prompt_len_stddev: The standard deviation of the length of the prompt to generate.
expect_output_tokens: The number of tokens to ex... | randomly_sample_sonnet_lines_prompt | python | ray-project/llmperf | src/llmperf/utils.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/utils.py | Apache-2.0 |
def sample_random_positive_int(mean: int, stddev: int) -> int:
"""Sample random numbers from a gaussian distribution until a positive number is sampled.
Args:
mean: The mean of the gaussian distribution to sample from.
stddev: The standard deviation of the gaussian distribution to sample from.
... | Sample random numbers from a gaussian distribution until a positive number is sampled.
Args:
mean: The mean of the gaussian distribution to sample from.
stddev: The standard deviation of the gaussian distribution to sample from.
Returns:
A random positive integer sampled from the gauss... | sample_random_positive_int | python | ray-project/llmperf | src/llmperf/utils.py | https://github.com/ray-project/llmperf/blob/master/src/llmperf/utils.py | Apache-2.0 |
def __init__(self, data, bsz, bptt, device='cpu', ext_len=None):
"""
data -- LongTensor -- the LongTensor is strictly ordered
"""
self.bsz = bsz
self.bptt = bptt
self.ext_len = ext_len if ext_len is not None else 0
self.device = device
# Work out how... |
data -- LongTensor -- the LongTensor is strictly ordered
| __init__ | python | kimiyoung/transformer-xl | pytorch/data_utils.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/data_utils.py | Apache-2.0 |
def __init__(self, data, bsz, bptt, device='cpu', ext_len=None, shuffle=False):
"""
data -- list[LongTensor] -- there is no order among the LongTensors
"""
self.data = data
self.bsz = bsz
self.bptt = bptt
self.ext_len = ext_len if ext_len is not None else 0
... |
data -- list[LongTensor] -- there is no order among the LongTensors
| __init__ | python | kimiyoung/transformer-xl | pytorch/data_utils.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/data_utils.py | Apache-2.0 |
def scatter(inputs, target_gpus, chunk_sizes, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given GPUs. Duplicates
references to objects that are not tensors.
"""
def scatter_map(obj):
if isinstance(obj, torch.Tensor):
try:
... |
Slices tensors into approximately equal chunks and
distributes them across given GPUs. Duplicates
references to objects that are not tensors.
| scatter | python | kimiyoung/transformer-xl | pytorch/utils/data_parallel.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/data_parallel.py | Apache-2.0 |
def scatter_kwargs(inputs, kwargs, target_gpus, chunk_sizes, dim=0):
r"""Scatter with support for kwargs dictionary"""
inputs = scatter(inputs, target_gpus, chunk_sizes, dim) if inputs else []
kwargs = scatter(kwargs, target_gpus, chunk_sizes, dim) if kwargs else []
if len(inputs) < len(kwargs):
... | Scatter with support for kwargs dictionary | scatter_kwargs | python | kimiyoung/transformer-xl | pytorch/utils/data_parallel.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/data_parallel.py | Apache-2.0 |
def __init__(self, range_max, n_sample):
"""
Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py
`P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)`
expected count can be approximated by 1 - (1 - p)^n
... |
Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py
`P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)`
expected count can be approximated by 1 - (1 - p)^n
and we use a numerically stable version -expm1(num... | __init__ | python | kimiyoung/transformer-xl | pytorch/utils/log_uniform_sampler.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/log_uniform_sampler.py | Apache-2.0 |
def sample_logits(embedding, bias, labels, inputs, sampler):
"""
embedding: an nn.Embedding layer
bias: [n_vocab]
labels: [b1, b2]
inputs: [b1, b2, n_emb]
sampler: you may use a LogUniformSampler
Return
logits: [b1, b2, 1 + n_sample]
"""
true_log_probs, sa... |
embedding: an nn.Embedding layer
bias: [n_vocab]
labels: [b1, b2]
inputs: [b1, b2, n_emb]
sampler: you may use a LogUniformSampler
Return
logits: [b1, b2, 1 + n_sample]
| sample_logits | python | kimiyoung/transformer-xl | pytorch/utils/log_uniform_sampler.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/log_uniform_sampler.py | Apache-2.0 |
def forward(self, hidden, target, keep_order=False):
'''
hidden :: [len*bsz x d_proj]
target :: [len*bsz]
'''
if hidden.size(0) != target.size(0):
raise RuntimeError('Input and target should have the same size '
'in the batch di... |
hidden :: [len*bsz x d_proj]
target :: [len*bsz]
| forward | python | kimiyoung/transformer-xl | pytorch/utils/proj_adaptive_softmax.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/proj_adaptive_softmax.py | Apache-2.0 |
def count_sents(self, sents, verbose=False):
"""
sents : a list of sentences, each a list of tokenized symbols
"""
if verbose: print('counting {} sents ...'.format(len(sents)))
for idx, symbols in enumerate(sents):
if verbose and idx > 0 and idx % 500000 == 0:
... |
sents : a list of sentences, each a list of tokenized symbols
| count_sents | python | kimiyoung/transformer-xl | pytorch/utils/vocabulary.py | https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/vocabulary.py | Apache-2.0 |
def get_bin_sizes(data, batch_size, tgt_len, cutoffs, std_mult=[2.5, 2.5, 2.5]):
"""
Note: the `batch_size` here should be per-core batch size
"""
bin_sizes = []
def _nearest_to_eight(x): # so that it's faster on TPUs
y = x - x % 8
return y + 8 if x % 8 >= 4 else max(8, y)
if cutoffs:
num_ba... |
Note: the `batch_size` here should be per-core batch size
| get_bin_sizes | python | kimiyoung/transformer-xl | tf/data_utils.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/data_utils.py | Apache-2.0 |
def batchify(data, batch_size, num_passes):
"""
if use_tpu = True: num_passes > 1
Since TPU training requires entire [bsz x tgt_len] chunks, it can discard
as many as `bsz * tgt_len` tokens in training. When `bsz` and `tgt_len` are
both large, as in the case of TPU training for Transformer-XL, ... |
if use_tpu = True: num_passes > 1
Since TPU training requires entire [bsz x tgt_len] chunks, it can discard
as many as `bsz * tgt_len` tokens in training. When `bsz` and `tgt_len` are
both large, as in the case of TPU training for Transformer-XL, the problem
may lead to detectable performanc... | batchify | python | kimiyoung/transformer-xl | tf/data_utils.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/data_utils.py | Apache-2.0 |
def mul_adaptive_embedding_lookup(x, n_token, d_embed, d_proj, cutoffs, initializer,
proj_initializer, div_val=1, perms=None,
proj_same_dim=True,
scope='adaptive_embed'):
"""
perms: If None, first compute W = W1 x ... |
perms: If None, first compute W = W1 x W2 (projection for each bin),
and then compute X x W (embedding lookup). If not None,
use bin-based embedding lookup with max_bin_size defined by
the shape of perms.
| mul_adaptive_embedding_lookup | python | kimiyoung/transformer-xl | tf/model.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/model.py | Apache-2.0 |
def transformer(dec_inp, target, mems, n_token, n_layer, d_model, d_embed,
n_head, d_head, d_inner, dropout, dropatt,
initializer, is_training, proj_initializer=None,
mem_len=None, cutoffs=[], div_val=1, tie_projs=[],
same_length=False, clamp_len=-1, use_t... |
cutoffs: a list of python int. Cutoffs for adaptive softmax.
tie_projs: a list of python bools. Whether to tie the projections.
use_tpu: if True, use one_hot in embedding lookup and bin-based implementation
of adaptive softmax.
perms: a list of tensors. Each tensor should of size [len, bsz, bin_size].
... | transformer | python | kimiyoung/transformer-xl | tf/model.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/model.py | Apache-2.0 |
def _create_or_get_iterations_per_loop():
"""Creates or gets the iterations_per_loop variable.
In TPUEstimator, the user provided computation, the model_fn, is wrapped
inside a tf.while_loop for peak performance. The iterations of the loop are
specified by this variable, which adjusts its value on the CPU afte... | Creates or gets the iterations_per_loop variable.
In TPUEstimator, the user provided computation, the model_fn, is wrapped
inside a tf.while_loop for peak performance. The iterations of the loop are
specified by this variable, which adjusts its value on the CPU after each TPU
program execution and before the n... | _create_or_get_iterations_per_loop | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _increase_eval_step_op(iterations_per_loop):
"""Returns an op to increase the eval step for TPU evaluation.
Args:
iterations_per_loop: Tensor. The number of eval steps running in TPU
system before returning to CPU host for each `Session.run`.
Returns:
An operation
"""
eval_step = evaluat... | Returns an op to increase the eval step for TPU evaluation.
Args:
iterations_per_loop: Tensor. The number of eval steps running in TPU
system before returning to CPU host for each `Session.run`.
Returns:
An operation
| _increase_eval_step_op | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def as_estimator_spec(self):
"""Creates an equivalent `EstimatorSpec` used by CPU train/eval."""
host_calls = {}
if self.eval_metrics is not None:
host_calls['eval_metrics'] = self.eval_metrics
if self.host_call is not None:
host_calls['host_call'] = self.host_call
host_call_ret = _Outfe... | Creates an equivalent `EstimatorSpec` used by CPU train/eval. | as_estimator_spec | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def __init__(self, iterations, num_steps=None, last_step=None):
"""Initializes a `StopAtStepHook`.
Args:
iterations: The number of iterations to run optimizer per training loop.
num_steps: Number of steps to execute.
last_step: Step after which to stop.
Raises:
ValueError: If one o... | Initializes a `StopAtStepHook`.
Args:
iterations: The number of iterations to run optimizer per training loop.
num_steps: Number of steps to execute.
last_step: Step after which to stop.
Raises:
ValueError: If one of the arguments is invalid.
| __init__ | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def generate_per_core_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, host_device, host_id):
"""Generates infeed enqueue ops for per-core input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id)
def enqueue_ops_... | Generates infeed enqueue ops for per-core input_fn on a single host. | generate_per_core_enqueue_ops_fn_for_host | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def generate_per_host_enqueue_ops_fn_for_host(
ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id):
"""Generates infeed enqueue ops for per-host input_fn on a single host."""
captured_infeed_queue = _CapturedObject()
hooks = []
with ops.device(device):
user_context = tpu_context.TPU... | Generates infeed enqueue ops for per-host input_fn on a single host. | generate_per_host_enqueue_ops_fn_for_host | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def enqueue_ops_fn():
"""A Fn returning the TPU infeed enqueue ops.
By providing as a Fn, it can be invoked inside the tf.while_loop such that
the input pipeline for multiple iterations can be executed by one
Session.run call.
Returns:
list of dict of ops.
"""
with ops.device(device)... | A Fn returning the TPU infeed enqueue ops.
By providing as a Fn, it can be invoked inside the tf.while_loop such that
the input pipeline for multiple iterations can be executed by one
Session.run call.
Returns:
list of dict of ops.
| enqueue_ops_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder,
num_hosts):
"""Generates infeed enqueue ops for one input_fn on all the hosts."""
captured_infeed_queue = _CapturedObject()
hooks = []
device_0 = ctx.tpu_host_placement_function(host_id=0)
wit... | Generates infeed enqueue ops for one input_fn on all the hosts. | generate_broadcast_enqueue_ops_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def enqueue_ops_fn():
"""Generates enqueue ops for all the hosts."""
broadcasted_inputs = []
flattened_inputs = None # Cache result from input_fn.
signals = None
for host_id in xrange(num_hosts):
with ops.device(ctx.tpu_host_placement_function(host_id=host_id)):
for _ in xrange(ctx.nu... | Generates enqueue ops for all the hosts. | enqueue_ops_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _flatten_input_dims(self, feature_dims, feature_dims_names, label_dims,
label_dims_names, label_names, has_labels):
"""Flatten input dims with the same order as flattened input tensors."""
flattened_input_dims = []
if feature_dims_names:
# We need a fixed orderi... | Flatten input dims with the same order as flattened input tensors. | _flatten_input_dims | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def validate_and_record_structure(self, features, labels):
"""Validates and records the structure of `features` and `labels`."""
# Extract structure.
has_labels = labels is not None
feature_names = _extract_key_names(features)
label_names = _extract_key_names(labels)
if not self._in... | Validates and records the structure of `features` and `labels`. | validate_and_record_structure | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def flatten_features_and_labels(self, features, labels, signals=None):
"""Flattens the `features` and `labels` to a single tensor list."""
self._feature_structure['features'] = features
if labels is not None:
self._feature_structure['labels'] = labels
if signals is not None:
self... | Flattens the `features` and `labels` to a single tensor list. | flatten_features_and_labels | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def unflatten_features_and_labels(self, flattened_inputs):
"""Restores the flattened inputs to original features and labels form.
Args:
flattened_inputs: Flattened inputs for each shard.
Returns:
A tuple of (`features`, `labels`), where `labels` could be None.
Each one, if pr... | Restores the flattened inputs to original features and labels form.
Args:
flattened_inputs: Flattened inputs for each shard.
Returns:
A tuple of (`features`, `labels`), where `labels` could be None.
Each one, if present, should have identical structure (single tensor vs
dic... | unflatten_features_and_labels | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def __init__(self, input_fn, batch_axis, ctx):
"""Constructor.
Args:
input_fn: input fn for train or eval.
batch_axis: A python tuple of int values describing how each tensor
produced by the Estimator `input_fn` should be split across the TPU
compute shards.
ctx: A `_InternalT... | Constructor.
Args:
input_fn: input fn for train or eval.
batch_axis: A python tuple of int values describing how each tensor
produced by the Estimator `input_fn` should be split across the TPU
compute shards.
ctx: A `_InternalTPUContext` instance with mode.
Raises:
Valu... | __init__ | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def dequeue_fn():
"""dequeue_fn is used by TPU to retrieve the tensors."""
# In the model-parallel case, both the host-side and device-side
# computations must agree on the core on which infeed takes place. We
# choose to perform infeed on logical core 0 of each replica.
values = self._inf... | dequeue_fn is used by TPU to retrieve the tensors. | dequeue_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _invoke_input_fn_and_record_structure(self):
"""Deploys the input pipeline and record input structure."""
enqueue_ops = []
infeed_queues = []
all_hooks = []
num_hosts = self._ctx.num_hosts
tpu_host_placement_fn = self._ctx.tpu_host_placement_function
run_infeed_loop_on_coordinator = Tru... | Deploys the input pipeline and record input structure. | _invoke_input_fn_and_record_structure | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _validate_input_pipeline(self):
"""Validates the input pipeline.
Perform some sanity checks to log user friendly information. We should
error out to give users better error message. But, if
_WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break
user code, so, log a warning.
... | Validates the input pipeline.
Perform some sanity checks to log user friendly information. We should
error out to give users better error message. But, if
_WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break
user code, so, log a warning.
Raises:
RuntimeError: If the val... | _validate_input_pipeline | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def convert_to_single_tpu_train_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single train step on TPU.
The user provided `model_fn` takes input tuple
(features, labels) and produces the EstimatorSpec with train_op and loss for
train `mode`. This usually represents a single train com... | Converts user provided model_fn` as a single train step on TPU.
The user provided `model_fn` takes input tuple
(features, labels) and produces the EstimatorSpec with train_op and loss for
train `mode`. This usually represents a single train computation on CPU.
For TPU training, a train (computation) s... | convert_to_single_tpu_train_step | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def train_step(loss, *cache):
"""Training step function for use inside a while loop."""
if not self._params.get('track_mean', False):
del loss # unused; required in function signature.
inputs = dequeue_fn()
features, labels = inputs.features_and_labels()
# Consume the current ca... | Training step function for use inside a while loop. | train_step | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def convert_to_single_tpu_eval_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single eval step on TPU.
Similar to training, the user provided `model_fn` takes input tuple
(features, labels) and produces the TPUEstimatorSpec with eval_metrics for
eval `mode`. This usually represents a ... | Converts user provided model_fn` as a single eval step on TPU.
Similar to training, the user provided `model_fn` takes input tuple
(features, labels) and produces the TPUEstimatorSpec with eval_metrics for
eval `mode`. This usually represents a single evaluation computation on CPU.
For TPU evaluation,... | convert_to_single_tpu_eval_step | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def eval_step(total_loss, *cache):
"""Evaluation step function for use inside a while loop."""
inputs = dequeue_fn()
features, labels = inputs.features_and_labels()
# Consume the current cache
tpu_estimator_spec = self._call_model_fn(features, labels, cache=cache)
if not isinstance(... | Evaluation step function for use inside a while loop. | eval_step | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def convert_to_single_tpu_predict_step(self, dequeue_fn):
"""Converts user provided model_fn` as a single predict step on TPU.
Args:
dequeue_fn: The function to retrieve inputs, features and labels, from TPU
infeed dequeue channel.
Returns:
A tuple of predict_fn, host_calls, and captur... | Converts user provided model_fn` as a single predict step on TPU.
Args:
dequeue_fn: The function to retrieve inputs, features and labels, from TPU
infeed dequeue channel.
Returns:
A tuple of predict_fn, host_calls, and captured scaffold_fn. The
predict_fn representing the predict ste... | convert_to_single_tpu_predict_step | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _validate_model_features_and_labels(self,
features,
labels,
is_export_mode):
"""Validates that the features and labels for the model function are valid.
A valid features/labels obje... | Validates that the features and labels for the model function are valid.
A valid features/labels object is the one with:
- Type: Tensor or a dictionary of Tensors
- Static shape if is_export_mode is False.
Args:
features: the features that would be input to the model function.
labels: the ... | _validate_model_features_and_labels | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def create_cpu_hostcall(host_calls):
"""Runs on the host_call on CPU instead of TPU when use_tpu=False."""
_OutfeedHostCall.validate(host_calls)
ret = {}
for name, host_call in host_calls.items():
host_fn, tensors = host_call
if isinstance(tensors, (tuple, list)):
ret[name] = host_f... | Runs on the host_call on CPU instead of TPU when use_tpu=False. | create_cpu_hostcall | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def create_enqueue_op(self):
"""Create the op to enqueue the recorded host_calls.
Returns:
A list of enqueue ops, which is empty if there are no host calls.
"""
if not self._names:
return []
tensors = []
# TODO(jhseu): Consider deduping tensors.
for name in self._names:
t... | Create the op to enqueue the recorded host_calls.
Returns:
A list of enqueue ops, which is empty if there are no host calls.
| create_enqueue_op | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def create_tpu_hostcall(self):
"""Sends the tensors through outfeed and runs the host_fn on CPU.
The tensors are concatenated along dimension 0 to form a global tensor
across all shards. The concatenated function is passed to the host_fn and
executed on the first host.
Returns:
A dictionary ... | Sends the tensors through outfeed and runs the host_fn on CPU.
The tensors are concatenated along dimension 0 to form a global tensor
across all shards. The concatenated function is passed to the host_fn and
executed on the first host.
Returns:
A dictionary mapping name to the return type of the... | create_tpu_hostcall | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def __init__(self,
model_fn=None,
train_cache_fn=None,
eval_cache_fn=None,
model_dir=None,
config=None,
params=None,
use_tpu=True,
train_batch_size=None,
eval_batch_size=None,
... | Constructs an `TPUEstimator` instance.
Args:
model_fn: Model function as required by `Estimator` which returns
EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation_hooks',
and `prediction_hooks` must not capure any TPU Tensor inside the model_fn.
model_dir: Directory to save mod... | __init__ | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def computation():
"""Compute tpu tensors used in export_outputs.
Passed to rewrite_for_inference so that model_fn will be called under
the rewriting contexts. Only tpu tensors are returned, but export_outputs
and scaffold are captured.
Returns:
A list of Tensors used in export_... | Compute tpu tensors used in export_outputs.
Passed to rewrite_for_inference so that model_fn will be called under
the rewriting contexts. Only tpu tensors are returned, but export_outputs
and scaffold are captured.
Returns:
A list of Tensors used in export_outputs and not marked for
... | computation | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _call_input_fn(self, input_fn, mode):
"""Calls the input function.
Args:
input_fn: The input function.
mode: ModeKeys
Returns:
Either features or (features, labels) where features and labels are:
features - `Tensor` or dictionary of string feature name to `Tensor`.
la... | Calls the input function.
Args:
input_fn: The input function.
mode: ModeKeys
Returns:
Either features or (features, labels) where features and labels are:
features - `Tensor` or dictionary of string feature name to `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with la... | _call_input_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _augment_model_fn(self, model_fn, train_cache_fn, eval_cache_fn, batch_axis):
"""Returns a new model_fn, which wraps the TPU support."""
def _model_fn(features, labels, mode, config, params):
"""A Estimator `model_fn` for TPUEstimator."""
with self._ctx.with_mode(mode) as ctx:
model_fn_... | Returns a new model_fn, which wraps the TPU support. | _augment_model_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _export_output_to_tensors(export_output):
"""Get a list of `Tensors` used in `export_output`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
Returns:
a list of tensors used in export_output.
Raises:
ValueError: ... | Get a list of `Tensors` used in `export_output`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
Returns:
a list of tensors used in export_output.
Raises:
ValueError: if `export_output` is not one of `ClassificationOut... | _export_output_to_tensors | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _clone_export_output_with_tensors(export_output, tensors):
"""Clones `export_output` but with new `tensors`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
tensors: a list of `Tensors` used to construct a new `export_out... | Clones `export_output` but with new `tensors`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
tensors: a list of `Tensors` used to construct a new `export_output`.
Returns:
A dict similar to `export_output` but with `te... | _clone_export_output_with_tensors | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
iterations_per_loop_var = _create_or_get_iterations_per_loop()
(single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks
) = model_fn_wrapper.convert_to_single_tpu_... | Executes `model_fn_wrapper` multiple times on all TPU shards. | _eval_on_tpu_system | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _wrap_computation_in_while_loop(device, op_fn):
"""Wraps the ops generated by `op_fn` in tf.while_loop."""
def computation(i):
with ops.control_dependencies(op_fn()):
return i + 1
iterations_per_loop_var = _create_or_get_iterations_per_loop()
# By setting parallel_iterations=1, the parallel exec... | Wraps the ops generated by `op_fn` in tf.while_loop. | _wrap_computation_in_while_loop | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _validate_tpu_training_graph():
"""Validate graph before running distributed training.
Raises:
ValueError: If the graph seems invalid for running on device
"""
operations = ops.get_default_graph().get_operations()
# Check if there is atleast one CrossReplicaSum operation in the graph
# This should... | Validate graph before running distributed training.
Raises:
ValueError: If the graph seems invalid for running on device
| _validate_tpu_training_graph | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def from_input_fn(return_values):
"""Returns an `_Inputs` instance according to `input_fn` return value."""
if isinstance(return_values, dataset_ops.Dataset):
dataset = return_values
return _Inputs(dataset=dataset)
features, labels = _Inputs._parse_inputs(return_values)
return _Inputs(featu... | Returns an `_Inputs` instance according to `input_fn` return value. | from_input_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def dataset_initializer_hook(self):
"""Returns a `SessionRunHook` to initialize this dataset.
This must be called before `features_and_labels`.
"""
iterator = self._dataset.make_initializable_iterator()
# pylint: disable=protected-access
hook = estimator_util._DatasetInitializerHook(iterator)
... | Returns a `SessionRunHook` to initialize this dataset.
This must be called before `features_and_labels`.
| dataset_initializer_hook | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def insert_stopping_signal(stop, batch_size, add_padding=False):
"""Inserts stopping_signal into dataset via _map_fn.
Here we change the data structure in the dataset, such that the return value
is a dictionary now and `features`, `labels`, and `signals` are three
distinguished keys in that dict. This ... | Inserts stopping_signal into dataset via _map_fn.
Here we change the data structure in the dataset, such that the return value
is a dictionary now and `features`, `labels`, and `signals` are three
distinguished keys in that dict. This provides a better structure, which
eases the process to decompose th... | insert_stopping_signal | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def _map_fn(*args):
"""The map fn to insert signals."""
if len(args) == 1:
# Unpack the single Tensor/dict argument as features. This is required
# for the input_fn returns no labels.
args = args[0]
features, labels = _Inputs._parse_inputs(args)
new_input_dict = {}
... | The map fn to insert signals. | _map_fn | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def as_dict(self):
"""Returns the signals as Python dict."""
shape = [self._batch_size, 1]
dtype = dtypes.bool
if self._stop:
stopping = array_ops.ones(shape=shape, dtype=dtype)
else:
stopping = array_ops.zeros(shape=shape, dtype=dtype)
signals = {'stopping': stopping}
if self.... | Returns the signals as Python dict. | as_dict | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def pad_features_and_labels(features, labels, batch_size):
"""Pads out the batch dimension of features and labels."""
real_batch_size = array_ops.shape(
_PaddingSignals._find_any_tensor(features))[0]
batch_size_tensor = constant_op.constant(batch_size, dtypes.int32)
check_greater = check_ops.a... | Pads out the batch dimension of features and labels. | pad_features_and_labels | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def pad_single_tensor(tensor):
"""Pads out the batch dimension of a tensor to the complete batch_size."""
rank = len(tensor.shape)
assert rank > 0
padding = array_ops.stack([[0, missing_count]] + [[0, 0]] * (rank - 1))
padded_shape = (batch_size,) + tuple(tensor.shape[1:])
padded_ten... | Pads out the batch dimension of a tensor to the complete batch_size. | pad_single_tensor | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def slice_tensor_or_dict(tensor_or_dict, signals):
"""Slice the real Tensors according to padding mask in signals."""
padding_mask = signals['padding_mask']
batch_size = array_ops.shape(padding_mask)[0]
def verify_batch_size(tensor):
check_batch_size = math_ops.equal(batch_size, tensor.shape[0])... | Slice the real Tensors according to padding mask in signals. | slice_tensor_or_dict | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def export_estimator_savedmodel(estimator,
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
... | Export `Estimator` trained model for TPU inference.
Args:
estimator: `Estimator` with which model has been trained.
export_dir_base: A string containing a directory in which to create
timestamped subdirectories containing exported SavedModels.
serving_input_receiver_fn: A function that takes no arg... | export_estimator_savedmodel | python | kimiyoung/transformer-xl | tf/tpu_estimator.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/tpu_estimator.py | Apache-2.0 |
def metric_fn(loss):
"""Evaluation metric Fn which runs on CPU."""
perplexity = tf.exp(tf.reduce_mean(loss))
bpc = tf.reduce_mean(loss) / tf.constant(math.log(2))
return {
"perplexity": tf.metrics.mean(perplexity),
"bpc": tf.metrics.mean(bpc),
} | Evaluation metric Fn which runs on CPU. | metric_fn | python | kimiyoung/transformer-xl | tf/train.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/train.py | Apache-2.0 |
def count_sents(self, sents, verbose=False):
"""
sents : a list of sentences, each a list of tokenized symbols
"""
if verbose: print('counting {} sents ...'.format(len(sents)))
for idx, symbols in enumerate(sents):
if verbose and idx > 0 and idx % 500000 == 0:
print(' line {}'.forma... |
sents : a list of sentences, each a list of tokenized symbols
| count_sents | python | kimiyoung/transformer-xl | tf/vocabulary.py | https://github.com/kimiyoung/transformer-xl/blob/master/tf/vocabulary.py | Apache-2.0 |
def resize(self, maxwidth=1000, maxheight=1000):
"""
Will resize the image proportionately based on maxwidth and maxheight.
NOTE: This may effect the result of the detection algorithm.
Return value is 0 if no change was made, 1 if the image was changed
based on width, 2 if the i... |
Will resize the image proportionately based on maxwidth and maxheight.
NOTE: This may effect the result of the detection algorithm.
Return value is 0 if no change was made, 1 if the image was changed
based on width, 2 if the image was changed based on height, 3 if it
was change... | resize | python | hhatto/nude.py | nude.py | https://github.com/hhatto/nude.py/blob/master/nude.py | MIT |
def __call__(self, r):
"""Add OAuth parameters to the request.
Parameters may be included from the body if the content-type is
urlencoded, if no content type is set a guess is made.
"""
# Overwriting url is safe here as request will not modify it past
# this point.
... | Add OAuth parameters to the request.
Parameters may be included from the body if the content-type is
urlencoded, if no content type is set a guess is made.
| __call__ | python | requests/requests-oauthlib | requests_oauthlib/oauth1_auth.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_auth.py | ISC |
def urldecode(body):
"""Parse query or json to python dictionary"""
try:
return _urldecode(body)
except Exception:
import json
return json.loads(body) | Parse query or json to python dictionary | urldecode | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def __init__(
self,
client_key,
client_secret=None,
resource_owner_key=None,
resource_owner_secret=None,
callback_uri=None,
signature_method=SIGNATURE_HMAC,
signature_type=SIGNATURE_TYPE_AUTH_HEADER,
rsa_key=None,
verifier=None,
cli... | Construct the OAuth 1 session.
:param client_key: A client specific identifier.
:param client_secret: A client specific secret used to create HMAC and
plaintext signatures.
:param resource_owner_key: A resource owner key, also referred to as
... | __init__ | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def authorized(self):
"""Boolean that indicates whether this session has an OAuth token
or not. If `self.authorized` is True, you can reasonably expect
OAuth-protected requests to the resource to succeed. If
`self.authorized` is False, you need the user to go through the OAuth
au... | Boolean that indicates whether this session has an OAuth token
or not. If `self.authorized` is True, you can reasonably expect
OAuth-protected requests to the resource to succeed. If
`self.authorized` is False, you need the user to go through the OAuth
authentication dance before OAuth-p... | authorized | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def authorization_url(self, url, request_token=None, **kwargs):
"""Create an authorization URL by appending request_token and optional
kwargs to url.
This is the second step in the OAuth 1 workflow. The user should be
redirected to this authorization URL, grant access to you, and then
... | Create an authorization URL by appending request_token and optional
kwargs to url.
This is the second step in the OAuth 1 workflow. The user should be
redirected to this authorization URL, grant access to you, and then
be redirected back to you. The redirection back can either be specif... | authorization_url | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def fetch_request_token(self, url, realm=None, **request_kwargs):
"""Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response an... | Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response and ready
to be used to construct an authorization url.
:param... | fetch_request_token | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def fetch_access_token(self, url, verifier=None, **request_kwargs):
"""Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a p... | Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a previously set verifier will be reset for your
convenience, or else sign... | fetch_access_token | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def parse_authorization_response(self, url):
"""Extract parameters from the post authorization redirect response URL.
:param url: The full URL that resulted from the user being redirected
back from the OAuth provider to you, the client.
:returns: A dict of parameters extract... | Extract parameters from the post authorization redirect response URL.
:param url: The full URL that resulted from the user being redirected
back from the OAuth provider to you, the client.
:returns: A dict of parameters extracted from the URL.
>>> redirect_response = 'https... | parse_authorization_response | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if "Authorization" in prepared_request.headers:
# If we get redirected to a new host, we sho... |
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
| rebuild_auth | python | requests/requests-oauthlib | requests_oauthlib/oauth1_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py | ISC |
def __init__(self, client_id=None, client=None, token=None):
"""Construct a new OAuth 2 authorization object.
:param client_id: Client id obtained during registration
:param client: :class:`oauthlib.oauth2.Client` to be used. Default is
WebApplicationClient which is usefu... | Construct a new OAuth 2 authorization object.
:param client_id: Client id obtained during registration
:param client: :class:`oauthlib.oauth2.Client` to be used. Default is
WebApplicationClient which is useful for any
hosted application but not mobile or de... | __init__ | python | requests/requests-oauthlib | requests_oauthlib/oauth2_auth.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_auth.py | ISC |
def __call__(self, r):
"""Append an OAuth 2 token to the request.
Note that currently HTTPS is required for all requests. There may be
a token type that allows for plain HTTP in the future and then this
should be updated to allow plain HTTP on a white list basis.
"""
if ... | Append an OAuth 2 token to the request.
Note that currently HTTPS is required for all requests. There may be
a token type that allows for plain HTTP in the future and then this
should be updated to allow plain HTTP on a white list basis.
| __call__ | python | requests/requests-oauthlib | requests_oauthlib/oauth2_auth.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_auth.py | ISC |
def __init__(
self,
client_id=None,
client=None,
auto_refresh_url=None,
auto_refresh_kwargs=None,
scope=None,
redirect_uri=None,
token=None,
state=None,
token_updater=None,
pkce=None,
**kwargs
):
"""Construct a n... | Construct a new OAuth 2 client session.
:param client_id: Client id obtained during registration
:param client: :class:`oauthlib.oauth2.Client` to be used. Default is
WebApplicationClient which is useful for any
hosted application but not mobile or desktop.... | __init__ | python | requests/requests-oauthlib | requests_oauthlib/oauth2_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py | ISC |
def scope(self):
"""By default the scope from the client is used, except if overridden"""
if self._scope is not None:
return self._scope
elif self._client is not None:
return self._client.scope
else:
return None | By default the scope from the client is used, except if overridden | scope | python | requests/requests-oauthlib | requests_oauthlib/oauth2_session.py | https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth2_session.py | ISC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.